我是画布的新手,我正在尝试创建一个小型游戏。我正在尝试在屏幕上渲染某些形状,但是由于某种原因,这些形状没有出现。这些方法被调用,形状被添加到数组中,但是屏幕上没有任何渲染。
const canvas = document.getElementsByClassName('gameContainer');
const context = canvas[0].getContext('2d');
let canvasWidth = window.innerWidth;
let canvasHeight = window.innerHeight;
let shapes = [];
class Shape {
constructor(x, y, rad) {
this.x = x;
this.y = y;
this.rad = rad;
}
createShape() {
context.beginPath();
context.arc(this.x, this.y, this.rad, 0, 2 * Math.PI, false);
context.fillStyle = '#000';
context.fill();
}
}
class CanvasState {
constructor() {
this.canvas = canvas[0];
this.canvas.height = canvasHeight;
this.canvas.width = canvasWidth;
this.shapes = shapes;
}
addShape() {
setInterval(function() {
const randomRad = randomNum(10, 100);
const shape = new Shape(randomNum(randomRad, canvasWidth - randomRad), -randomRad, randomRad);
shape.createShape(this.context);
shapes.push(shape);
}, 1000);
}
}
function randomNum(min, max) {
Math.round(Math.random() * (max - min) + min);
}
function init() {
const cvs = new CanvasState();
cvs.addShape();
}
window.onload = function() {
init();
}
我们将不胜感激,谢谢!
答案 0 :(得分:0)
假设您有randomNum
的有效实现,则以下几行会导致y坐标始终为负:
const randomRad = randomNum(10, 100);
const shape = new Shape(randomNum(randomRad, canvasWidth - randomRad), -randomRad, randomRad);
因此所有形状都从屏幕上绘制了。