VA31 VA31 - 7 months ago 13
HTML Question

html canvas - issue with moving image

I am learning html canvas and below is my html code.

<!DOCTYPE html>
<html>
<head>
<script language="javascript">
function moveImage(x) {
var context = document.getElementById('myCanvas').getContext("2d");
var img = new Image();
img.onload = function () {
context.drawImage(img, x, 259);
}
img.src = "flower.jpg";
}

function startDrawing() {
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
context.beginPath();
context.moveTo(50, 300);
context.lineTo(950, 300);
context.stroke();
var x=50;
setInterval(function() {
x = x+20;
moveImage(x);
}, 1000);
}
</script>
</head>
<body onload="startDrawing()">
<canvas id="myCanvas" width="1000" height="1000">
</body>
</html>


Please find the below output from this code:enter image description here

How can I remove the traces of 'older frames' (of the flower), as you could see lots of flowers while it is moving from left to right in the screen shot ? Please help the code changes required.

Thanks.

Answer

The problem is you aren't clearing the canvas before drawing on it again. You can clear it using clearRect.

setInterval(function() {
  // Clear the canvas
  context.clearRect(0, 0, canvas.width, canvas.height);
  x += 20;
  moveImage(x);
}, 1000);

Keep in mind that this will clear the entire canvas. If you're rendering anything else, you'll want to redraw it after the clear.

Comments