首页 > 解决方案 > 如何更改每个点的弧中使用的strokeStyle?

问题描述

我正在尝试使用许多点来绘制一个对象,并且我试图通过将颜色分配给 strokeStyle 来为每个点分配唯一的颜色。我正在使用 HSL 风格的着色。

它只采用第一种颜色或黑色。

下面是我尝试过的代码。

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>

标签: javascriptcanvas

解决方案


如果要更改每个点的颜色,则需要在循环的每一步都开始一条新路径。代码中的弧只是小点。如果您想查看任何内容,您需要在前一点 ( last) 和新点之间画线。

在我的代码中,我已经注释掉了绘制弧线的部分。

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>


推荐阅读