2012-03-20 54 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