绘制矩形。
Rectangles
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);};
同样,可设置各种颜色。
var canvas = document.getElementById('canvas'), context = canvas.getContext('2d');context.lineJoin = 'round';context.lineWidth = 30;context.font = '24px Helvetica';context.fillText('Click anywhere to erase', 175, 200);//设置各种颜色context.strokeStyle = 'goldenrod';context.fillStyle = 'rgba(0, 0, 255, 0.5)';//设置各种颜色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);};
创建渐变颜色。
var canvas = document.getElementById('canvas'), context = canvas.getContext('2d'), gradient = context.createLinearGradient( 0, 0, 0, canvas.height / 2);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();