Mozilla 官方 <canvas> 教程在這里。
畫布 <canvas> 的默認(rèn)寬高為 300 與 150 ,但是同樣可以使用 CSS 設(shè)定寬高。但因?yàn)?CSS 與 JavaScript 在渲染工程中有速度的差異,所以不建議使用 CSS 對(duì) <canvas> 的寬高做設(shè)定。
<canvas id="canvasId" width="300" height="150">
</canvas>
下面的 ctx 即為渲染上下文對(duì)象。globalCompositeOperation 為對(duì)于 canvas 繪畫時(shí)的渲染屬性設(shè)置,具體表現(xiàn)如下圖所示。
var canvas = document.getElementById('canvasId');
var ctx = canvas.getContext('2d');
// 繪畫 canvas 的屬性
ctx.globalCompositeOperation = 'destination-over';
http://wiki.jikexueyuan.com/project/fend_note/images/C/canvas-global-composite.png" alt="" />
http://wiki.jikexueyuan.com/project/fend_note/images/C/canvas-drawing-steps.png" alt="" />
一個(gè)周期就是完整的一幀的繪畫過(guò)程。
http://wiki.jikexueyuan.com/project/fend_note/images/C/canvas-animation.gif" alt="" />
var sun = new Image();
var moon = new Image();
var earth = new Image();
function init() {
sun.src = 'Canvas_sun.png';
moon.src = 'Canvas_moon.png';
earth.src = 'Canvas_earth.png';
window.requestAnimationFrame(draw);
}
function draw(){
var ctx = document.getElementById('canvas').getContext('2d');
ctx.globalCompositeOperation = 'destination-over';
// 清空畫布內(nèi)容
ctx.clearRect(0, 0, 300, 300);
ctx.fillStyle = 'rgba(0, 0, 0, 0.4)';
ctx.strokeStyle = 'rgba(0, 153, 255, 0.4)';
// 保存畫布狀態(tài)
ctx.save();
ctx.translate(150, 150);
// 開(kāi)始繪制圖形
// 地球
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);
ctx.drawImage(earth, -12, -12);
// 月亮
ctx.rotate(((2*Math.PI)/6)*time.getSeconds() + ((2*Math.PI)/6000)*time.getMilliseconds());
ctx.translate(0, 28.5);
ctx.drawInmage(moon, -3.5, -3.5);
// 恢復(fù)畫布狀態(tài)
ctx.restore();
ctx.beginPath();
ctx.arc(150, 150, 105, 0, Math.PI*2, false);
ctx.stroke();
ctx.drawImage(sun, 0, 0, 300, 300);
window.requestAnimationFrame(draw);
}
init();