Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
383 views
in Technique[技术] by (71.8m points)

moving an image across a html canvas

I am trying to move an image from the right to the center and I am not sure if this is the best way.

var imgTag = null;
    var x = 0;
    var y = 0;
    var id;

    function doCanvas()
    {
        var canvas = document.getElementById('icanvas');
        var ctx = canvas.getContext("2d");
        var imgBkg = document.getElementById('imgBkg');
        imgTag = document.getElementById('imgTag');

        ctx.drawImage(imgBkg, 0, 0);

        x = canvas.width;
        y = 40;

        id = setInterval(moveImg, 0.25);

    }

    function moveImg()
    {
        if(x <= 250)
            clearInterval(id);

        var canvas = document.getElementById('icanvas');
        var ctx = canvas.getContext("2d");

        ctx.clearRect(0, 0, canvas.width, canvas.height);

        var imgBkg = document.getElementById('imgBkg');
        ctx.drawImage(imgBkg, 0, 0);

        ctx.drawImage(imgTag, x, y);

        x = x - 1;
    }

Any advice?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

This question is 5 years old, but since we now have requestAnimationFrame, here's an approach for that using vanilla JavaScript:

var imgTag = new Image();
var canvas = document.getElementById('icanvas');
var ctx = canvas.getContext("2d");
var x = canvas.width;
var y = 0;

imgTag.onload = animate;
imgTag.src = "http://i.stack.imgur.com/Rk0DW.png";   // load image

function animate() {
  ctx.clearRect(0, 0, canvas.width, canvas.height);  // clear canvas
  ctx.drawImage(imgTag, x, y);                       // draw image at current position
  x -= 4;
  if (x > 250) requestAnimationFrame(animate)        // loop
}
<canvas id="icanvas" width=640 height=180></canvas>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...