Chewie The Chorkie
Chewie The Chorkie

Reputation: 5234

Vary line color, alpha and width when drawing on canvas in JavaScript

I am testing this in Chrome. I tried a line thickness solution from StackOverflow here that did not work.

I have a object called redLine with a position and an array of offset positions. The only thing that is affected is the alpha value. Color and line thickness stays once it is set.

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();

}

Upvotes: 0

Views: 484

Answers (1)

Kaiido
Kaiido

Reputation: 136717

You need to call ctx.beginPath() after each ctx.stroke() otherwise, all the next lineTo() will be added to the one and only sub-path and when you'll call stroke() again with a thicker lineWidth, the whole sub-path will get redrawn, covering the thinner lines that were drawn before.

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>

Upvotes: 1

Related Questions