Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically calling Canvas Functions

Is there any way to call canvas functions using apply() or a similar method, as to dynamically call canvas methods or to be able to pass an array of arguments?

Im looking for this effect context.fillRect.apply(this,args);

like image 615
anson Avatar asked Sep 11 '26 00:09

anson


2 Answers

If I understand you correctly:

var op = "fillRect";    
var args = [
  10, 10, 180, 180  
];
ctx[op].apply(ctx, args);

Example: http://jsfiddle.net/eZwYQ/

like image 75
Lachlan McDonald Avatar answered Sep 12 '26 13:09

Lachlan McDonald


your apply method should work just fine :

function rectangle(){
    ctx.fillRect.apply(ctx,arguments);
}

And of course this can get more "dynamic" :

function doSomethingWithCanvas(context,action,arg1,arg2/*,...argn*/){
    context[action].apply(context,Array.prototype.slice.call(arguments,2));
}

And you could use the same function to fill a rectangle, to draw a circle or to draw a simple line :

// simple line
doSomethingWithCanvas(ctx,'lineTo',10, 100);

// circle
doSomethingWithCanvas(ctx,'arc',275, 275, 200, 0, Math.PI*2, true);

// fillRect
doSomethingWithCanvas(ctx,'fillRect,10, 10, 180, 180);

PS : by providing the canvas context as an argument, you can use this function to draw on any canvas.

like image 20
gion_13 Avatar answered Sep 12 '26 13:09

gion_13



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!