我正在尝试在JavaScript画布中创建一个圆形菜单,看起来类似于以下内容:
这是我正在使用的代码:
let canvas = document.querySelector("#canvas");
canvas.width = 500;
canvas.height = 500;
let ctx = canvas.getContext("2d");
ctx.fillStyle = "rgba(0,0,0,.45)"; // color
let circlePath = [];
let centerCircle = new Path2D();
for (let t = 0; t < 8; t++) {
circlePath[t] = new Path2D();
circlePath[t].moveTo(250, 250);
circlePath[t].arc(
250,
250,
190,
Math.PI * 2 * 0.125 * t,
Math.PI * 2 * 0.125 * t + Math.PI * 2 * 0.1175
);
circlePath[t].closePath();
ctx.fill(circlePath[t]);
}
ctx.fillStyle = "#fff";
centerCircle.moveTo(250, 250);
centerCircle.arc(250,250,100,0,2*Math.PI);
ctx.fill(centerCircle);
canvas.addEventListener("mousemove", function (event) {
ctx.clearRect(0, 0, canvas.width, canvas.height);
for (let t = 0; t < 8; t++) {
if (ctx.isPointInPath(circlePath[t], event.offsetX, event.offsetY)) {
ctx.fillStyle = "blue";
} else {
ctx.fillStyle = "rgba(0,0,0,.45)";
}
ctx.fill(circlePath[t]);
}
ctx.fillStyle = "#fff";
centerCircle.moveTo(250, 250);
centerCircle.arc(250,250,100,0,2*Math.PI);
//ctx.globalCompositeOperation = "destination-out";
ctx.fill(centerCircle);
});
#canvas {
border: 1px solid #000;
background: green;
};
<canvas id="canvas"></canvas>
我遇到的问题是,当我尝试使用ctx.globalCompositeOperation = "destination-out";
白色圆圈在圆弧的中部“冲出”一个孔时,它会使所有对象消失。
预先感谢您提供的任何输入。
弄清楚了!必须放置ctx.globalCompositeOperation = "destination-out";
在正确的位置,其次是:ctx.globalCompositeOperation = "source-over";
这是更新的代码:
let canvas = document.querySelector("#canvas");
canvas.width = 500;
canvas.height = 500;
let ctx = canvas.getContext("2d");
ctx.fillStyle = "rgba(0,0,0,.45)"; // color
let circlePath = [];
let centerCircle = new Path2D();
for (let t = 0; t < 8; t++) {
circlePath[t] = new Path2D();
circlePath[t].moveTo(250, 250);
circlePath[t].arc(
250,
250,
190,
Math.PI * 2 * 0.125 * t,
Math.PI * 2 * 0.125 * t + Math.PI * 2 * 0.1175
);
circlePath[t].closePath();
ctx.fill(circlePath[t]);
}
ctx.fillStyle = "#fff";
centerCircle.moveTo(250, 250);
centerCircle.arc(250,250,100,0,2*Math.PI);
ctx.globalCompositeOperation = "destination-out";
ctx.fill(centerCircle);
ctx.globalCompositeOperation = "source-over";
canvas.addEventListener("mousemove", function (event) {
ctx.clearRect(0, 0, canvas.width, canvas.height);
for (let t = 0; t < 8; t++) {
if (ctx.isPointInPath(circlePath[t], event.offsetX, event.offsetY)) {
ctx.fillStyle = "blue";
} else {
ctx.fillStyle = "rgba(0,0,0,.45)";
}
ctx.fill(circlePath[t]);
}
ctx.fillStyle = "#fff";
centerCircle.moveTo(250, 250);
centerCircle.arc(250,250,100,0,2*Math.PI);
ctx.globalCompositeOperation = "destination-out";
ctx.fill(centerCircle);
ctx.globalCompositeOperation = "source-over";
});
#canvas {
border: 1px solid #000;
background: green;
};
<canvas id="canvas"></canvas>
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句