【发布时间】:2019-07-23 19:59:59
【问题描述】:
我有一个画布元素,其中显示了多个图像。我想要实现的是,当我单击一个按钮时,它应该在 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。如果有人能帮助我,那就太好了。
【问题讨论】:
标签: javascript html animation canvas