javascript - 如何更改每个点的弧中使用的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>
解决方案
如果要更改每个点的颜色,则需要在循环的每一步都开始一条新路径。代码中的弧只是小点。如果您想查看任何内容,您需要在前一点 ( 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>
推荐阅读
- java - 在生产中部署 .jar 文件的正确方法
- react-native - 在反应导航 5.x 中禁用导航回登录/注册屏幕
- c# - 列表集合对于 30000 个项目来说太慢了
- vagrant - 如何 chown 与 rsync-auto 同步的文件/文件夹?
- sql - 如何使用 Lead() 和 Lag() 获取第一个非空值
- google-chrome - 创建 crx 文件失败
- python - For循环列表以在Python中命名变量
- reporting-services - 如何编码为多个发票分页并具有两个 tablix(tablii?)的 SSRS 发票
- excel - VBA 从网站下载 xlsx 文件(DMS 或 EDM)
- codeigniter - 是否可以在本地主机上设置 CORS Anywhere?