Search Topic Here

Sunday, 29 December 2013

Oscillator


code

<!DOCTYPE HTML>
<html>
  <head>
    <style>
      body {
        margin: 0px;
        padding: 0px;
      }
    </style>
  </head>
  <body>
    <canvas id="myCanvas" width="578" height="500"></canvas>
    <script>
      window.requestAnimFrame = (function(callback) {
        return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame ||
        function(callback) {
          window.setTimeout(callback, 1000 / 60);
        };
      })();

      function drawSpring(canvas, context) {
        context.beginPath();
        context.moveTo(0, 0);

        for(var y = 0; y < 200; y++) {
          // Sine wave equation
          var x = 30 * Math.sin(y / 9.05);
          context.lineTo(x, y);
        }
      }
      function drawWeight(canvas, context) {
        var size = 100;
        context.save();
        context.fillStyle = 'red';
        context.fillRect(-size / 2, 0, size, size);
        context.restore();
      }
      function animate(canvas, theta, lastTime) {
        var context = canvas.getContext('2d');

        // update
        var time = (new Date()).getTime();
        var timeDiff = time - lastTime;
        theta += timeDiff / 400;
        lastTime = time;

        var scale = 0.8 * (Math.sin(theta) + 1.3);

        // clear
        context.clearRect(0, 0, canvas.width, canvas.height);

        // draw
        context.save();
        context.translate(canvas.width / 2, 0);

        context.save();
        context.scale(1, scale);
        drawSpring(canvas, context);
        context.restore();

        context.lineWidth = 6;
        context.strokeStyle = '#0096FF';
        // blue-ish color
        context.stroke();

        context.translate(0, 200 * scale);
        drawWeight(canvas, context);
        context.restore();

        // request new frame
        requestAnimFrame(function() {
          animate(canvas, theta, lastTime);
        });
      }
      var canvas = document.getElementById('myCanvas');
      var theta = 0;
      var time = (new Date()).getTime();
      animate(canvas, theta, time);

    </script>
  </body>
</html>

No comments:

Post a Comment