最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Dynamically calling Canvas Functions - Stack Overflow

programmeradmin1浏览0评论

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);

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);

Share Improve this question asked Dec 1, 2011 at 5:43 ansonanson 4,1742 gold badges24 silver badges30 bronze badges 2
  • I'm curious, why can't you call them directly? – Lachlan McDonald Commented Dec 1, 2011 at 5:46
  • You can, but like I said, I want to be to call them dynamically using a function string or an array of arguments. This way I dont need to create two separate functions for similar operations. – anson Commented Dec 1, 2011 at 5:50
Add a ment  | 

2 Answers 2

Reset to default 7

If I understand you correctly:

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

Example: http://jsfiddle/eZwYQ/

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.

发布评论

评论列表(0)

  1. 暂无评论