我是JS的新手,还没有接触过jQuery之类的东西。我想做的就是在画布上画4个简单的圆圈。我将对象放到一个数组中,因为我计划将来可能会扩展,但这些信息是不相关的。
我需要的帮助,是理解如何在数组中创建对象的基础知识,然后在画布上显示它们。这是我的功能失调的代码:
var canvas = document.getElementById("canvas"),
ctx = canvas.getContext("2d");
var W = 400, H = 500
canvas.width = W, canvas.height = H;
var ball = [3];
for (i===0;i<=3; i++){
ball[i] = {
x: (Math.floor(Math.random() * 350) + 50),
y: (Math.floor(Math.random() * 450) + 50),
color: "red",
radius: (Math.floor(Math.random() * 35) + 15),
draw: balls(x, y, color, radius)
};
}
function balls(x, y, color, radius){
ctx.beginPath();
ctx.arc(x, y, radius, 0, 2*Math.PI, false);
ctx.fillStyle = color;
ctx.fill();
ctx.closePath();
}发布于 2015-07-17 01:06:02
您可以简单地将draw分配给balls函数,如下所示:
ball[i] = {
....
draw: balls
};然后,在定义了ball[i]之后,调用它的draw()函数来绘制它:
var b = ball[i];
b.draw(b.x, b.y, b.color ,b.radius); 编辑:如何引用函数ball()本身,而不是使用ball这样的括号。最后一件事,您需要将for (i===0;i<=3; i++)更改为for (i=0;i<=3; i++)。===是严格的比较运算符,=是赋值。
发布于 2015-07-17 01:11:40
使用此方法会使问题变得非常复杂:
function ball(){
this.x = Math.random() * 100;
this.y = Math.random() * 100;
this.radius = Math.random() * 10;
this.color = "#" + (Math.random() * 16777215).toString(16);
this.draw = function(){
ctx.beginPath();
ctx.arc(this.x, this.y, this.radius, 0, 2*Math.PI, false);
ctx.fillStyle = color;
ctx.fill();
ctx.closePath();
}
}
var balls = [];
for(var i = 0; i < 4; i++) {
balls[i] = new ball();
balls[i].draw();
}https://stackoverflow.com/questions/31460262
复制相似问题