在 JavaScript 中在画布上绘制时改变线条颜色、alpha 和宽度



我正在Chrome中测试这个。我在这里尝试了来自 StackOverflow 的线粗解决方案,但没有奏效。

我有一个名为 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();
}
您需要

在每次ctx.stroke()后调用ctx.beginPath(),否则,所有接下来的lineTo()都将添加到唯一的子路径中,当您再次使用较粗的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
}
<canvas id="canvas"></canvas>

最新更新