如何在画布的循环中创建一排星星?

时间:2016-10-18 13:59:28

标签: javascript html oop canvas

我正在制作美国国旗的画布图像,我需要创建50颗星,但显然不想创建50颗独立的星星,那么我怎么能循环呢? 这是我到目前为止创建一个单星的代码。

    class Star extends drawable{
    constructor(x = 0,y = 0, outerRadius = 0, innerRadius = 0, numberOfPoints = 0, lineWidth = 0,fillStyle = "#000",strokeStyle = "transparent",context){
    super(context,x,y,fillStyle,strokeStyle,lineWidth);
    this.outerRadius = outerRadius;
    this.innerRadius = innerRadius;
    this.numberOfPoints = numberOfPoints;
}
draw(){
    super.draw();
    this.context.beginPath(); 
    this.context.moveTo(this.x,this.y - this.outerRadius); 
    this.numberOfPoints = this.numberOfPoints * 2; 
    let pointOffSetRadians = (2 * Math.PI) / this.numberOfPoints; 
    for(let i = 0; i < this.numberOfPoints; i++){
        let radX,radY;
        if(i % 2 === 0){
            radX = this.outerRadius * Math.sin(i * pointOffSetRadians);
            radY = this.outerRadius * Math.cos(i * pointOffSetRadians) * -1;
        } else {
            radX = this.innerRadius * Math.sin(i * pointOffSetRadians);
            radY = this.innerRadius * Math.cos(i * pointOffSetRadians) * -1; 
        }
        this.context.lineTo(radX + this.x, radY + this.y);
    }
    this.context.closePath(); 
    this.context.stroke(); 
    this.context.fill(); 
    super.afterDraw();
}
}
// For loop for multiple rectangles
for(let i = 0; i < 7; i++){
let yPos = (rectSize+20)*i;
        for(let j = 0; j < 7; j++){
            this.context.fillRect((rectSize+10)*j,yPos,this.width/-2,this.height/-2,this.width,this.height);
            this.context.strokeRect(this.width / -2, this.height / -2, this.width, this.height);
        }
    }
const star1 = new Star(24,130,18,7,5,0,"white","green",context4);
star1.draw();
const usaRedStripe = new   Rectangle(context4,340,40,"red","transparent",10,660,50);

usaRedStripe.draw();

1 个答案:

答案 0 :(得分:1)

只需使用for循环。

for (i=1;i<=50;i++){ //Loop 50 times for 50 stars.
    var x = 24 + (18 * i); //24 being the X of the first star, 18 being the width of each star.
    var y = 130; //130 being the Y of the first row.
    if (x > 203){ //203 is if this star instance is beyond the X bounds at the 10th star.
        x = 24 + (18 * (i-9)); //Subtract 9 from i to put this instance back at the beginning of the row.
    }
    if (i mod 11 == 0){ //Divide by 11 and if remainder is 0 this should be a new row.
        y = 130 + (7 * i); //Original Y + height of star * number of stars.
    }
    var tempStar = new Star(x,y,18,7,5,0,"white","green",context4);
    tempStar.draw();
}