I'm trying to add a clear button to erase the canvas of union draw
I thought clearRect should be able to do that. I tried with:
function clearCanvas() {
clearRect(0,0,canvas.width,canvas.height);
}
or
function clearCanvas(x,y,w,h) {
ctx.clearRect(x,y,w,h);
}
...but it doesn't work, why?
The problem with using ctx.clearRect(0,0,canvas.width,canvas.height) is that if you have modified the transformation matrix you likely will not be clearing the canvas properly.
The solution? Reset the transformation matrix prior to clearing the canvas:
// Store the current transformation matrix ctx.save();
// Use the identity matrix while clearing the canvas ctx.setTransform(1, 0, 0, 1, 0, 0); ctx.clearRect(0, 0, canvas.width, canvas.height);
// Restore the transform ctx.restore();
Edit:
Chrome responds well to: context.clearRect ( x , y , w , h ); but IE9 seems to completely ignore this instruction. IE9 seems to respond to: canvas.width = canvas.width; but it doesn't clear lines, just shapes, pictures and other objects.
So if you have a canvas and context created like this:
var canvas = document.getElementById('my-canvas'); var context = canvas.getContext('2d');
You can use a method like this:
function clearCanvas(context, canvas) { context.clearRect(0, 0, canvas.width, canvas.height); var w = canvas.width; canvas.width = 1; canvas.width = w; }
Edit2:
use this code to check if the browser supports it:
function checkSupported() {
canvas = document.getElementById('canvas');
if (canvas.getContext){
ctx = canvas.getContext('2d');
// Canvas is supported
} else {
// Canvas is not supported
alert("We're sorry, but your browser does not support the canvas tag. Please use any web browser other than Internet Explorer.");
}
}
And to make this code execute when the web page loads, adjust the body tag so it reads like this:
<body onload="checkSupported();">