添加控件以操纵Javascript Canvas中的动画

Adding controls to manipulate Animation in Javascript Canvas

本文关键字:动画 Canvas Javascript 控件 操纵 添加      更新时间:2024-03-13

我正在学习使用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>

您可以在html中添加2个按钮,如下所示:

<input type="button" value="+" id="btnAdd">

在javascript中,将按钮绑定到点击事件,如下所示:

document.getElementById('btnAdd').addEventListener('click', function(event) {
//Here you do your logic
speed++;
});

为了速度,你也要做同样的事情;

编辑:工作FIDDLE