简体   繁体   中英

How To Add Methods to Html5 Canvas?

I am working on a project using Html5 canvas , i want to add methods to 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.

  • 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

  • You cannot guarantee Canvas API stays as the same in the future browsers and thus your functions might clash with the future browsers

Instead use encapsulation or proxy design proxy patterns and write your own Canvas class wrapper where you can add your own methods.

More about the matter in this (almost related) question:

Subclassing CanvasRenderingContext2D

However if you want to do it after all this discouragement adding new functions to existing JavaScript objects is easy as:

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

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


c.alert();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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