andrea andrea - 9 months ago 41
Javascript Question

HTML5 clean canvas with buttons

I have this javascript code, and when i click on the buttons, the canvas cleans.

But when i move the mouse, the canvas shows me what i wrote before, and it doesn't start with a blank canvas

What can i do to start with a blank canvas after i click on the buttons?

Thank you.

<!DOCTYPE html>
<html>
<body>

<canvas id="myCanvas" width="200" height="100" style="border:1px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.</canvas>
<div id="buttons">
<input type="button" id="clear" value="Clear">
<input type="button" onClick="erase()" value="Erase">
</div>



<script>
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");

function getMousePos(canvas, evt) {
var rect = canvas.getBoundingClientRect();
return {
x: evt.clientX - rect.left,
y: evt.clientY - rect.top
};
}

canvas.addEventListener('mousemove',
function(evt){
var mousePos = getMousePos(canvas, evt);
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.strokeStyle = 'red';
ctx.lineTo(mousePos.x,mousePos.y);
ctx.stroke();
}

);

document.getElementById('clear').addEventListener('click', function(){
ctx.clearRect(0, 0, canvas.width, canvas.height);
}, false);


function erase(){
ctx.clearRect(0, 0, canvas.width, canvas.height);
}

</script>

</body>
</html>

K3N K3N
Answer Source

Remember to use beginPath() to also clear the path which stills exists after clearRect() has been used, e.g.:

function(evt){
  var mousePos = getMousePos(canvas, evt);
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  ctx.strokeStyle = 'red';

  ctx.beginPath();     // <- here
  //ctx.moveTo(x, y);  // you will probably also want this at some point

  ctx.lineTo(mousePos.x,mousePos.y);
  ctx.stroke();
}