[英]can you animate an image on a canvas
由於我正在學習html和javascript,因此我想知道是否可以在畫布上並排放置運動圖像? 如果是這樣,怎么辦呢???
到目前為止,這是我要做的。
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="ann.css" />
<script>
window.onload = animate;
var canvas=document.getElementById('mycanvas');
var ctx=canvas.getContext('2d');
function animate()
{
window.setInterval(slide,1000);
}
function slide()
{
var obj = document.getElementById("ball");
var left = obj.style.left;
if(left === ''){
left = 0;
}
var wartosc = parseInt(left, 10);
obj.style.left = (wartosc + 10) + "px";
}
function Loop() {
if (left>canvas.width){
var right = obj.style.right;
if(right === ''){
right = 0;
}
var wartosc = parseInt(right, 10);
obj.style.right = (wartosc + 10) + "px";
}
</script>
<style>
#ball
{
position: relative;
left: 1px;
}
#mycanvas {border:1px solid #000000}
</style>
</head>
<body>
<img src="ball.gif" id="ball" alt="Usmiech" width="30" height="30" />
<canvas id=mycanvas width=600 height=50>Canvas Not Supported
</canvas>
<body>
</html>
我想要做的是將圖像包含在畫布中,並從左向右移動,到達畫布的右側時,圖像繼續向左返回,依此類推。
但是我的問題是是否可以解決,我不知道如何將圖像放置在畫布上,一旦圖像到達畫布末端,就無法使圖像向右移動。 我認為問題出在我的循環函數上,可以嘗試使它移到右邊。
從小提琴鏈接中可以看到,當我刪除循環功能代碼時,它起作用了。 但是,它只會移到左側。
請有人能幫我解決嗎? :)
您可以為spritesheet而不是.gif
設置動畫。
序列很簡單:
requestAnimationFrame
循環中)。 這是帶注釋的代碼和演示:
var canvas=document.getElementById("canvas"); var ctx=canvas.getContext("2d"); var cw=canvas.width; var ch=canvas.height; // timing related vars var nextTime=0; var spriteCount=7; var interval=700/spriteCount; // sprite related vars var sIndex=0; var sw=60; var sh=95; var animationOn=true; // current x,y position of sprite var x=100; var y=100; // load the spritesheet var ss=new Image(); ss.onload=start; ss.src="http://i59.tinypic.com/jpkk6f.jpg"; function start(){ // draw the first sprite ctx.drawImage(ss,sIndex*sw,0,sw,sh,x,y,sw,sh); // start the animation loop requestAnimationFrame(animate); } function animate(time){ // wait for the specified interval before drawing anything if(time<nextTime || !animationOn){requestAnimationFrame(animate); return;} nextTime=time+interval; // draw the new sprite ctx.clearRect(0,0,cw,ch); ctx.drawImage(ss,sIndex*sw,0,sw,sh,x,y,sw,sh); // get the next sprite in sequence if(++sIndex>=spriteCount){sIndex=0;} // advance the sprite rightward x+=5; if(x>cw){x=-sw-10;} // request another animation loop requestAnimationFrame(animate); }
body{ background-color: ivory; } #canvas{border:1px solid red; margin:0 auto; }
<canvas id="canvas" width=300 height=300></canvas>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.