VA31 VA31 - 11 months ago 38
HTML Question

html canvas - issue with moving image

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

<!DOCTYPE html>
<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.moveTo(50, 300);
context.lineTo(950, 300);
var x=50;
setInterval(function() {
x = x+20;
}, 1000);
<body onload="startDrawing()">
<canvas id="myCanvas" width="1000" height="1000">

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.



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;
}, 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.