如何在html canvas元素上绘制半透明线,且该线中没有点?

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

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

如果可能,我想实现图像2

如何在html canvas元素上绘制半透明线,且该线中没有点?

如何在html canvas元素上绘制半透明线,且该线中没有点?

这是我的画布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);

});
CS_DN_CS_DN 回答:如何在html canvas元素上绘制半透明线,且该线中没有点?

我建议折光您的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
}
本文链接:https://www.f2er.com/3005185.html

大家都在问