canvas提供了三个API,分别是:
1.绘制一个填充的矩形
fillRect(x, y, width, height)
2.绘制一个矩形的边框
strokeRect(x, y, width, height)
3.清除指定矩形区域,让清除部分完全透明
clearRect(x, y, width, height)
其中x、y是相对于画布左上角0,0 的距离,width是宽度,height设置矩形高度;
实例1
window.onload=function(){
var canvas = document.getElementById('canvas');
canvas.width='300';
canvas.height='300';
var ctx = canvas.getContext('2d');
//在x轴为10,y轴为10的位置画长为120,宽为80的长方形
ctx.strokeRect(10,10,120,80);
//在x轴为120,y轴为120的位置画长为160,宽为100的填充长方形
ctx.fillRect(120,120,160,100);
}
绘制了两个长方形一个只有有边框的,一个只有填充的
实例2
window.onload=function(){
var canvas = document.getElementById('canvas');
canvas.width='300';
canvas.height='300';
var ctx = canvas.getContext('2d');
//在x轴为30,y轴为30的位置画边长为120的正方形
ctx.fillRect(30,30,120,120);
//在x轴为50,y轴为50的位置清除边长为80的正方形区域
ctx.clearRect(50,50,80,80);
}
可以看到黑色的正方形里面被清除出来一个边长为80的正方形区域,clearRect就是这个作用
我们可以尝试在清除出来的区域里面再画一个正方形
window.onload=function(){
var canvas = document.getElementById('canvas');
canvas.width='300';
canvas.height='300';
var ctx = canvas.getContext('2d');
//在x轴为30,y轴为30的位置画边长为120的正方形
ctx.fillRect(30,30,120,120);
//在x轴为50,y轴为50的位置清除边长为80的正方形区域
ctx.clearRect(50,50,80,80);
//在x轴为70,y轴为70的位置画边长为40的正方形
ctx.fillRect(70,70,40,40);
}
看到如下效果