html5 – 在html画布上移动图像

前端之家收集整理的这篇文章主要介绍了html5 – 在html画布上移动图像前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我试图将图像从右侧移动到中心,我不确定这是否是最佳方式.
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);

        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,canvas.width,canvas.height);

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

        ctx.drawImage(imgTag,x,y);

        x = x - 1;
    }

任何建议?

解决方法

这个问题是5年之久,但由于我们现在有了requestAnimationFrame,这里有一个使用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,canvas.height);  // clear canvas
  ctx.drawImage(imgTag,y);                       // draw image at current position
  x -= 4;
  if (x > 250) requestAnimationFrame(animate)        // loop
}
<canvas id="icanvas" width=640 height=180></canvas>
原文链接:https://www.f2er.com/html5/168323.html

猜你在找的HTML5相关文章