【发布时间】:2019-07-23 13:25:55
【问题描述】:
我有一个正在渲染图像的画布对象。当用户单击按钮时,图像将向右移动。我的问题是这个动作不顺畅。图像只是跳转到指定位置。我怎样才能使这个动作平滑? This is the codepen example谁能帮帮我?
$(window).on('load', function () {
myCanvas();
});
function myCanvas() {
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
var x = 0;
function fly() {
ctx.clearRect(0, 0, c.width, c.height);
ctx.closePath();
ctx.beginPath();
var img = new Image();
img.onload = function () {
ctx.drawImage(img, x, 0);
};
img.src = 'http://via.placeholder.com/200x200?text=first';
}
fly();
$('#movebutton').click(function () {
for (i = 0; i < 200; i++) {
x = i;
requestAnimationFrame(fly);
}
});
}
<canvas id="myCanvas" width="960" height="600"></canvas>
<button id="movebutton">Move</button>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
【问题讨论】:
-
这是一个复杂的话题。您正在寻找的东西称为“插值”。您必须考虑帧速率等。
-
看来我需要对它进行彻底的研究......
-
我花了很长时间研究,但是如果你没有时间并且可以使用它,我建议你这个 JS 库:createjs.com/easeljs
-
我发现这个帖子很有帮助stackoverflow.com/questions/43626268/…
标签: javascript html animation canvas requestanimationframe