Activate your free membership today | Log-in

Friday, May 9th, 2008

Processing.js: Port of the Processing language to JavaScript and Canvas

Category: JavaScript, Canvas

Processing.js

John Resig has completed 7 months of work to produce a port of Processing, the “programming language and integrated development environment (IDE) built for the electronic arts and visual design communities”, which aims to teach the basics of computer programming in a visual context, and to serve as the foundation for electronic sketchbooks. One of the stated aims of Processing is to act as a tool to get non-programmers started with programming, through the instant gratification of visual feedback.”

Processing.js uses Canvas and obviously JavaScript to get the job down in the browser.

John talks about the two pieces of the puzzle:

The Processing Language

The first portion of the project was writing a parser to dynamically convert code written in the Processing language, to JavaScript. This involves a lot of gnarly regular expressions chewing up the code, spitting it out in a format that the browser understands.

The language includes a number of interesting aspects, many of which are covered in the basic demos. Here’s a brief selection of language features that are handled:

  • Types and type casting - Type information is generally discarded, but becomes important in variable declaration and in casting (which is generally handled well).
  • Classes - The full class system is supported (can be instantiated, etc. just fine).
  • Method overloading and multiple constructors - Within classes you can have multiple method (or constructor) definitions - with the appropriate methods being called, based upon their signature length.
  • Inheritance - Even classical-style inheritance is supported.

Note: There’s one feature of Processing that’s pretty much impossible to support: variable name overloading. In Processing you can have variables and functions that have the same name (e.g. float size = 0; float size(){}). In order to support this there would have to be considerable overhead - and it’s generally not a good practice to begin with.

The Processing API

The second portion of the project is the full 2d Processing API. This includes all sorts of different methods:

  • Shapes drawing
  • Canvas manipulation
  • Pixel utilities
  • Image drawing
  • Math functions
  • Keyboard and mouse access
  • Objects (point, arrays, random number generators)
  • Color manipulation
  • Font selection and text drawing
  • Buffers

Congratulations to John, and I look forward to seeing some fantastic visualizations in the browser thanks to this work.

Posted by Dion Almaer at 12:54 am
5 Comments

++++-
4.4 rating from 16 votes

Monday, May 5th, 2008

Compression using Canvas and PNG

Category: JavaScript, Canvas

The image above is the 124 kilobyte Prototype library embedded in a 30 kilobyte 8 bit PNG image file.

Jacob Seidelin had some fun this weekend it appears and created a script that can read in JavaScript code from images. To do this, he used the canvas getImageData() method.

Here are the detailed steps:

The first step was to find the best image format for the job, that means the one that gives the best compression while still being lossless. Here on the intertubes, we don’t get a lot of image format choices and since JPEG is lossy, we’re down to GIF and PNG.
For PNG we have two options, 24 bit and 8 bit. Using 24 bit RGB colors, we can store 3 bytes of data per pixel while 8 bit indexed colors only gives us 1 byte per pixel.
A quick test in Photoshop tells us that a 100×100 image with random 24 bit colored noise compresses down to about 20 KB while a 300×100 image with random 8 bit monochromatic noise compressed down to just 5 KB. A regular 8 bit GIF comes in a bit heavier than the 8 bit PNG, so we go with the PNG option.

Now we need to convert our Javascript file into color data and stuff it in a PNG file. For this purpose, I crafted this quick and dirty PHP script, which reads the Javascript file, creates a PNG image file and simply lets each pixel have a value 0-255 corresponding to the ascii value of the character in the script.

I ran into a problem here, since the image is created as a truecolor image and we need it to be 8 bit indexed and PHP won’t make an exact conversion. I guess there are ways to create a palletted image from scratch in PHP/GD, but I haven’t looked into that yet. The solution for now is to simply run the generated image through something like Photoshop and convert it to 8 bit there.

So now we have the Javascript all nice and packed up in a compressed PNG file and now we need to get it out again in the client. Using the canvas element, we simply paint the picture using drawImage() and then read all the pixel data using getImageData(). This data is given to us as a large array of values, where each pixels takes up 4 elements (RGBA), so we just take every 4 value and tack them all together into an eval()-ready string. And we’re done.

And the reading function is here.

NOTE: This is for fun, and isn’t meant to be used in the real world. That being said, see it at work in the mario game.

Posted by Dion Almaer at 10:28 am
19 Comments

++++-
4.8 rating from 26 votes

Thursday, April 24th, 2008

Using canvas to test your site with colorblind folk

Category: Library, Accessibility, Canvas

Color Matrix

The picture above is showing you how someone with the color blindness trait Tritanopia would see the image. Michael Deal first created the Color Matrix Library, which supports a large portion of the most common color functions available, including:

Hue, Saturation, Brightness, Contrast, Exposure, Temperature, Tint, Channels, Blindness, Colorize, Threshold, and Invert

Michael then created a canvas library that uses the Color Matrix to help us visualize what our content may look like to people who have various color blind issues. Here is what he did:

The most obvious way would be to do the calculations in CIE XYZ using confusion lines, however, <canvas> uses RGB. So you’d have to convert from XYZ to RGB, run the confusion lines, then convert back to RGB. Here’s an example of what that looks like: Color Blindness Library — It’s great for running on a few colors, but too slow for larger images.

Matrix’s are generally about as quick as you’re going to get for generic color filters, so that’s what I’ve converted the formulas into – compliant with Actionscript’s ColorMatrix, and other programming languages that use standard RGBA matrix’s. Also, I’ve converted them into color transform’s which are useful in Actionscript (ColorTransform), Pixelmator (Image… Channel Mixer), and Photoshop (Image… Adjustments… Channel Mixer).

I used data generated by Matthew Wickline’s formulas to base my blindness library. My script triangulates the hue by comparing the un-filtered, completely saturated, RGB values with the same value after they’d been run through Wickline’s formula.

Posted by Dion Almaer at 1:35 pm
4 Comments

++++-
4.6 rating from 21 votes

Wednesday, April 16th, 2008

Busy.js: Loading indicators with Canvas

Category: JavaScript, Library, Canvas

Busy.js Logo

Christian Effenberger is back with some more canvasy goodness. He has released Busy.js, a library that allows you to add/remove loading indicators to html elements on your webpages (inc. overlay color & transparency). It uses unobtrusive javascript to keep your code clean. Requires no plugin/extension or any other external resource.

Usage

JAVASCRIPT:
  1.  
  2. var ctrl = getBusyOverlay(document.getElementById('box'));
  3. ctrl.remove();
  4.  

Features

  • supports Canvas and VML (identical representation)
  • Fast and easy to implement (perfect for ajax applications)
  • Don't need to spend time in an image editor creating gif animations
  • Very flexible by multiple (optional) parameters for individual styles
  • Get always a proper loading indicator independently of parent elements style
  • Moves the DOM tree up to find the next parent block-level element
  • Freezes the parent element visual (overlay) and technical (mouse events)
  • Works with html elements even if (moz/webkit)-border-radius is activated
  • In older browsers, the script degrades to simple quadratic shapes
  • It's dead easy to add or remove the loading indicator to/from an html element

Busy.js

Posted by Dion Almaer at 9:13 am
5 Comments

+++--
3.9 rating from 29 votes

Wednesday, April 9th, 2008

Canvas2Image: Save out your canvas data to images

Category: JavaScript, Library, Canvas

Ajax Canvas

More from Jacob Seidelin. He has created Canvas2Image, a library that takes <canvas> data and makes an image out of it. This means that you can create canvas images on the fly and then:

JAVASCRIPT:
  1.  
  2. var strDataURI = oCanvas.toDataURL()
  3. // returns "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAMgAAADICAYAAACt..."
  4.  

See the full API in use here:

JAVASCRIPT:
  1.  
  2. /*
  3. * Canvas2Image.saveAsXXXX = function(oCanvasElement, bReturnImgElement, iWidth, iHeight) { ... }
  4. */
  5.  
  6. var oCanvas = document.getElementById("thecanvas");
  7.  
  8. Canvas2Image.saveAsPNG(oCanvas)// will prompt the user to save the image as PNG.
  9.  
  10. Canvas2Image.saveAsJPEG(oCanvas); // will prompt the user to save the image as JPEG.
  11.                                   // Only supported by Firefox.
  12.  
  13. Canvas2Image.saveAsBMP(oCanvas)// will prompt the user to save the image as BMP.
  14.  
  15.  
  16. // returns an <img /> element containing the converted PNG image
  17. var oImgPNG = Canvas2Image.saveAsPNG(oCanvas, true);   
  18.  
  19. // returns an <img /> element containing the converted JPEG image (Only supported by Firefox)
  20. var oImgJPEG = Canvas2Image.saveAsJPEG(oCanvas, true);
  21.                                                        
  22. // returns an <img /> element containing the converted BMP image
  23. var oImgBMP = Canvas2Image.saveAsBMP(oCanvas, true);
  24.  
  25.  
  26. // all the functions also takes width and height arguments.
  27. // These can be used to scale the resulting image:
  28.  
  29. // saves a PNG image scaled to 100x100
  30. Canvas2Image.saveAsPNG(oCanvas, false, 100, 100);
  31.  

Posted by Dion Almaer at 10:00 am
7 Comments

+++++
24527.7 rating from 42 votes

Super Mario; 14KB of JavaScript

Category: JavaScript, Fun, Games, Canvas

Jacob Seidelin is doing great work, and for something fun, he build a piece of Super Mario in just 14KB of JavaScript:

Here's an experiment in keepings things small and confined to one Javascript file. There are no external image files or anything, everything is rendered with Javascript using either canvas elements or old fashioned div-making tactics (for IE). The sprites are stored in custom encoded strings in a format that only allows 4 colors for each sprite but in turn only takes up around 40-60 bytes per sprite.

We also have MIDI music embedded as base64-encoded data: URI's. No music for IE, though, and it seems all the other browsers each have different, minor problems with it, but it sort of works.

Posted by Dion Almaer at 12:39 am
15 Comments

+++++
2.754661662493E+48 rating from 116 votes

Monday, March 17th, 2008

cvi_text_lib: cross API text stroking

Category: JavaScript, Library, Canvas

Christian Effenberger, or Mr. Canvas as we think of him, has come back from a data recovery nightmare with a new library, cvi_text_lib, that supports stroke text capability for Canvas & VML.

It uses unobtrusive javascript to keep the code clean and it works in all the major browsers - Mozilla Firefox 1.5+, Opera 9+, Safari and IE6+.

Features

  • supports Canvas and VML (identical representation)
  • font format supports moves, lines and curves (bezier & quadratic)
  • font characters 30-127 and 160-255 (charset UTF-8 or ISO-8859-1)
  • font type (built in) is a sans-serif multiple master single
    line stroke font, similar to "VAG Rounded" and "DIN 17"
  • expandable with custom font types/faces
  • font size is limited to min 1 max 99999 default is 12px
  • font weight is limited to min 1 max 400 default is 100%
  • font width is limited to min 10 max 400 default is 100%
  • font spacing is limited to min 10 max 1000 default is 100%
  • uncompressed lib is 32 KBytes (inc. sans-serif font)
  • the integrated sans-serif font is also adaptable for SVG

Here it is at work:

HTML:
  1.  
  2. <script src="cvi_text_lib.js"></script>
  3.         var context = canvas.getContext('2d');
  4.         set_textRenderContext(context);
  5.         if(check_textRenderContext(context)) {
  6.                 ...
  7.                 context.strokeText(text,x,y,fontsize);
  8.                 ...
  9.         }
  10. </script>
  11. <!--[if gte IE 6]>
  12.         if(check_strokeTextCapability()) {
  13.                 ...
  14.                 string = get_strokeText(text,x,y,fontsize)
  15.                 document.getElementById("div").innerHTML += string;
  16.                 ...
  17.         }
  18. </script>
  19. <![endif]-->
  20.  

CVI Text Library

Posted by Dion Almaer at 7:28 am
4 Comments

++++-
4.7 rating from 24 votes

Tuesday, February 26th, 2008

Canvas Polar Clock

Category: JavaScript, Prototype, Articles, Canvas

"agrath" has developed a very nice Canvas example using Prototype that makes use of a common Prototype-isms: Object.extend, Class.create, bind, enumerables, $w, $.

The Polar Clock is a different visualization of time and the example walks through all of the work required to implement it using Prototype 1.6.0.2 and Canvas, including the draw method:

JAVASCRIPT:
  1.  
  2. draw:function(){
  3.     this.clearCanvas();
  4.     var w = 20;
  5.     var r = 260;
  6.     this.date = new Date();
  7.     var cr = r;
  8.     $('labels').update()
  9.     $w("month day weekday space hour min second").reverse().each(function(interval){
  10.         cr = cr - w - w/2;
  11.         if(interval != 'space')
  12.         {
  13.             var ir = this.intervalToDegrees[interval].bind(this.date)();
  14.             var i = ((ir / 360) * 255) + 147;
  15.             var color = this.cc.rgbToCss(this.cc.hslToRgb(i.wrap(0,255),205,127));
  16.             this.drawSolidArc(color, cr, w, ir.toRadians());           
  17.             $('labels').insert(this.getIntervalLabel[interval].bind(this.date)() + '<br />');
  18.         }
  19.     }.bind(this));
  20. },
  21.  

The article walks through a lot of Canvas as well as the Prototype side of things. Very thorough.

Posted by Dion Almaer at 6:31 am
3 Comments

+++--
3.7 rating from 18 votes

Tuesday, February 5th, 2008

Canvas Pie Chart from datatable

Category: Canvas, Unobtrusive JS

I love it when a plan comes together (removes cigar): After I played with Google charts and porting the idea of generating charts from accessible table data over to YUI charts Stoyan Stevanof had to use the same idea to generate his own, home-made Canvas-driven charts:

Example chart generated from a data table using canvas

His solution shows in a few lines not only how to get the data from a table, but also how to do a pie chart in canvas.

Posted by Chris Heilmann at 1:24 pm
5 Comments

+++--
3.4 rating from 16 votes

Thursday, December 20th, 2007

Mapper.js 1.0: Highlighting for imagemaps

Category: JavaScript, Library, Canvas

Christian Effenberger has doubled up to release Mapper.js 1.0, a library that allows you to add automatic area highlighting to image maps
on webpages. It uses unobtrusive javascript to keep the code clean.

It works in all the major browsers - Mozilla Firefox 1.5+, Opera 9+,
Safari and IE6+. On older browsers, it can use "jsgraphics" from
Walter Zorn (if installed), else it'll degrade and visitors won't
notice a thing.

You are able to create an image map, and then define the colors through the simple CSS class microformat:

HTML:
  1.  
  2. <img class="mapper iborder00aa00 icolor00ff00" src="images/eu.gif" usemap="#map_of_europe" />
  3.  

Mapper.js

Posted by Dion Almaer at 1:15 am
12 Comments

++++-
4.6 rating from 44 votes

Monday, December 17th, 2007

WireIt: Yahoo! Pipes Canvas Wiring API

Category: JavaScript, Library, UI, Canvas, Yahoo!, Widgets

Eric Abouaf has released WireIt, a library that answers the though: "wow, I wish there was an API that did the UI bits that Yahoo! Pipes does."

WireIt uses canvas, excanvas for IE, and YUI to get the job done. Take a look at the docs to see how it works.

Here is the code for simple terminals:

JAVASCRIPT:
  1.  
  2. var bl = YAHOO.util.Dom.get('blockLeft');
  3. var br = YAHOO.util.Dom.get('blockRight');
  4. var bt = YAHOO.util.Dom.get('blockTop');
  5. var bb = YAHOO.util.Dom.get('blockBottom');
  6.        
  7. for( var i = 0 ; i <7 ; i++) {
  8.         new WireIt.Terminal(bl, {direction: [1,0], offsetPosition:[0,i*50] });
  9.         new WireIt.Terminal(br, {direction: [-1,0], offsetPosition:[0,i*50] });
  10.         new WireIt.Terminal(bt, {direction: [0,1], offsetPosition:[i*50,0] });
  11.         new WireIt.Terminal(bb, {direction: [0,-1], offsetPosition:[i*50,0] });
  12. }
  13.  

And there is even a fun game to check out:

Planar

Posted by Dion Almaer at 9:00 am
Comment here

+++--
3.8 rating from 32 votes

Friday, December 14th, 2007

Canvas Bevel Script

Category: Component, Canvas

The champion of unobtrusive canvas, Christian Effenberger, has come out with a new microformat script that enables you to add bevels to your images (and also shading, shining and glowing).

Why would you want to do this via canvas?

  • Fast and easy to implement. Just add class="bevel" to the image and your good to go
  • Don't need to spend time in an image editor creating images with corners
  • Works really well with forum avatars. Doesn't require additional server work
  • It's dead easy to change the attributes of the corners
  • Free of charge use on non-commercial and private web sites.

The microformat

  • Initialisation class "bevel"
  • vary the radius by adding iradius followed by the desired radius in percent:
    Image radius class "iradius20" - min=20 max=40 default=20
  • vary the masking by adding usemask:
    Image masking class "usemask"
  • vary the masking by adding ibackcol followed by the color:
    Mask color class "ibackcol" - min=000000 max=ffffff default=0080ff
  • vary the masking by adding ifillcol followed by the color:
    Mask color class "ifillcol" - min=000000 max=ffffff default=ibackcol
  • vary the glowing by adding noglow:
    Image glowing class "noglow"
  • vary the glowing by adding iglowopac followed by the desired opacity in percent:
    Glow opacity class "iglowopac" - min=1 max=100 default=33
  • vary the glowcolor by adding iglowcol followed by the color:
    Glow color class "iglowcol" - min=000000 max=ffffff default=000000
  • vary the shining by adding noshine:
    Image shining class "noshine"
  • vary the shining by adding ishineopac followed by the desired opacity in percent:
    Shine opacity class "ishineopac" - min=1 max=100 default=40
  • vary the shinecolor by adding ishinecol followed by the color:
    Shine color class "ishinecol" - min=000000 max=ffffff default=ffffff
  • vary the shading by adding noshade:
    Image shading class "noshade"
  • vary the shading by adding ishadeopac followed by the desired opacity in percent:
    Shade opacity class "ishadeopac" - min=1 max=100 default=50