javascript - 如何在 html canvas 元素上绘制一条半透明的线且线上没有点?

标签 javascript html canvas drawing

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

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

如果可能的话,图2是我想要实现的目标 This is what happens when I run my code This is what I would like to achieve

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

});

最佳答案

我建议重构您的 draw() 并使用 Canvas ( 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
}

关于javascript - 如何在 html canvas 元素上绘制一条半透明的线且线上没有点?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59110618/

相关文章:

javascript - 如何在 Angular Controller 中将复选框标记为已选中

javascript - 如何跳转到视频中的不同帧

html - 单击时将 div 放在按钮上

html - Z-Index 问题,我没有解释

javascript - Fabricjs loadFromJSON 性能

javascript - 将小数评级(最多 5 w/0.1 增量)转换为百分比

Javascript XML - 如何返回空值

javascript:获取关联数组中包含重复数据的键

performance - PixelSearch功能效率很低,如何优化?

c# - WPF - Canvas 中的中心控件(标签)