简体   繁体   中英

Clear canvas button

I am trying to create a button to clear a canvas, but with no success.

My codes for this

JS

function clearcanvas1(){
ctx.clearRect(0, 0, canvas.width, canvas.height); 
var w = canvas.width; canvas.width = 1; canvas.width = w; 
}

HTML

<button onmouseover="clearcanvas1()">clear</button>

I have tried other options such as

canvas.width = canvas.width;

and

ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);

At the moment I have substituted the clear button for a location.reload function, but it upsets a secondary canvas on the same page which I want to operate independently. How can i achieve this?

You don't seem to be getting the canvas element within your function (or indeed its context)...

function clearcanvas1()
{
    var canvas = document.getElementById('canvas'),
        ctx = canvas.getContext("2d");
    ctx.clearRect(0, 0, canvas.width, canvas.height);
}

Obviously, you'll need to update document.getElementById() to represent the correct ID for your markup, or you can use document.getElementsByTagName() .

on the button call the below function

function clearall()
{
    var canvas=document.getElementById("canvas+id");
    var context=canvas.getContext("2d");
    context.clearRect(0,0,canvas.width,canvas.height);
}

hope this will help you. Be aware this function will clear everything in the canvas.

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