使用圖形上下文不帶參數(shù)的clip()方法來實現(xiàn)Canvas圖形裁切功能贡羔,該方法會使用先創(chuàng)建好的路徑對canvas設(shè)置裁剪區(qū)域儡司,裁剪指定區(qū)域顯示內(nèi)容
切記:裁剪是對畫布進行的,裁剪后的畫布是不能恢復(fù)到原來的大小晓褪,因此使用save及restore
語法:
context.clip();
栗子:
- 準備工作: 裁切為圓形挺智,則需要圓心,及每步的長度
// 起始圓心坐標
var arcX = 100;
var arcY = 100;
// 起始步長
var stepX = 6;
var stepY = 8;
- 畫圓
function draw() {
// 保存上下文的設(shè)置及變換的狀態(tài)
ctx.save();
// 清空畫布
ctx.clearRect(0, 0, 500, 500);
// 重洗畫圖
ctx.fillStyle = 'orange';
ctx.fillRect(0, 0, 500, 500);
ctx.fill();
// 設(shè)置裁切區(qū)域
ctx.beginPath();
ctx.fillStyle = '#FFF';
ctx.arc(arcX, arcY, 100, 0, 2 * Math.PI);
//先繪制好裁切路徑艰山,然后調(diào)用clip
ctx.clip();
ctx.fill();
ctx.beginPath();
// 字號 字體加粗 字體
ctx.font = '40px bold';
// 字體填充色
ctx.fillStyle = 'blue';
ctx.fillText('小貝真好', 200, 200);
ctx.strokeStyle = 'black';
ctx.strokeText('小貝是誰', 200, 300);
// 恢復(fù)之前保存的狀態(tài)
ctx.restore();
}
- 來個定時器, 順便判斷一下可運動的范圍
var timer = setInterval (function () {
// 100 為圓的半徑 500為畫布的大小
if (arcX + 100 >= 500) {
stepX *= -1;
}
if (arcX - 100 < 0) {
stepX *= -1;
}
if (arcY + 100 >= 500) {
stepY *= -1;
}
if (arcY - 100 < 0) {
stepY *= -1;
}
arcX += stepX;
arcY += stepY;
draw();
}, 17);