我正在学习使用Html5 Canvas。如何添加两个按钮来降低或提高画布中动画方块的速度?我是编程的初学者,所以我试着保持简单。
<!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>
答案 0 :(得分:1)
您可以在html中添加2个按钮,如下所示:
<input type="button" value="+" id="btnAdd">
并在javascript中,将按钮绑定到click事件,如下所示:
document.getElementById('btnAdd').addEventListener('click', function(event) {
//Here you do your logic
speed++;
});
你为速度做同样的事情 - ;
修改:工作FIDDLE