画布摆动图像

时间:2014-03-24 17:22:00

标签: javascript html5 canvas

我正试图让图像振荡。但我有一些问题。我正在使用这个教程http://www.html5canvastutorials.com/advanced/html5-canvas-oscillation-animation/

我尝试更改教程的第55-61行来加载图像src。但它没有显示任何东西。

有什么建议吗?

<canvas id="myCanvas" width="578" height="200"></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 drawRectangle(myRectangle, context) {
        context.beginPath();
        context.rect(myRectangle.x, myRectangle.y, myRectangle.width, myRectangle.height);
        context.fillStyle = '#8ED6FF';
        context.fill();
        context.lineWidth = myRectangle.borderWidth;
        context.strokeStyle = 'black';
        context.stroke();
      }
      function animate(myRectangle, canvas, context, startTime) {
        // update
        var time = (new Date()).getTime() - startTime;
        var amplitude = 150;

        // in ms
        var period = 2000;
        var centerX = canvas.width / 2 - myRectangle.width / 2;
        var nextX = amplitude * Math.sin(time * 2 * Math.PI / period) + centerX;
        myRectangle.x = nextX;

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

        // draw
        drawRectangle(myRectangle, context);

        // request new frame
        requestAnimFrame(function() {
          animate(myRectangle, canvas, context, startTime);
        });
      }
      var canvas = document.getElementById('myCanvas');
      var context = canvas.getContext('2d');

      var myRectangle = new Image();
                        myRectangle.src = "http://www.skilledsoldiers.com/e107_plugins/aacgc_gamelist/icons/dota2_icon.png";
                        myRectangle.onload = function()
      };

      drawRectangle(myRectangle, context);

      // wait one second before starting animation
      setTimeout(function() {
        var startTime = (new Date()).getTime();
        animate(myRectangle, canvas, context, startTime);
      }, 1000);
    </script>

1 个答案:

答案 0 :(得分:1)

您需要使用context.drawImage,而不是尝试使用图片绘制矩形。

function drawImage(myRectangle, context) {
    context.drawImage(myRectangle.img, myRectangle.x, myRectangle.y, myRectangle.width, myRectangle.height);   
}

看到这个小提琴:http://jsfiddle.net/fb4vS/