How to change strokeStyle used in an arc for each point?

Viewed 150

I am trying to draw an object using numerous points and I am trying to assign a unique color to each point by assigning the color to strokeStyle. I am using HSL style of coloring.

It is only taking the first color or black.

Below is the code that I have tried.

const c = document.getElementById("myCanvas");
c.width=window.innerWidth;
c.height=window.innerHeight - 150;
let ctx = c.getContext("2d");
let cx = c.width/2, cy = c.height/2;
let n = 6, d = 71;

ctx.translate(cx,cy);
ctx.save();
ctx.beginPath();

for(let i = 0; i < 361; i++){
  let k = i * d * Math.PI/180;
  let r = 150 * Math.sin(n*k);
  let x = r * Math.cos(k);
  let y = r * Math.sin(k);
  ctx.arc(x, y, 0.5, 0, 2 * Math.PI);
  ctx.strokeStyle = "hsl("+Math.random() * 360 | 0+",100%,50%)"; // assign a random color to each point
}

ctx.stroke();
<canvas id="myCanvas"></canvas>

2 Answers

If you want to change the color for each point you need to begin a new path with every step of the loop. The arcs in your code are just small dots. If you want to see anything you need to draw lines between the previous point (last) and the new one.

In my code I've commented out the part where you draw the arc.

const c = document.getElementById("myCanvas");
c.width=window.innerWidth;
c.height=window.innerHeight;
let ctx = c.getContext("2d");
let cx = c.width/2, cy = c.height/2;
let n = 6, d = 71;

ctx.translate(cx,cy);
ctx.save();



let last = {x:0,y:0}

for(let i = 0; i < 361; i++){
  let k = i * d * Math.PI/180;
  let r = 150 * Math.sin(n*k);
  let x = r * Math.cos(k);
  let y = r * Math.sin(k);
  
  ctx.beginPath();
  ctx.moveTo(last.x,last.y);
  ctx.lineTo(x,y)
  ctx.strokeStyle = "hsl("+ Math.random() * 360 + ",100%,50%)"; 
  ctx.stroke();
  /*
  ctx.beginPath();
  ctx.arc(x, y, 0.5, 0, 2 * Math.PI);
  ctx.stroke();*/
  
  last={x,y}
}
<canvas id="myCanvas"></canvas>

The main reason is the ctx.stroke(); command. You are not actually drawing anything in the loop. Just constructing a very long path. At the point where you call the stroke() method it strokes the entire path with the current color. You need to find a way to break up the the paths into the segments you want and stroke each one independently. That is, call beginPath() when you want a new segment and stroke() when that segment is ready to be drawn.

This answer also provides some details.

Related