绘制重叠的半透明线,没有可见的重叠

问题描述 投票:0回答:2

我正在使用 HTML5 画布开发一个画家程序。我创建了一个绘图工具,用户可以拖动并移动鼠标。

我有一个监听

mousemove
事件的监听器,绘制短线:

Painter.mainCanvas.beginPath();
Painter.mainCanvas.moveTo(Painter.lastX, Painter.lastY);
Painter.lastX = e.offsetX;
Painter.lastY = e.offsetY;
Painter.mainCanvas.lineTo(Painter.lastX, Painter.lastY);
Painter.mainCanvas.stroke();

一切正常,直到我将全局 Alpha 设置为 < 1. When using this method to draw, the end dot is also start dot. So the dot is drawn twice. And because we have transparent color, the dot now has different color with other dots in line.

我尝试了另一种方法,当 mousemove 触发时,它只使用

lineTo()
stroke()
当 mouseup 触发时。

这解决了双重绘制问题,但也引入了一个新问题:当用户打算绘制同一个点两次时,即没有鼠标按下的十字线,该点将不会被绘制两次。因为

lineTo()
函数不会在中间没有笔划的情况下绘制两次点。

html canvas vector-graphics
2个回答
20
投票

(重申你的问题)你最初的问题是,通过为每个段调用

beginPath()
stroke()
,你会得到许多重叠的半透明路径。您的新“问题”是,通过创建所有
lineTo()
命令作为同一路径的一部分,然后在最后调用
stroke()
once,用户想要的任何自相交路径都不会显示可见的重叠。

这是一个显示制作之间差异的示例

  • 单个路径中的许多半透明线并抚摸一次(左上),与
  • 不同路径中的许多半透明线并抚摸每条线(右下)

                        http://jsfiddle.net/jhyG5/2/

A semi-transparent set of crossing lines (all the same opacity) in the upper left and a set of crossing lines with increasing opacity where they cross in the bottom right.

我想说,您当前的解决方案(单个路径)是正确的方法,即使单个自交叉路径的不透明度不会加倍。这就是您在 Adobe Photoshop 和 Illustrator 中绘制半透明路径时所看到的情况:所有用鼠标按下的绘图都是同一个、单个、不重叠的透明对象的一部分。只有当用户释放并重新按下鼠标按钮时,您才会积累更多透明度:

  • 两个不透明度为 50% 的 Photoshop 画笔描边:
    Photoshop Overlapping Style

  • 两条不透明度为 50% 的 Illustrator 路径: Illustrator Overlapping Strokes

特别注意,自相交的笔画和路径在交叉过程中不会显示双倍的不透明度,但单独的新路径会显示。

我建议您坚持使用当前的解决方案,因为这就是这些传统的、经过深思熟虑的应用程序的行为方式。我这么说既是因为您希望您的包能够模仿用户的期望,也因为如果这些包这样做,可能有一个很好的理由:您最初遇到的问题! :)


0
投票

一个好的解决方法是在绘制每条线之前绘制画布背景颜色。

https://jsfiddle.net/gfsrt6L5/

这是我添加的代码。请参阅 JS 小提琴

        if (distinctPaths){
            const oldStyle = ctx.strokeStyle;
            ctx.strokeStyle = 'white';
            ctx.moveTo(pts[0][0]+x,pts[0][1]+y);
            ctx.lineTo(pts[1][0]+x,pts[1][1]+y);
            ctx.stroke();
            ctx.beginPath();
            ctx.strokeStyle = oldStyle;
        }

© www.soinside.com 2019 - 2024. All rights reserved.