【问题标题】:Vary line color, alpha and width when drawing on canvas in JavaScript使用 JavaScript 在画布上绘图时改变线条颜色、alpha 和宽度
【发布时间】:2019-05-29 20:41:11
【问题描述】:

我正在 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();

}

【问题讨论】:

    标签: javascript canvas colors line


    【解决方案1】:

    您需要在每个ctx.stroke() 之后调用ctx.beginPath(),否则,所有下一个lineTo() 将被添加到唯一的子路径中,并且当您再次调用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
    
    }
    &lt;canvas id="canvas"&gt;&lt;/canvas&gt;

    【讨论】:

    • 感谢 Kaiido,改变了线宽,但现在它们没有连接,所以我认为这意味着你不能让连接线改变宽度?颜色(即使没有宽度变化)也有所不同,但线条不连接。有什么办法可以让连接线段变色?
    • 是的,但这并不容易:stackoverflow.com/questions/24027087/…
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-23
    • 2012-11-29
    • 1970-01-01
    • 2018-12-10
    • 2020-06-09
    • 1970-01-01
    相关资源
    最近更新 更多