核心参数:
ctx.globalCompositeOperation = "xor";
xor参数的作用是将两个图形进行异或操作,重叠部分为空白,其他地方为有色区域,基于这个特性,可以在canvas画布区域使用两个图形,一个覆盖整个画布区域,另一个为圆形聚光灯区域。动态修改圆形的位置坐标即可实现聚光灯效果。
函数如下:
绘制两个图像区域
function render() {
clear();//开始之前清空一下画布区域
// 方形
ctx.beginPath();
ctx.fillStyle = "black";
ctx.globalAlpha = 0.8;
ctx.fillRect(0, 0, w, h);
ctx.globalCompositeOperation = "xor"
// 圆形
ctx.beginPath();
ctx.shadowBlur = (1 / 2);
ctx.arc(circle_w, circle_h, 220, 0, Math.PI * 2);
ctx.closePath();
ctx.fillStyle = "blue";
ctx.fill();
ctx.strokeStyle = 'black';
requestAnimationFrame(render);//反复调用绘画函数,可以实现动态效果
}
清空画布的函数
function clear() {
ctx.clearRect(0, 0, w, h);
}
检测窗口大小变化,一旦调整,随之更改画布大小
var h = canvas.height = document.body.offsetHeight;
var w = canvas.width = document.body.offsetWidth;
window.onresize = function () {
w = canvas.width = document.body.offsetWidth;
h = canvas.height = document.body.offsetHeight;
}
监听鼠标动作,移动圆形区域,实现聚光灯效果.
document.addEventListener('mousemove', (e) => {
fun(e);
});
function fun(e) {
circle_w = e.clientX;
circle_h = e.clientY;
render();
}