» tagged pages
» logout
qooxdoo
Return to qooxdoo blog

Let there be color in the browser

Tags Applied to this Entry

1 person has tagged this page:

I always wanted to play with the browser's canvas element but never really found the right toy project. Then I read Ariya Hidayat's blog post "Let there be color". He has implemented the HSL color pie using Qt's 2D drawing canvas. How hard would it be to put something like this into the browser? I decided to try the port of his code to JavaScript and render the pie using only canvas. If this worked out maybe I could embed it into nice little qooxdoo windows.

HSV Pie

Once I figured out how to realize "putPixel" and "getPixel" functions in canvas the port was merely a copy and paste with some minor changes. Right now I use the canvas methods "getImageData" and "putImageData" to obtain and render a pixel buffer. Unfortunately these methods are only available in Firefox. I'm still looking for an alternative for Opera and Safari. The last missing part was the conversion from HSV to RGB but luckily I could drop in a modified version of qooxdoo's hsbToRgb method.

Now the port could start. What really intrigued me was that the main algorithm was nearly the same as the C++ code. Just take this code fragment from the original code:

for (int i = 0; i < radius; i++) {
  qreal hue = 1 - init;
  qreal sat = 1 - qreal(i) / radius;
  for (int d = 0; d < depth; d++) {
    qreal value = 1 - qreal(d) / depth;
    QColor color = QColor::fromHsvF(hue, sat, value);
    img-&gt;setPixel(width / 2 - radius + i + 1, center + d, color.rgb());
  }
}

and compare it to the ported JavaScript:

for (var i = 0; i < radius; i++) {
  var hue = 1 - init;
  var sat = 1 - i / radius;
  for (var d = 0; d < depth; d++) {
    var value = 1 - d / depth;
    var color = hsbToRgb(hue, sat, value);
    setPixel(img, width / 2 - radius + i + 1, center + d, color);
  }
}

Basically only the variable declaration is different. The same is true for almost all of the relevant code. My first version was an all in one HTML file with the JavaScript code embedded. I used no framework, just plain JavaScript.

Of course I wanted to use some qooxdoo, so the next iteration was to put this into a qooxdoo application. Up to now qooxdoo had no support for embedding canvas elements into a qooxdoo widget. I used much of the new 0.8 widget infrastructure to create a canvas embedding widget. With this widget I could take the code from my first version and embed it into a qooxdoo window. You can see this application life or download the sources. This code is based on the latest qooxdoo 0.8 trunk.

Have fun!

Username:
Password:
(or Cancel)