简体   繁体   中英

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; 

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()

 <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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM