【问题标题】:Javascript Canvas + objects/functionsJavascript Canvas + 对象/函数
【发布时间】: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();
  }
}
&lt;canvas&gt;&lt;/canvas&gt;

【问题讨论】:

    标签: javascript html oop canvas scope


    【解决方案1】:

    我相信有几件事你没有做,这可能会让你感到困惑。

    你有一个类似于 Circle 结构的类。我猜这就是你的代码的意图,但你还没有在任何地方创建该类的实例。

    您需要创建该类的新引用,然后在新对象中调用该类所需的方法。

    我用你自己的代码为你写了一个小提琴。

    类似这样的:

    var j = new Circle(100, 100, 200, 200, 20, 'red');
    j.draw();
    

    https://jsfiddle.net/wu3dcyfm/

    【讨论】:

    • 另外,给定您的代码,您引用的是 strokeStyle,这只会绘制圆圈的边框。如果要画内脏,需要修改 c.fillStyle = 'somecolor'
    • 我觉得你也很想学习一些正确的 OO 机制,所以我冒昧地删除了你所有的全局引用,并将所有内容都包含在类中。 jsfiddle.net/hdx799py 如果您想更进一步,请将画布从 html 本身中完全删除,并在 javascript 中创建它。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-14
    • 2012-10-04
    • 2011-08-22
    • 2021-11-28
    相关资源
    最近更新 更多