如何在不隐藏路口重叠的情况下隐藏路径直接重叠?

How to hide the path immediate overlap without hiding intersection overlap?

我正在制作一个绘画应用程序,并使用 canvas 路径作为画笔:

function onMove(){
    ctx.beginPath();
    ctx.moveTo(pos.x, pos.y); // from position
    pos=getPosition(event); 
    ctx.lineTo(pos.x, pos.y); // to position 
    ctx.stroke(); // draw it!
}

我陷入了两难境地,如果我将所有路径连接成一条,我就会失去交点重叠,如果我分别实时绘制它们,我会得到那些 start/end 个重叠球体。

有没有一种干净的方法可以解决这个问题?谢谢。

好的,因为我们在这里处理 alpha 值,所以它变得复杂了..

基本上,您可以使用 destination-insource-in 混合模式在缓冲区 canvas 中绘制新行的“缺失部分”。

想法是:“计算”第 N-1 行的重叠,然后仅在此重叠之外绘制第 N 行: (为了演示,第 N 行将绘制为红色。)

const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');

const canvas2 = document.createElement('canvas')
canvas2.width = 300
canvas2.height = 300
const ctx2 = canvas2.getContext('2d');

ctx.lineWidth = 30
ctx.lineCap = 'round';
ctx.strokeStyle = 'rgba(0,0,0,0.5)';
ctx.imageSmoothingEnabled = false;
ctx.lineJoin = "round"



function drawLine1(ctx) {
  ctx.beginPath();
  ctx.moveTo(250, 250);
  ctx.lineTo(100, 250);
  ctx.stroke();
}
function drawLine2(ctx) {
  ctx.beginPath();
  ctx.moveTo(100, 250);
  ctx.lineTo(100, 50);
  ctx.stroke();
}

// draw image until line n-1 on screen
ctx.beginPath();
ctx.moveTo(0, 100);
ctx.lineTo(250, 100); // 1st
ctx.lineTo(250, 250); // 2nd
ctx.lineTo(100, 250); // n-1
ctx.stroke();

// clear buffer canvas and setup
ctx2.clearRect(0, 0, canvas2.width, canvas2.height);
ctx2.lineWidth = 30
ctx2.lineCap = 'round';
ctx2.imageSmoothingEnabled = false;
// draw line n-1 on buffer in opaque color
ctx2.strokeStyle = 'rgba(0,0,0,1)';
drawLine1(ctx2)

// draw line n on buffer in "destination-in" blend mode opaque
ctx2.globalCompositeOperation = 'destination-in';
ctx2.strokeStyle = 'rgba(0,0,0,1)';
drawLine2(ctx2)

// draw line n on buffer in "source-out" blend mode and original color
ctx2.globalCompositeOperation = 'source-out';
ctx2.strokeStyle = 'rgba(255,0,0,0.5)';
drawLine2(ctx2)

ctx.drawImage(canvas2, 0 ,0)
<canvas id="canvas" width="400" height="400"></canvas>

它并不完美,但它是一个起点..