我创建了2个对象。一个创建一个canvas对象并将其附加到html的主体,另一个应该绘制一个不是的矩形。我做错了什么?
window.onload = function(){
var oCanvas = {
canvas : document.createElement("canvas"),
ctx : document.createElement("canvas").getContext("2d"),
create : function(){
oCanvas.canvas.id = "canvas";
oCanvas.canvas.width = 350;
oCanvas.canvas.height = 350;
oCanvas.canvas.style.background = "yellow";
document.body.appendChild(oCanvas.canvas);
}
};
var oMap = {
createGrid : function(){
oCanvas.ctx.fillRect(50, 25, 150, 100);
}
};
oCanvas.create();
oMap.createGrid();
};
答案 0 :(得分:2)
要使用自引用的方法,您可以这样做 -
new
关键字创建对象的新实例。现在你可以通过使用例如原型来进一步改进它,但为了简单起见:
function myCanvas() {
/// create a reference to ourselves (saves us some headache later)
var me = this;
/// create a canvas as a property on this instance
this.canvas = document.createElement("canvas");
/// now this.canvas exists and we can get the context
this.ctx = this.canvas.getContext("2d"),
/// metod create which references 'me'
this.create = function(){
me.canvas.id = "canvas";
me.canvas.width = 350;
me.canvas.height = 350;
me.canvas.style.background = "yellow";
document.body.appendChild(me.canvas);
}
};
/// create an instance (you can create several of this)
var oCanvas = new myCanvas();
现在它可以用于 can see in this demo 。
答案 1 :(得分:1)
你正在制作两个独立的画布。定义ctx
属性时,应该引用之前创建的canvas
属性。从对象定义中删除ctx
并在对象已定义后添加到下面:
var oCanvas = {
canvas : document.createElement("canvas"),
...
}
oCanvas.ctx = oCanvas.canvas.getContext("2d");
答案 2 :(得分:0)
更新:似乎我被击败了,这是一个更好的解决方案:https://stackoverflow.com/a/20009730/1634430
您正在创建2个元素,并绘制错误的元素。解决方案在这里:http://codepen.io/zshift/pen/gxoEA。
而不是
...
canvas : document.createElement("canvas"),
ctx : document.createElement("canvas").getContext("2d"),
...
你应该写
var element = document.createElement("canvas");
...
canvas: element,
ctx: element.getContext("2d"),
...
答案 3 :(得分:0)
如果这是一个单个对象,您可以将其保留为对象文字,但如果要创建多个实例,则可以使用构造函数和原型。可以找到构造函数和原型的介绍here。
假设只有一个oCanvas实例正在使用中,您可以将代码更改为:
var oCanvas = {
canvas : document.createElement("canvas"),
ctx : null,/can't set it to anything yet
//oCanvas doesn't exist yet here
create : function(){
oCanvas.canvas.id = "canvas";
oCanvas.canvas.width = 350;
oCanvas.canvas.height = 350;
oCanvas.canvas.style.background = "yellow";
document.body.appendChild(oCanvas.canvas);
//set the context now
this.ctx = this.canvas.getContext("2d");
}
};
var oMap = {
createGrid : function(){
oCanvas.ctx.fillRect(50, 25, 150, 100);
}
};
oCanvas.create();
oMap.createGrid();