【发布时间】:2018-06-10 20:25:49
【问题描述】:
我正在尝试自学 javascript,因此我决定使用 HTML5 和 canvas 做一个项目,但在我的代码中遇到了一个我无法弄清楚的错误。我将上下文声明为变量 c,但在任何引用 c 的函数和对象定义中,诸如 c.beginPath() 之类的东西都显示为未定义。但是,如果这样的引用在函数之外起作用。我正在密切关注画布上的在线教程,我看不出我正在做的事情和教程正在做的事情之间有什么区别,这会使我的代码无法运行。我的大部分代码都在下面,而对 draw 方法的调用给我带来了麻烦。任何帮助将不胜感激!
var canvas = document.querySelector('canvas');
var w = window.innerWidth;
var h = window.innerHeight
canvas.width = w;
canvas.height = h;
var c = canvas.getContext('2d');
// circle object
function Circle(x, y, dx, dy, r, color) {
this.x = x;
this.y = y;
this.dx = dx;
this.dy = dy;
this.r = r;
this.color = color;
this.draw = function() {
c.beginPath();
c.arc(this.x, this.y, this.r, 0, 2 * Math.PI, false);
c.strokeStyle = this.color;
c.stroke();
c.fill();
}
this.update = function() {
if (this.x + this.r > w || this.x - this.r < 0) {
this.dx = -this.dx;
}
if (this.y + this.r > h || this.y - this.r < 0) {
this.dy = -this.dy;
}
this.x += this.dx;
this.y += this.dy;
this.draw();
}
}
<canvas></canvas>
【问题讨论】:
标签: javascript html oop canvas scope