Canvas 學(xué)習(xí)筆記之動畫 -- by Damon
動畫的基本步驟
- 清空
- 保存狀態(tài)
- 繪制圖形(animated shapes)
- 恢復(fù)狀態(tài)
操控動畫
有安排的更新畫布
- setInterval
- setTimeout
- requestAnimationFrame(cb)
動畫太陽系
function draw() {
ctx.clearRect(0, 0, 300, 300);
ctx.fillStyle = 'rgba(0, 0, 0, 0.4)';
ctx.strokeStyle = 'rgba(0, 153, 255, 0.4)';
ctx.save();
ctx.translate(150, 150);
// earth
var time = new Date();
ctx.rotate(((2 * Math.PI) / 60) * time.getSeconds() + ((2 * Math.PI) / 60000) * time.getMilliseconds());
ctx.translate(105, 0);
ctx.fillRect(0, -12, 50, 24); // Shadow
ctx.drawImage(earth, -12, -12);
// Moon
ctx.save();
ctx.rotate(((2 * Math.PI) / 6) * time.getSeconds() + ((2 * Math.PI) / 6000) * time.getMilliseconds());
ctx.translate(0, 28.5);
ctx.drawImage(moon, -3.5, -3.5);
ctx.restore();
// sun
ctx.restore();
ctx.beginPath();
ctx.arc(150, 150, 105, 0, Math.PI * 2, false); // Earth orbit
ctx.stroke();
ctx.drawImage(sun, 0, 0, 300, 300);
window.requestAnimationFrame(draw);
}
注意坐標(biāo)系的變化闸衫,首先將坐標(biāo)系移到中心,然后保存當(dāng)前狀態(tài)驹针。
繪制地球時蝗蛙,旋轉(zhuǎn)离赫、移動坐標(biāo)系魂迄,然后繪制注服。
繪制月球時禾乘,坐標(biāo)系不要變化澎埠,此時地球?yàn)閰⒖枷担瑢?shí)際上此時不用save一次始藕,因?yàn)闋顟B(tài)變化是疊加的蒲稳。畫完月球后restore一次,恢復(fù)到畫地球之前的狀態(tài)就可以了伍派。
繪制太陽時江耀,先確保恢復(fù)到繪制地球之前的狀態(tài)诉植。
Paste_Image.png