由于项目里面需求一个圆形的橡皮檫功能,但是原生的canvas清空方法只有一个clearRect() 方法,这个方法只是可以提供矩形清空的方法。
根据项目需求,我们只能想办法实现,最后,通过百度想到的办法就是,通过使用clearRect() 多次清除,来实现圆形清除。
逻辑很简单,接下来带上源码,大家可以下载下来,然后将图片的src修改一下,即可。
<!doctype html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>canvas画布的圆形橡皮檫效果</title>
</head>
<body>
<canvas id="canvas" style="margin: 0 auto; display: block;"></canvas>
</body>
<script>
let canvas = document.getElementById('canvas');
let ctx = canvas.getContext("2d");
let img = new Image();
//这里直接修改图片的路径
img.src = "meinv.jpg";
img.onload = function () {
//设置canvas的宽高
canvas.height = img.height;
canvas.width = img.width;
//将图像绘制到canvas上面
ctx.drawImage(img, 0, 0, img.width, img.height);
//绑定点击事件,然后通过点击事件获取当前点击区域进行绘制
canvas.addEventListener("mousedown", function (e) {
//获取到canvas距离窗口左上角的位置
let offsetLeft = canvas.getBoundingClientRect().left;
let offsetTop = canvas.getBoundingClientRect().top;
//获取到鼠标距离窗口左上角的
let downX = e.clientX - offsetLeft;
let downY = e.clientY - offsetTop;
//console.log(downX, downY);
generatePixel(downX, downY);
function mouseMove(event) {
let moveX = event.clientX - offsetLeft;
let moveY = event.clientY - offsetTop;
//console.log(moveX, moveY);
generatePixel(moveX, moveY);
}
function mouseUp() {
document.removeEventListener("mousemove", mouseMove);
document.removeEventListener("mouseup", mouseUp);
}
document.addEventListener("mousemove", mouseMove);
document.addEventListener("mouseup", mouseUp)
});
//根据坐标位置,生成附近九像素的贴图
let num = 50;
let r = num / 2;
function generatePixel(x, y) {
function clearArc(x, y, radius) {
//圆心(x,y),半径radius
for(let i=0; i<=radius; i++){
var calcWidth = radius - i;
var calcHeight = Math.sqrt(radius * radius - calcWidth * calcWidth);
var posX = x - calcWidth;
var posY = y - calcHeight;
var widthX = 2 * calcWidth;
var heightY = 2 * calcHeight;
ctx.clearRect(posX, posY, widthX, heightY);
}
}
clearArc(x, y, num / 2);
//如果是在左右边缘,需要绘制两次
if (x + r > canvas.width) {
clearArc(x - canvas.width, y, num / 2);
}
if (x - r < 0) {
clearArc(x + canvas.width, y, num / 2);
}
}
};
</script>
</html>