在HTML5中组合对象

时间:2015-07-28 01:07:40

标签: javascript html html5 canvas elements

我正在与远程另外两个人合作开展一个项目。我们正在尝试将三个对象组合在一起,因此当我们运行我们的Web应用程序时,它会显示一个旋转的风车,一个正方形的蓝色轮廓和一个红色的轨道圆。不幸的是,我不知道在我忽略的语法中是否存在一个小的简单错误,或者我的元素是否与之​​匹配。欢迎任何建议。

<!DOCTYPE html>
<html>
<head>
</head>
<style>
  body {
    margin: 0px;
    padding: 0px;
  }
  #buttons {
    position: absolute;
    top: 5px;
    left: 10px;
  }
  #buttons > input {
    padding: 10px;
    display: block;
    margin-top: 5px;
  }
</style>

<body>
  <canvas id="myCanvas" width="600" height="600"></canvas>
  <div id="buttons">
    <input type="button" id="clear" value="Clear">
  </div>
  <script>
    (function() {

        function init() {
          var canvas = document.getElementById('myCanvas');
          var c = canvas.getContext('2d');
          var w = canvas.width;
          var h = canvas.height;

          var circle = function(color, r) {
            c.fillStyle = color;

            c.beginPath();
            c.arc(0, 0, r, 0, 2 * Math.PI, true);
            c.closePath();

            c.fill();
          }

          var i = 0;
          var redraw = function() {
            c.save();


            c.fillStyle = 'gray';
            c.fillRect(0, 0, w, h);


            c.translate(w / 2, h / 2);


            c.rect(10, 10, 100, 100);
            c.strokeStyle = 'blue';
            c.stroke();


            c.rotate(i / 200);
            c.translate(200, 0);


            circle('red', 10);

            c.restore();

            i++;

            c.translate(100, 100);
            var rotateAngle = 0.01;


            function draw(time) {

              c.clearRect(-100, -100 canvas.width, canvas.height);
              c.beginPath();
              c.fillStyle = "red";
              c.moveTo(100, 0);

              for (var angle = 0; angle < 2 * Math.PI; angle += 0.01) {
                var x = 100 * Math.cos(2 * angle) * Math.cos(angle);
                var y = 100 * Math.cos(2 * angle) * Math.sin(angle);
                c.lineTo(x, y);
              }

              c.fill();
              c.rotate(rotateAngle);
              requestAnimationFrame(redraw);
            };

            requestAnimationFrame(redraw);

            function speedUpdate(factor) {
              rotateAngle = factor * rotateAngle;
            }

          }
          window.addEventListener('load', init, false);

        }());
    }
  </script>
  </head>
</body>
</html>

0 个答案:

没有答案