【问题标题】:How to fill shape outside on canvas如何在画布上填充外部形状
【发布时间】:2021-11-08 04:16:13
【问题描述】:
我使用画布并用鼠标绘制闭合线,而不是用某种颜色填充内部区域(例如绿色)。如何填充外部区域,而不是内部。
这是我使用的代码块:
const context = canvas.getContext('2d')
canvas.addEventListener('mouseup', function (e) {
context.closePath();
context.fill();
draw = false;
});
这是我要实现的示例
https://jsfiddle.net/tonycaso/drxpb8vy/24/
但是它使用fabricjs库,我需要通过原生canvas和js来完成。
【问题讨论】:
标签:
javascript
canvas
html5-canvas
【解决方案1】:
您可以使用globalCompositeOperation。它设置绘制新形状时应用的合成操作类型。您可能想了解更多关于它的信息here。
在您的情况下,您可以先用一种颜色(例如绿色)填充整个画布。然后让鼠标画出形状。绘制形状后,使用全局复合操作destination-out 对其进行填充。它将从背景中切出形状,从而使外部区域保持填充状态。
const canvas = document.querySelector('canvas');
const context = canvas.getContext('2d');
context.canvas.width = 300;
context.canvas.height = 300;
canvas.addEventListener('mousedown', function (e) {
context.beginPath();
context.moveTo(e.clientX, e.clientY);
});
canvas.addEventListener('mousemove', function (e) {
context.lineTo(e.clientX, e.clientY);
});
canvas.addEventListener('mouseup', function (e) {
context.closePath();
// Fill a rect on the entire canvas with the desired color
context.fillStyle = "green";
context.fillRect(0, 0, canvas.width, canvas.height);
// Cut out the drawn shape
context.globalCompositeOperation = "destination-out";
context.fill();
});
canvas {
cursor: crosshair;
border: 2px solid #000;
}
<canvas></canvas>
【解决方案2】:
基本上这真的很难。您需要编写一个自定义函数来检查每个像素。我们可以做的是让事情变得更容易
background (what color you want to fill)
fill(the original Background color)
//drawYourShape