我有多个形状(矩形、圆弧……),我希望它们都围绕一个特定的圆(在某个不可见圆的边界上)。
考虑这个不可见圆圈的中心位于屏幕的中心 (canvas.width/2,canvas.height/2) 其半径为200 但形状是在某个矩形内生成的,我不想要这个。
let canvas = document.querySelector('canvas');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
let particlesNum = 100;
let particles = [];
let ctx = canvas.getContext('2d');
function Particle(x,y,r){
this.x = x ;
this.y = y ;
this.r = r ;
}
Particle.prototype.draw = function() {
ctx.beginPath();
ctx.fillStyle = 'red' ;
ctx.arc(this.x,this.y,this.r,0,2*Math.PI,false);
ctx.fill();
}
function generateParticels(){
let x,y,r ;
for(let i=0 ; i<particlesNum ; i++){
x = canvas.width/2+Math.cos(Math.random()*(2*Math.PI))*200;
y = canvas.height/2+Math.sin(Math.random()*(2*Math.PI))*200;
r = 1 ; //radius of each circle
particles.push(new Particle(x,y,r));
}
particles.forEach(particle=>particle.draw());
}
generateParticels();
*{
box-sizing: border-box;
padding: 0;
margin: 0;
}
html,body{height: 100%;}
<canvas></canvas>
最佳答案
问题是您分别为 X 和 Y 生成不同的随机 Angular 。两者使用相同的随机 Angular :
let canvas = document.querySelector('canvas');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
let particlesNum = 100;
let particles = [];
let ctx = canvas.getContext('2d');
function Particle(x,y,r){
this.x = x ;
this.y = y ;
this.r = r ;
}
Particle.prototype.draw = function() {
ctx.beginPath();
ctx.fillStyle = 'red' ;
ctx.arc(this.x,this.y,this.r,0,2*Math.PI,false);
ctx.fill();
}
function generateParticels(){
let x, y, r, randomAngle ;
for(let i=0 ; i<particlesNum ; i++){
randomAngle = Math.random() * 2 * Math.PI;
x = canvas.width / 2 + Math.cos(randomAngle) * 200;
y = canvas.height / 2 + Math.sin(randomAngle) * 200;
r = 1 ; //radius of each circle
particles.push(new Particle(x,y,r));
}
particles.forEach(particle=>particle.draw());
}
generateParticels();
*{
box-sizing: border-box;
padding: 0;
margin: 0;
}
html,body{height: 100%;}
<canvas></canvas>
关于javascript - 围绕圆形路径生成形状,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54004274/