相对于当前位置在画布中一起移动多个对象

时间:2019-03-01 18:41:27

标签: javascript html5 animation canvas

我有一个显示多个图像的canvas元素。我试图实现的是,当我单击按钮时,它应该在X坐标中移动200个位置。我设法移动了第二张图像,但是第一张图像没有移动。并且图像必须按照各自的当前位置移动。我在这里附加了我的JavaScript。

 $(window).on('load', function () {
    imageContent(200);
});
function imageContent(x) {
    var posX = x;
    var imgArray = ['http://via.placeholder.com/200x200?text=first', 'http://via.placeholder.com/200x200?text=second'];
    $.each(imgArray, function (i, l) {
        var img = new Image();
        img.onload = function () {
            var x = 0;

            myCanvas(img, i * posX);
        };
        img.src = l;
    });
}
function myCanvas(img, x) {
    var c = document.getElementById("myCanvas");
    var ctx = c.getContext("2d");

    var last_ts = -1
    var speed = 0.1

    function renderScene() {
        ctx.beginPath();
        ctx.drawImage(img, x, 0);
    }
    function fly(ts) {
        if (last_ts > 0) {
            x += speed * (ts - last_ts)
        }
        last_ts = ts

        if (x < 200) {

            imageContent(x);
            requestAnimationFrame(fly);
        }
    }
    renderScene();
    $('#movebutton').click(function () {
        x = 0;
        requestAnimationFrame(fly);
    });

}

Here is the codepen。如果有人可以帮助我,那就太好了。

1 个答案:

答案 0 :(得分:1)

修改:实现并排移动

我稍微修改了您的代码,并删除了jQuery。看看这是否是您想要达到的效果:

var imgArr = [],
  c = document.getElementById("myCanvas"),
  ctx = c.getContext("2d"),
  last_ts = -1,
  speed = 0.1,
  x = 0

window.onload = function() {
  [
    'http://via.placeholder.com/200x200?text=first',
    'http://via.placeholder.com/200x200?text=second'
  ].forEach(function(obj, idx) {
    var img = new Image()
    img.onload = function() {
      drawImage(img, idx * 200, 0)
    }
    img.src = obj
    imgArr.push(img)
  })
}

function drawImages(x) {
  ctx.clearRect(0, 0, c.width, c.height)
  imgArr.forEach(function(obj, idx) {
    drawImage(obj, x + idx*200, 0)
  })
}

function drawImage(img, x, y) {
  ctx.beginPath()
  ctx.drawImage(img, x, y)
}

function fly(ts) {
  if (last_ts > 0) {
    x += speed * (ts - last_ts)
  }

  last_ts = ts

  if (x < 200) {
    drawImages(x)
    requestAnimationFrame(fly)
  }
}

document
  .getElementById('movebutton')
  .addEventListener('click', function() {
    x = 0
    fly()
  }, false)
canvas {
  border: 1px solid red;
}
<canvas id="myCanvas" width="960" height="600"></canvas>
<button id="movebutton">Move</button>