javascript对象MVC画布'类'清理

javascript Object MVC Canvas 'class' decloration

本文关键字:清理 对象 MVC javascript 画布      更新时间:2023-09-26

嗨,我是整个OOJ和原型模式的新手,在构建包含大量html5画布标签的应用程序时,我正在努力学习这一点。

我想创建一个初始的canvas对象来容纳我执行canvas标记所需的标准选项的基础,这些选项需要是动态值,所以下面是我的构造函数(如果这是不正确的,请原谅我的术语)

 //create the view object
    var view = view ||{};
    //generic canvas obj
    view.pageCanvas = function(){
    //incase I need 'this in  a new context'
    var This = this;
//get the canvas
    this.canvas = function(id){ 
        document.getElementById(id).getContext('2d');
        };
//draw a line
    this.line = function (x,y){
        return  this.canvas.lineTo(x,y);
    }; 
//set the line width
    this.linewidth = function(width){
         this.canvas.lineWidth(width);
    };
//set the stroke colour
    this.lineCol = function(colour){
        return this.canvas.strokeStyle = colour;
    }
//draw the line
    this.build = this.canvas.stroke();
};

然后我会用下面这样的东西来称之为

Background = new view.pageCanvas();
    Background.canvas('BG');    
    Background.canvas.line(400 , 0);
    Background.canvas.line(0,500);
    Background.canvas.linewidth(10);
    Background.canvas.lineCol( "blue"); // line color
    Background.canvas.build();

我在这方面出了问题,因为我在"this.canvas.stroke()"上出现了类型错误

有人能告诉我哪里出了问题吗?或者这种模式是否真的不是最好的方法?最终,我希望设计是可扩展的

提前感谢:)

在您的情况下,this.canvas是一个函数,因此您无法解析this.canvas.stroke(),因为您定义的this.canva是一个接受DOM中canvas标记id的函数。

与其将this.cnv作为一个函数,不如将其作为document.getElementById("),这样它将成为对画布对象的引用。

 //create the view object
    var view = view ||{};
    view.setCanvas = function(id) {
        this.canvas = document.getElementById(id).getContext('2d');
    };
    //generic canvas obj
    view.pageCanvas = function() {
      //incase I need 'this in  a new context'
      var This = this;
//draw a line
    this.line = function (x,y){
        return  this.canvas.lineTo(x,y);
    }; 
//set the line width
    this.linewidth = function(width){
         this.canvas.lineWidth(width);
    };
//set the stroke colour
    this.lineCol = function(colour){
        return this.canvas.strokeStyle = colour;
    }
//draw the line
    this.build = this.canvas.stroke();
};

所以setCanvas看起来就像上面的一样,你可以根据需要改变你想用它做什么。