ZeppRock
ZeppRock

Reputation: 1148

How do i clear a canvas?

By some starnge reason it does not work for me to do the

canvas.width = canvas.width;

here is my code:

function startDraw(){
document.getElementById('PaintArea').setAttribute('onmousemove', 'getMouse(event)');
}
function stopDraw(){
document.getElementById('PaintArea').setAttribute('onmousemove', '');
}
function Paint(){
var Size = document.getElementById('Size').value;
var Opacity = document.getElementById('opa').value;
var color = document.getElementById('color').value;
canvas = document.getElementById('PaintArea');
if(canvas.getContext){
    var ctx = canvas.getContext('2d');

    ctx.fillStyle = color;
    ctx.globalAlpha = Opacity;
    ctx.beginPath();
    ctx.arc(musX-10, musY-10, Size, 0, Math.PI*2); 
    ctx.closePath();
    ctx.fill();
}
}

function clear(){       
canvas.width = canvas.width;
}

function getMouse(event) {
musY = event.clientY;
musX = event.clientX;
Paint();
}

button:

<button onclick="clear()">Clear</button>

in the chrome console it says : "document.clear() is deprecated. This method doesn't do anything."

i also have these global varables:

var musX;
var musY;
var canvas; 

Upvotes: 1

Views: 131

Answers (2)

PointedEars
PointedEars

Reputation: 14980

<button onclick="clear()">Clear</button>

in the chrome console it says: "document.clear() is deprecated. This method doesn't do anything."

You have run into the legacy scope chain augmentation problem.

In this case, clear is the name of a property of the object referred to by the host-defined document property, which is in the scope chain of the code in the event-handler attribute value. In order to access your functions reliably (cross-browser), you need to circumvent the scope chain.

Possible solutions:

  1. Make your functions methods of your own object:

    var myObject = {
      startDraw: function (…) {
        // …
      },
    
      // …
    
      clear: function (…) {
        // …
      }
    };
    
    …
    
    <button onclick="myObject.clear()">Clear</button>
    
  2. Access the global object, whose methods your functions are, directly:

    var _global = this;
    
    // …
    
    function clear ()
    {
      // …
    }
    
    …
    
    <button onclick="_global.clear()">Clear</button>
    

    (You may choose any other variable identifier in place of _global as long as it does not collide with a built-in or host defined symbol. _global is an identifier unlikely to collide.)

Approach 1 is recommended as it reduces the number of user-defined global symbols, thus the likelihood of collision with built-in and host-defined symbols.

Upvotes: 0

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324790

Guessing based on the error message... try this:

<button onclick="window.clear();">Clear</button>

If that works, consider using a less vague function name, something like clearCanvas()

Upvotes: 1

Related Questions