使用的API:
- ctx.strokeRect(x, y, width, height) 给一个矩形描边
- ctx.fillRect(x, y, width, height) 填充一个矩形
- ctx.clearRect(x, y, width, height) 清除矩形区域
- ctx.lineJoin = 'round' | 'bevel' | 'miter' 定义线交点处的样式
var canvas = document.getElementById('canvas'), context = canvas.getContext('2d'); canvas.width = 1024; canvas.height = 768; // ctx.lineJoin = "bevel" || "round" || "miter"; 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); }
显示效果:
鼠标点击canvas上任意位置,矩形和文字就都不见了。