【发布时间】:2014-04-13 22:03:45
【问题描述】:
我有点难过。我还是 Javascript 的新手,所以当涉及到类和对象时,它的一些工作原理让我难以理解。我有很多相关的代码,我在一个简单的 javascript 文件中工作,将它重构为一个工作类似乎很自然。这个过程并不顺利。
在大量 Stackoverflow 和 Google 和 W3Cschool 搜索之后,我现在迷路了。
在构建这个类时,允许调用环境定义一个画布上下文并将该上下文传递给我的类以便它可以工作似乎很自然。但是,因为在浏览器看到它的时候,它还没有被定义。经过一番搜索,我想出了以下内容:
function HexGrid () {
this.canvas = null; // (canvas Context)
this.borderColor = "#FF0000"; // Hex Border Color
this.fillColor = "yellow"; // Hex Fill Color
this.hexSize = 20; // Hex Size Default
// Draw a hex using Offset Coordinates.
// Lets do Offset first, this should be the easiest.
// “odd-q” vertical layout
this.O_hex = function (x, y) {
var width = this.HexSize * 2;
var Horz = 3 / 4 * width;
var Vert = Math.sqrt (3) / 2 * width;
var Hpos = x * (Horz);
var Vpos = (y * Vert) + ( (x%2)*(Vert/2) );
this.drawHex(Hpos, Vpos);
};
// Draw a Hex onto the Canvas.
this.drawHex = function (in_x,in_y) {
console.log ('Canvas = ' + this.canvas);
var ctx = this.canvas;
console.log ('ctx = ' + ctx);
ctx.strokeStyle = this.borderColor;
console.log ('ctx = ' + ctx);
ctx.beginPath();
for (var i = 0; i <= 6; i++) {
angle = 2 * Math.PI / 6 * i
x_i = in_x + size * Math.cos(angle);
y_i = in_y + size * Math.sin(angle);
if (i === 0) {
ctx.moveTo (x_i, y_i);
} else {
ctx.lineTo (x_i, y_i);
}
}
ctx.fillStyle=this.fillColor;
ctx.fill();
ctx.stroke();
};
}
//// TESTING CODE //////
function main () {
Hex = new HexGrid;
Hex.canvas = document.getElementById('canvas_1');
for (var x = 0; x <= 10; x += 1) {
for (var y = 0; y <= 10; y += 1) {
Hex.O_hex (x,y);
}
}
}
我现在得到的是控制台中的以下内容:
Canvas = [object HTMLCanvasElement] hex-a27.js:24
ctx = [object HTMLCanvasElement] hex-a27.js:26
ctx = [object HTMLCanvasElement] hex-a27.js:28
Uncaught TypeError: Object #<HTMLCanvasElement> has no method 'beginPath' hex-a27.js:29
HexGrid.drawHex hex-a27.js:29
HexGrid.O_hex hex-a27.js:19
main hex-a27.js:53
onload Aquarius-a27.php:8
这表明我确实在 ctx 中获得了一个画布引用,但它说它找不到 beginPath() 方法。我担心我的作业甚至没有进入画布上下文。从评估代码时可能不存在的 Javascript 访问 DOM 元素的方法的正确方法是什么? (即您稍后创建它并将其传入,或将其分配给属性。)
基本上,我需要某种类型的原型设计(这里想 C'ish):“是的,会有一个名为 beginPath() 的方法和一个名为 strokeStyle 的属性,所以,如果你能找到,请不要惊慌他们还没有......或者我只需要另一种可行的方法。
谢谢。
【问题讨论】:
-
var ctx = this.canvas.getContext('2d'); // 你确定你调用了 html canvas 元素的二维上下文的方法吗?
标签: javascript html object dom canvas