gpt4 book ai didi

javascript - 如何暂停动画

转载 作者:可可西里 更新时间:2023-11-01 13:41:17 26 4
gpt4 key购买 nike

我让这张图片在 Canvas 上移动,但没有一种方法可以阻止它移动。我设置了 setInterval 来移动并稍后通过 clearInterval 清除 Interval 以停止运动,但似乎它不起作用

<html>
<head>
<script type="application/javascript">
var ctx = null;
var x_icon = 0;
var y_icon = 0;
var stepX = 1;
var stepY = 1;
var size_x = 221;
var size_y = 184;
var canvas_size_x = 800;
var canvas_size_y = 600;
var anim_img = null;



function draw() {
var canvas = document.getElementById("canvas");
ctx = canvas.getContext("2d");
anim_img = new Image(size_x, size_y);
anim_img.onload = function() {
var myvar = setInterval(myAnimation, 10);
function stopMove() {
clearInterval(myVar);
}

}
anim_img.src = 'image/download.jpg';
}

function myAnimation() {
ctx.clearRect(0, 0, canvas_size_x, canvas_size_y);
if (x_icon < 0 || x_icon > canvas_size_x - size_x) {stepX = -stepX; }
if (y_icon < 0 || y_icon > canvas_size_y - size_y) {stepY = -stepY; }
x_icon += stepX;
y_icon += stepY;
ctx.drawImage(anim_img, x_icon, y_icon);
}



</script>
</head>
<body onload="draw();">
<canvas id="canvas" width="800" height="600" style="border:solid 1px;"></canvas>
<button onmousedown="stopMove()">STOP</button>
</body>
</html>

我希望通过单击“停止”按钮停止 download.jpg 的运动,但它不起作用

最佳答案

正如@Snel23 所说,您需要从draw() 上下文中提取stopMove()myvar

  var ctx = null;
var x_icon = 0;
var y_icon = 0;
var stepX = 1;
var stepY = 1;
var size_x = 221;
var size_y = 184;
var canvas_size_x = 800;
var canvas_size_y = 600;
var anim_img = null;
var myvar = null; // moving interval handle outside draw()



function draw() {
var canvas = document.getElementById("canvas");
ctx = canvas.getContext("2d");
anim_img = new Image(size_x, size_y);
anim_img.onload = function()
{
myvar = setInterval(myAnimation, 10);
}
anim_img.src = 'image/download.jpg';
}
function stopMove() {
clearInterval(myVar);
}


function myAnimation() {
ctx.clearRect(0, 0, canvas_size_x, canvas_size_y);
if (x_icon < 0 || x_icon > canvas_size_x - size_x) {stepX = -stepX; }
if (y_icon < 0 || y_icon > canvas_size_y - size_y) {stepY = -stepY; }
x_icon += stepX;
y_icon += stepY;
ctx.drawImage(anim_img, x_icon, y_icon);
}

关于javascript - 如何暂停动画,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57752322/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com