[英]Html5 canvas animation. How to reset rectangle when it hits the end
嘿,我正在尝试一些 html5 动画,到目前为止我有一个方块,每当我按下按钮时它就会“下落”。 我想知道当它跌至底部并再次跌落时,如何让它回到顶部。 我目前的代码是:
<html>
<head>
</head>
<body>
<canvas id="myCanvas" width="200" height="400" style="border:1px solid black;">
Your browser does not support the HTML5 canvas tag.
</canvas>
<script>
function draw (x,y){
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.save();
var side = 10
var up = 10
ctx.clearRect(0,0,200,400);
ctx.fillStyle = "#FF0000";
ctx.fillRect(x,y,up,side);
ctx.restore();
y += 5;
var loopTimer = setTimeout('draw('+x+','+y+')',30);
}
</script>
<button onclick="draw(0,0)">draw</button>
</body>
</html>
使用变量y
,您可以简单地检查它是否低于画布高度的高度。
if( y > c.height ){ // use the canvas height, not the context height
y = 0;
}
此外,您当前调用计时器的方式有点低效。 代替 :
var loopTimer = setTimeout('draw('+x+','+y+')',30);
我会推荐
var loopTimer = setTimeout(function(){ draw(x,y); },30);
这是一个工作示例: http : //jsfiddle.net/vwcdpLvv/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.