scrblnrd3
scrblnrd3

Reputation: 7416

Add function to context of canvas

I'm working on creating some libraries for math in javascript, and one of those would be a grapher in canvas. What I'm aiming to do is this.

ctx.graph('sin(x)');

or something like that. How would I add a method to the ctx of a canvas? One other thing I was considering was something like

graph(ctx,'sin(x)');

and then using eval to do it.

Thanks.

Upvotes: 0

Views: 436

Answers (1)

markE
markE

Reputation: 105015

You extend the prototype of the context object to include your graph.

Put this code in a .js file and include that file with your projects:

var canvasPlusGraph=document.createElement("canvas");
var contextPlusGraph=canvasPlusGraph.getContext("2d");

Object.getPrototypeOf(contextPlusGraph).graph=function(...) {

    // do your graph code
}

Upvotes: 1

Related Questions