简体   繁体   English

如何向Html5 Canvas添加方法?

[英]How To Add Methods to Html5 Canvas?

I am working on a project using Html5 canvas , i want to add methods to Canvas Object . 我正在使用Html5 canvas进行项目,我想向Canvas Object添加方法。 Something Like This ... 像这样的东西...

HtmlCanvas.alert = function() { alert("width : " + this.width + ", height : " + this.height) }; // adding method
var canvas1 = document.getElementById("myCanvas1"); // getting canvas1
canvas1.width = 200; // setting width
canvas1.height = 200; // setting height

var canvas2 = document.getElementById("myCanvas2"); // getting canvas1
canvas2.width = 100; // setting width
canvas2.height = 100; // setting height

canvas1.alert(); // alert info
canvas1.alert(); // alert info

I strongly recommend not to try to extend native objects of web browsers. 我强烈建议不要尝试扩展Web浏览器的本机对象。

  • It is very bad programming practice to stick new functions to classes which are out of your control. 将新功能粘贴到您无法控制的类上是非常糟糕的编程习惯。 It decreases the maintainability of the code base. 它降低了代码库的可维护性。

  • Web security might not like the idea you messing with native objects prototypes Web安全可能不喜欢您弄乱本机对象原型的想法

  • You cannot guarantee Canvas API stays as the same in the future browsers and thus your functions might clash with the future browsers 您不能保证Canvas API在将来的浏览器中保持不变,因此您的功能可能会与将来的浏览器发生冲突

Instead use encapsulation or proxy design proxy patterns and write your own Canvas class wrapper where you can add your own methods. 而是使用封装或代理设计代理模式,并编写自己的Canvas类包装器,在其中可以添加自己的方法。

More about the matter in this (almost related) question: 有关此(几乎相关的)问题的更多信息:

Subclassing CanvasRenderingContext2D 子类化CanvasRenderingContext2D

However if you want to do it after all this discouragement adding new functions to existing JavaScript objects is easy as: 但是,如果您希望这样做,那么在现有的JavaScript对象中添加新功能很容易,因为:

var c = document.getElementById("myCanvas1");

c.alert = function() {
     alert("xxx");
}


c.alert();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM