简体   繁体   中英

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: 在此处输入图片说明

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.

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.

You need to re-render the frame. Here's some code from an incomplete game I wrote:

var main = function () {
  var now   = Date.now(),
      delta = now - then;

  update(delta / 1000);
  render();

  then = now;

  // Request to do this again ASAP
  requestAnimationFrame(main);
};

GitHub repo code

My render function contains the context.drawImg() work (getting properly re-rendered), and that's similar to your moveImage function.

Edit: A little explanation. The image traces are previous renderings of the your image at each updated position. Without the frame itself being reset, each move of the image is preserved on the screen, giving the appearance of a trail of images.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM