No More Recursion

In my last post, I mentioned a bug I had where I was creating a processing.js instance from inside the processing library, in order to use it to measure the pixel in text drawn to a canvas, using createGraphics.

What was happening was when you change the processing text, you need to recalculate textLeading (which I was informed it’s lead, as in the metal, and not in what a leader does), which makes a call to textAscent, which sets up the new processing instance, which then reset textLeading, causing an infinite amount of recursion.

I fixed this by instead of calling create graphics, I setup a small class that does exactly what I needed it to do. In other words, I emulated the basic most text drawing functionality of processing. Here is my class:

    var thisStupidThing = function(fontFace, fontSize, baseLine, text) {
      this.canvas = document.createElement('canvas');
      this.canvas.setAttribute('width', fontSize + "px");
      this.canvas.setAttribute('height', fontSize + "px");
      this.ctx = this.canvas.getContext("2d");
      this.ctx.font = fontSize + "pt " + fontFace;
      this.ctx.fillStyle = "black";
      this.ctx.fillRect (0, 0, fontSize, fontSize);
      this.ctx.fillStyle = "white";
      this.ctx.fillText(text, 0, baseLine);
      this.imageData = this.ctx.getImageData(0, 0, fontSize, fontSize);
      this.get = function(x, y) {
        return[((y*(this.imageData.width*4)) + (x*4))];

It went from being a about thirteen thousand lines(all of processing), to fifteen. This also happens to be faster, as we no longer have to load all of processing to do this one simple function.

I think my initial plan of using processing, at first was the right one. It was the quick and easy way to get it working, then I went back and shined it up once I had the rest working.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: