主要思想:
首先要準備壹張有連續幀的圖片,然後利用HTML5 Canvas的draw方法在不同的時間間隔繪制不同的幀,這樣看起來就像動畫在播放。
關鍵技術點:
JavaScript 函數setTimeout()有兩個參數,第壹個是參數可以傳遞壹個JavaScript方法,
另外壹個參數代表間隔時間,單位為毫秒數。代碼示例:
setTimeout( update, 1000/30);
Canvas的API-drawImage()方法,需要指定全部9個參數:
ctx.drawImage(myImage, offw, offh, width,height, x2, y2, width, height);
其中offw, offh是指源圖像的起始坐標點,width, height表示源圖像的寬與高,x2,y2表
示源圖像在目標Canvas上的起始坐標點。
<!DOCTYPE?html>?<html>?
<head>?
<meta?patible?browser.");?
return;?
}?
//?get?2D?context?of?canvas?and?draw?rectangel?
ctx?=?canvas.getContext("2d");?
ctx.fillStyle="black";?
ctx.fillRect(0,?0,?canvas.width,?canvas.height);?
myImage?=?document.createElement('img');?
myImage.src?=?"../robin.png";?
myImage.onload?=?loaded();?
}?
function?loaded()?{?
imageReady?=?true;?
setTimeout(?update,?1000/30);?
}?
function?redraw()?{?
ctx.clearRect(0,?0,?460,?460)?
ctx.fillStyle="black";?
ctx.fillRect(0,?0,?460,?460);?
//?find?the?index?of?frames?in?image?
var?height?=?myImage.naturalHeight/5;?
var?width?=?myImage.naturalWidth/5;?
var?row?=?Math.floor(frame?/?5);?
var?col?=?frame?-?row?*?5;?
var?offw?=?col?*?width;?
var?offh?=?row?*?height;?
//?first?robin?
px?=?px?-?5;?
py?=?py?-?5;?
if(px?<?-50)?{?
px?=?300;?
}?
if(py?<?-50)?{?
py?=?300;?
}?
//var?rate?=?(frame+1)?/22;?
//var?rw?=?Math.floor(rate?*?width);?
//var?rh?=?Math.floor(rate?*?height);?
ctx.drawImage(myImage,?offw,?offh,?width,?height,?px,?py,?width,?height);?
//?second?robin?
x2?=?x2?-?5;?
y2?=?y2?+?5;?
if(x2?<?-50)?{?
x2?=?300;?
y2?=?0;?
}?
ctx.drawImage(myImage,?offw,?offh,?width,?height,?x2,?y2,?width,?height);?
}?
function?update()?{?
redraw();?
frame++;?
if?(frame?>=?22)?frame?=?0;?
setTimeout(?update,?1000/30);?
}?
</script>?
</head>?
<body>?
<h1>HTML?Canvas?Animations?Demo?-?By?Gloomy?Fish</h1>?
<pre>Play?Animations</pre>?
<div?id="my_painter">?
<canvas?id="animation_canvas"></canvas>?
</div>?
</body>?
</html>