1. 画矩形和写字
var canvas = document.getElementById('canvas'), context = canvas.getContext('2d'); context.lineWidth = 30; context.font = '24px Helvetica'; context.fillText('Click anywhere to erase', 175, 40); context.strokeRect(75, 100, 200, 200); context.fillRect(325, 100, 200, 200); // 鼠标按下时清除整个画布 context.canvas.onmousedown = function (e) { context.clearRect(0, 0, canvas.width, canvas.height); };
2. 射线渐变
var canvas = document.getElementById('canvas'), context = canvas.getContext('2d'), gradient = context.createRadialGradient( canvas.width/2, canvas.height, 10, canvas.width/2, 0, 100); gradient.addColorStop(0, 'blue'); gradient.addColorStop(0.25, 'white'); gradient.addColorStop(0.5, 'purple'); gradient.addColorStop(0.75, 'red'); gradient.addColorStop(1, 'yellow'); context.fillStyle = gradient; context.rect(0, 0, canvas.width, canvas.height); context.fill();
3. 居中文字
function drawText() { context.fillStyle = 'blue'; context.strokeStyle = 'yellow'; context.fillText(text, canvas.width/2, canvas.height/2); context.strokeText(text, canvas.width/2, canvas.height/2); } context.textAlign = 'center'; context.textBaseline = 'middle';
4. 图片
var canvas = document.getElementById('canvas'), context = canvas.getContext('2d'), image = new Image(); image.src = 'fence.png'; image.onload = function(e) { context.drawImage(image, 0, 0); };
5. 画布中的画布
var canvas = document.getElementById('canvas'), context = canvas.getContext('2d'), scaleWidth = ..., // Calculate scales for width and height scaleHeight = ...; ... context.drawImage(canvas, 0, 0, scaleWidth, scaleHeight);