javascript - 运行以下脚本后,只显示一个圆圈。为什么?我该如何修复它?

标签 javascript html canvas

我试图在 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/

相关文章:

javascript - 使用 javascript 将 HTML 代码添加到 div 中

html - div 周围的样式边框

javascript - Canvas 重复矩形不是唯一的

android - 如果在 "%"中设置,CSS 将不起作用

javascript - 不点击任何东西调用一个函数

javascript - 使用 $(document.createElement()) 时是否需要使用 $(document).ready() ?

javascript - 为什么我的 Promise 定义会被执行?

canvas - 如何找出 Canvas 中贝塞尔曲线中特定点的Y坐标?

javascript - Web Worker 在 HTML5 Canvas 处理中内存不足

javascript - Js 聊天 Controller