添加控件以在Javascript画布中操纵动画
我正在学习使用Html5画布。如何添加两个按钮来降低或提高画布中已设置动画的正方形的速度?我是一个编程新手,所以我尽量让它简单添加控件以在Javascript画布中操纵动画,javascript,html,canvas,Javascript,Html,Canvas,我正在学习使用Html5画布。如何添加两个按钮来降低或提高画布中已设置动画的正方形的速度?我是一个编程新手,所以我尽量让它简单 <!DOCTYPE HTML> <html> <head> <style> body { margin: 0px; padding: 0px; } </style> </head> <body> <c
<!DOCTYPE HTML>
<html>
<head>
<style>
body {
margin: 0px;
padding: 0px;
}
</style>
</head>
<body>
<canvas id="ex1" width="525" height="200" style = "border: 5px solid black;"</canvas>
<script>
var x = 0;
var y = 15;
var speed = 10;
function animate() {
reqAnimFrame = window.mozRequestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.msRequestAnimationFrame ||
window.oRequestAnimationFrame
;
reqAnimFrame(animate);
x += speed;
if(x <= 0 || x >= 475)
{
speed = -speed;
}
draw();
}
function draw() {
var canvas = document.getElementById("ex1");
var context = canvas.getContext("2d");
context.clearRect(0, 0, 600, 170);
context.fillStyle = "#ff00ff";
context.fillRect(x, y, 40, 40);
}
animate();
</script>
<p></p>
<audio controls>
<source src="fortworth.ogg" type="audio/ogg">
<source src="fortworth.mp3" type="audio/mpeg">
Your browser does not support the audio element.
</audio>
</body>
</html>
身体{
边际:0px;
填充:0px;
}
您可以在html中添加2个按钮,如下所示:
<input type="button" value="+" id="btnAdd">
document.getElementById('btnAdd').addEventListener('click', function(event) {
//Here you do your logic
speed++;
});
你对速度做同样的事情--
编辑:工作这似乎是工作,但我的数学在某个地方错了。单击+按钮7次后,它将跳转为负数。例如,我点击+键到6,7,8,9,10,然后跳到-9。看到我哪里出错了吗?啊,负数是因为当你的方块改变方向时!从左到右,速度为正,从右到左,速度为负。我加了一个bool来知道它什么时候运行正常,看看按钮上我的事件,这就是我需要加还是减的地方:我只想加上负数是正常的,因为你在做speed=-speed;我更新了我的评论,以帮助您理解我做得更好。