Canvas构造函数

时间:2014-02-18 00:17:10

标签: canvas constructor

画布构造函数看起来像什么?我认为这样的事情,但显然有些错误。

function Canvas(canvas) {
    this.canvas = document.createElement('canvas');
    this.width = 400;
    this.height = 400;
    this.style.border = "1px solid";
    document.body.appendChild(canvas);
    this.context = canvas.getContext('2d');
}

var canvas1 = new Canvas('canvas1');

2 个答案:

答案 0 :(得分:0)

您的代码有几个问题。您没有引用正确的变量。 this是您创建的对象,而不是canvas元素,因此您无法执行this.style.border=和其他类似的分配。这是一个有效的构造函数:

function Canvas(canvas) {
    this.canvas = document.createElement('canvas');
    this.canvas.width = 400;
    this.canvas.height = 408;
    this.canvas.style.border = "1px solid";
    document.body.appendChild(this.canvas);
    this.canvas.context = this.canvas.getContext('2d');
}

答案 1 :(得分:0)

您只引用作为对象本身的this,而不是您创建的画布。这应该有效:

function Canvas(canvasID) {
    this.canvas = document.createElement('canvas');

    this.canvas.width = 400;
    this.canvas.height = 400;

    this.context = this.canvas.getContext('2d');

    this.canvas.style.border = "1px solid";
    this.canvas.id = canvasID;               // or use name

    document.body.appendChild(this.canvas);
}

var canvas1 = new Canvas('canvas1');
canvas1.context.fillRect(0, 0, 400, 400);

当你在函数范围内时,this引用了对象本身。您正在对象(画布等)上设置新属性,以便引用那些您需要在对象内使用相同属性名称的属性,即。 this.canvas等等。

设置id / name真的没什么意义,因为你已经有了对象中元素的引用,除非你使用CSS或查询。

如果没有提供宽度和高度,也可以使用默认值:

function Canvas(canvasID, width, height) {
    this.canvas = document.createElement('canvas');

    this.canvas.width = width || 400;
    this.canvas.height = height || 400;

    this.context = this.canvas.getContext('2d');

    this.canvas.style.border = "1px solid";
    this.canvas.id = canvasID;               // or use name

    document.body.appendChild(this.canvas);
}

var canvas1 = new Canvas('canvas1');              //  400x400
var canvas2 = new Canvas('bigCanvas', 2000, 500); // 2000x500