好的,我正在开发一个绘图应用程序,我想让用户可以更改画笔的不透明度。我已经通过更改 alpha 值来改变不透明度,但是当我用降低的 alpha 值绘制一条线时,该线有许多不同透明度的点。如何使半透明线条绘制非常干净,并且仅在重叠处偶尔改变透明度?
图 1 是我运行代码时发生的情况
这是我的 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/