首先,为什么要在帧渲染功能中加载图像 - 如果禁用缓存,它将每帧请求一个图像!
我重写了脚本以使动画线性和平滑,您可以编辑速度变量来调整移动速度。
$(window).on('load', function () { var img = new Image(); img.onload = function () { myCanvas(img); }; img.src = 'http://via.placeholder.com/200x200?text=first'; }); function myCanvas(img) { var c = document.getElementById("myCanvas"); var ctx = c.getContext("2d"); var x = 0; var last_ts = -1 var speed = 0.1 function renderScene() { ctx.clearRect(0, 0, c.width, c.height); ctx.closePath(); 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) { renderScene() requestAnimationFrame(fly); } } renderScene() $('#movebutton').click(function () { x = 0; requestAnimationFrame(fly); }); }