我正在Chrome中对此进行测试。我尝试了来自StackOverflow here的线宽解决方案,但该方法无效。
我有一个名为redLine的对象,该对象具有一个位置和一组偏移位置。唯一受影响的是alpha值。设置后,颜色和线条粗细保持不变。
function renderRedLine(){
context.beginPath();
for(j=0; j<redLine.posArr.length; ++j){
var startPoint
if(j===0){
startPoint = redLine.pos
}else{
startPoint = redLine.posArr[j-1]
}
var endPoint = redLine.posArr[j]
let alpha = 1.0 - (j/(redLine.posArr.length-1))
let g = 150 - (10*j)
context.strokeStyle = 'rgba(255, ' + g + ', ' + 0 + ', ' + alpha + ')'
context.lineWidth = j+1
if(j===0){
context.moveTo(startPoint.x, startPoint.y);
}else{
context.lineTo(endPoint.x, endPoint.y);
}
context.stroke();
}
context.closePath();
}
答案 0 :(得分:1)
您需要在每个ctx.beginPath()
之后调用ctx.stroke()
,否则,接下来的所有lineTo()
都会添加到一个唯一的子路径中,并且在您调用{{1} }再次使用较粗的lineWidth,整个子路径将被重绘,覆盖之前绘制的较细的线。
stroke()
const context = canvas.getContext('2d');
const redLine = {
posArr: Array.from({
length: 12
}).map(() => ({
x: Math.random() * canvas.width,
y: Math.random() * canvas.height
})),
pos: {
x: canvas.width / 2,
y: canvas.height / 2
}
};
console.log(redLine);
renderRedLine();
function renderRedLine() {
for (j = 0; j < redLine.posArr.length; ++j) {
// at every iteration we start a new sub-path
context.beginPath();
let startPoint;
if (j === 0) {
startPoint = redLine.pos
} else {
startPoint = redLine.posArr[j - 1]
}
const endPoint = redLine.posArr[j]
const alpha = 1.0 - (j / (redLine.posArr.length - 1))
const g = 150 - (10 * j)
context.strokeStyle = 'rgba(255, ' + g + ', ' + 0 + ', ' + alpha + ')'
context.lineWidth = j + 1
// since we start a new sub-path at every iteration
// we need to moveTo(start) unconditionnaly
context.moveTo(startPoint.x, startPoint.y);
context.lineTo(endPoint.x, endPoint.y);
context.stroke();
}
//context.closePath is only just a lineTo(path.lastMovedX, path.lastMovedY)
// i.e not something you want here
}