围绕圆形路径生成形状

时间:2019-01-02 09:57:06

标签: javascript html canvas

我有多种形状(矩形,弧形...),我希望它们都围绕一个特定的圆(在某个不可见的圆的边界上)。

考虑此不可见圆的中心在屏幕的中心 (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>

1 个答案:

答案 0 :(得分:2)

问题是您分别为X和Y生成了不同的随机角度。两者使用相同的随机角度:

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>