Reputation: 27
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?
Upvotes: 0
Views: 6809
Reputation: 1063
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.
Upvotes: 0
Reputation: 53246
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()
.
Upvotes: 3