【问题标题】:How do I draw a semi transparent line on a html canvas element without dots in the line? [duplicate]如何在 html 画布元素上绘制一条半透明的线条,而线条中没有点? [复制]
【发布时间】:2020-03-25 09:29:20
【问题描述】:

好的,我正在开发一个绘图应用程序,我想制作它,以便用户可以更改画笔的不透明度。我已经通过更改 alpha 值来改变不透明度,但是当我用降低的 alpha 值绘制一条线时,该线中有许多不同透明度的点。如何使半透明线绘制得非常干净,仅在重叠处偶尔改变透明度?

图 1 是我运行代码时发生的情况

如果可能的话,我想实现图 2

这是我画布的 javascript 代码

const canvas = document.querySelector("#canvas");
const ctx = canvas.getContext('2d');

window.addEventListener('load', function() {

    //Resizing
    canvas.height = window.innerHeight;
    canvas.width = window.innerWidth;

    //Variables
    let painting = false;

    function startPosition(e) {
        painting = true;
        draw(e);
    }

    function finishedPosition() {
        painting = false;
        ctx.beginPath();
    }

    function draw(e) {
        if(!painting) return;

        ctx.lineWidth = 10;
        ctx.lineCap = "round";

        ctx.lineTo(e.clientX, e.clientY);
        ctx.stroke();
        ctx.beginPath();
        ctx.moveTo(e.clientX, e.clientY);

    }

    //EventListeners
    canvas.addEventListener('mousedown', startPosition);
    canvas.addEventListener('mouseup', finishedPosition);
    canvas.addEventListener('mousemove', draw);

});

【问题讨论】:

  • 对于单色,存储所有坐标,清除整个画布并重绘为单个子路径。对于不同的颜色,在屏幕外画布上绘制一次不透明*,然后降低可见画布的 globalAlpha 并在屏幕外画布上绘制图像。 (* 如果你真的只有这些画,你可以使用合成将它们全部放在同一个画布上。
  • 啊,好吧,我找到了一些代码,但我真的不明白实际发生了什么。有什么资源可以让我了解更多信息吗?

标签: javascript html canvas drawing


【解决方案1】:

我会建议您重构您的 draw() 并使用画布 (shameless plug of my canvas credibility) 进行一些 OOP。

我说 OOP,以便您可以在更清晰的状态下跟踪用户以前的坐标和当前坐标。

一旦实施了一些 OOP,您就可以利用以下代码:

function draw(e) {
    //Update Current coords
    this.currX = e.clientX
    this.currY = e.clientY

    ctx.beginPath();
    ctx.moveTo(this.prevX, this.prevY);
    ctx.lineTo(this.currX, this.currY);
    ctx.lineWidth = this.lineWidth;          //10
    ctx.lineCap = this.lineCap;              //round
    ctx.strokeStyle = this.lineColor;        //blue 
    ctx.stroke();
    ctx.closePath();

    // Update coords
    this.prevX = this.currX
    this.prevY = this.currY
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-03-12
    • 2014-07-19
    • 2021-01-26
    • 1970-01-01
    • 1970-01-01
    • 2014-01-30
    • 2021-10-30
    • 1970-01-01
    相关资源
    最近更新 更多