我试图在 Canvas 上“画”几个“球”。我写了这个小脚本,但运行后,只显示一个圆圈。看起来它正在绘制同一个“圆形”100 次。为什么?
这是我的 app.js:
var canvas = document.getElementById("cv");
let width = window.innerWidth * 0.98;
let height = window.innerHeight * 0.97;
canvas.width = width;
canvas.height = height;
var context = canvas.getContext("2d");
var boubles = [];
var createBouble = function() {
this.x = width * Math.random();
this.y = height * Math.random();
this.color = getColor();
this.radius = 30 + (Math.random() * 50);
// console.log(this);
return this;
}
var getColor = function() {
return 'rgba(' + (Math.random() * 255) + ', ' + (Math.random() * 255) + ', ' + (Math.random() * 255) + ', ' + 0.3 + ')';
}
var generateBoubles = function(amount) {
for (let i = 0; i < amount; i++) {
boubles.push(createBouble());
}
drowBoules();
}
var drowBoules = function() {
context.clearRect(0, 0, canvas.width, canvas.height);
for (let i = 0; i < boubles.length; i++) {
drowBouble(i);
}
}
var drowBouble = function(index) {
context.fillStyle = boubles[index].color;
context.arc(boubles[index].x, boubles[index].y, boubles[index].radius, 0, 2 * Math.PI);
context.fill();
}
generateBoubles(10);
<canvas id="cv"></canvas>
最佳答案
在函数中
var createBouble = function() {
this.x = width * Math.random();
this.y = height * Math.random();
this.color = getColor();
this.radius = 30 + (Math.random() * 50);
// console.log(this);
return this;
}
当您console.log
this
时,它总是结果是window
对象。
这是因为它被视为正常功能。
创建新对象时应使用 new
关键字。
即应该是
var generateBoubles = function(amount) {
for (let i = 0; i < amount; i++) {
boubles.push(new createBouble()); // use new here
}
drowBoules();
}
关于javascript - 运行以下脚本后,只显示一个圆圈。为什么?我该如何修复它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56827401/