开发者

How to use HTML5 Canvas functional style

I'm doing some work with HTML5's Canvas element, and I'm wondering how to best implement my own, custom draw functions in a functional way. Each of these will need the context, but I can think of multiple ways to give it to them:

  1. Add it as a parameter to each draw function call
  2. Add it as a global variable
  3. Call "getContext" in each draw method.
  4. Extend the prototype of ´CanvasRenderingContext2D´.

I don't like to use global variables if I can avoid it, so I'm phasing out option 2. Option 3 requires way too much code duplication, so I also ignore that.

This leaves me with choice 1, which is how I would do it in a non-functional language and 4 which is in my opinion the cleanest approach, but I'm not entirely sure it won't lead to problems. How do you do it? Is there a reason why I shouldn't go with option 4?

To illustrate this, I'll add a code example for each of the remaining option. Here's option 1:

function drawPerson(context, ...) {
    context.fillRect(...);
    ...
}

$(function() {
    var context = $("#canvas")[0].getContext("2d");
    drawPerson(context, ...);
});

And h开发者_StackOverflowere option 4:

CanvasRenderingContext2D.prototype.drawPerson = function(...) {
    this.fillRect(...);
    ...
}

$(function() {
    var context = $("#canvas")[0].getContext("2d");
    context.drawPerson(...);
});


Another option is to use a module which contains all drawing functions and initialize():

var Painter = (function(){

  var context = null;

  return {
    init : function(ctx){
      context = ctx;
    },
    drawPerson : function(){
      /* do stuff with context*/
    }
  }

})(); 

Painter.init($("canvas").getContext("2d"));
Painter.drawPerson();

That way there is only one global var, context is set only once and you don't mess with other objects.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜