2012-03-20 53 views
2

我需要將圖像浮在HTML5和JavaScript中的幫助。我一直在搜索,並沒有發現任何東西。我可以在屏幕上繪製形狀,但我不知道如何爲它們製作動畫。 我想要幾個不同的圖像從不同的方向浮在畫布上。 有人可以幫助我嗎? 4小時谷歌搜索我所能做的就是後這使用HTML5和canvas製作動畫圖像

<script type = "Text/JavaScript"> 
       function Animate(){ 
       var canvas=document.getElementById("myCanvas"); 
       var ctx=canvas.getContext("2d"); 

       var img = new Image(); 

       img.onload = function() 
       { 
        ctx.drawImage(img,20,20,300,300); 

       }; 
       img.src = "vb.png"; 
       } 
      </script> 
    </head> 
<body> 
<canvas id="myCanvas" height="200" width="800"></canvas> 
<br><button onclick="Animate();">Restart</button> 

似乎有成爲很多教程上的動畫造型,但我想加載了我自己的照片,並讓它們在飛行到畫布上。

+0

看看[MDN約變換(https://developer.mozilla.org/en/Canvas_tutorial/Transformations)。它有你需要的一切。 – 2012-03-20 17:46:49

回答

11

嘗試帆布動畫的此非常基本的演示:

http://jsfiddle.net/bDQ6b/2/

window.addEventListener('load', function() { 
    var 
    img = new Image, 
    ctx = document.getElementById('myCanvas').getContext('2d'); 

    img.src = 'http://www.gravatar.com/avatar/a1f80339c0cef95be6dc73e0ac510d5d?s=32&d=identicon&r=PG'; 
    img.addEventListener('load', function() { 

    var interval = setInterval(function() { 
     var x = 0, y = 0; 

     return function() { 
     ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height); 
     ctx.drawImage(img, x, y); 

     x += 1; 
     if (x > ctx.canvas.width) { 
      x = 0; 
     } 
     }; 
    }(), 1000/40); 
    }, false); 
}, false); 

有很多這可雖然做的更好。例如:

  • 使用requestAnimationFrame代替間隔

  • 在使用速度和時間差的更方便的方法

  • 預加載的圖像(從最後到當前幀),而不是固定的增量

  • and more more

但是,因爲所有這些都會使示例方式太複雜,我會保持原樣,並希望在學習的同時閱讀這些主題。

2

要使用畫布動畫,您需要記錄對象的位置,然後將其增加到新框架上setInterval(draw, 1000/25);允許您在指定的時間間隔後運行函數。每次渲染新幀時,您都可以使用此功能更新頁面上對象的位置。

例如:

function draw() { playersShip.move(); }

當移動功能遞增或遞減x和/或你的對象的y座標。這條線在指定的座標處繪製指定的圖像(每個幀被渲染時更新)。

ctx.drawImage(shipImage, playersShip.position.x, playersShip.position.y);

這將是,如果你的構建遊戲或類似的物體的運動,從你的幀率隔離是個好主意。如果您需要,我可以提供更多深入的樣本。

使用這個想法,你應該能夠創建你的圖像的動畫。

2

以下是HTML5畫布中簡單的示例反射球動畫。

<body> 
<canvas id="Canvas01" width="400" height="400" style="border:5px solid #FF9933; margin-left:10px; margin-top:10px;"></canvas> 

<script> 
    var canvas = document.getElementById('Canvas01'); 
    var ctx = canvas.getContext('2d'); 
    var p = {x:25, y:25}; 
    var velo=6, corner=30, rad=20; 
    var ball={x:p.x, y:p.y}; 

    var moveX=Math.cos(Math.PI/180*corner) * velo; 
    var moveY=Math.sin(Math.PI/180*corner) * velo; 


    function DrawMe() { 
    ctx.clearRect(0,0,canvas.width, canvas.height); 

    if(ball.x>canvas.width-rad || ball.x<rad) moveX=-moveX; 
    if(ball.y>canvas.height-rad || ball.y<rad) moveY=-moveY; 

    ball.x +=moveX; 
    ball.y +=moveY; 

    ctx.beginPath(); 
    ctx.fillStyle = 'blue'; 
    ctx.arc(ball.x, ball.y, rad, 0 , Math.PI*2,false); 
    ctx.fill(); 
    ctx.closePath(); 
    } 

    setInterval(DrawMe,30); 

</script> 
</body> 

你可以自己在這裏試試吧:http://codetutorial.com/examples-canvas/canvas-examples-bounce-ball