在HTML5 Canvas中停止移动图像

时间:2014-11-30 20:01:03

标签: javascript image html5-canvas

我是HTML5中canvas元素的新手。

我想要做的是将图像从屏幕的右侧移动到左侧,一旦它到达左侧,我希望它从右侧再次开始。我只想要它做2/3次然后停止。

我尝试添加一个for循环,以便限制迭代,但这不成功。

任何帮助都将不胜感激。

继承我的代码:

<canvas id="myCanvas" width="600" height="400"></canvas> 
 <script>
  window.addEventListener('load', function () {
  var
    img = new Image,
    ctx = document.getElementById('myCanvas').getContext('2d');

  img.src = 'pies.png';
  img.addEventListener('load', function () {

    var interval = setInterval(function() {
      var x = 650, y = 194;

      return function () {
        ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
        ctx.drawImage(img, x, y);

        x -= 1;
        if (x < -500) {
          x = 650;
        }
      };
    }(), 1000/40);
  }, false);
}, false);


    </script>

1 个答案:

答案 0 :(得分:0)

一种方法是指定向左移动的最大数量:

// allow leftward moves = 2 1/2 time the canvas width 
// (plus an allowance for the image width)

var maxMoves = (canvas.width+image.width) *2.5; 

然后只倒计时maxMoves直到零。在零时,停止动画:

var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var cw=canvas.width;
var ch=canvas.height;
ctx.fillStyle='skyblue';

var currentX=cw;
var delay=16; // 16ms between moves
var continueAnimating=true;
var nextMoveTime,maxMoves;

var img=new Image();
img.onload=start;
img.src="https://dl.dropboxusercontent.com/u/139992952/multple/sun.png";
function start(){

  maxMoves=(cw+img.width)*2.5;

  nextMoveTime=performance.now();

  requestAnimationFrame(animate);

}


function animate(currentTime){

  if(continueAnimating){ requestAnimationFrame(animate); }

  if(currentTime<nextMoveTime){return;}

  nextMoveTime=currentTime+delay;
  
  ctx.fillRect(0,0,cw,ch);
  ctx.drawImage(img,currentX,50);

  if(--currentX<-img.width){ currentX=cw; }

  if(--maxMoves<0){continueAnimating=false;}

}
body{ background-color: ivory; padding:10px; }
#canvas{border:1px solid red;}
<p>Stop animating after 2 1/2 "sunrises"</p>
<canvas id="canvas" width=300 height=300></canvas>