Html5 canvas – Use of getimagedata – putimagedata or drawimage

Working with new technology always has its unique challenges.

The first being, not enough documentation or examples. So in an effort to help anybody out there working with the Canvas element might find the following useful.

In my Mockuptiger application each widget or icon is a vector so you can scale indefinitely and you will not lose any details. The vectors when drawn upon each other appropriate care is taken to make sure that the vectors maintain their transparency. Because of this delicate balance of transparency, it provides an added benefit that you can mix different shapes and create unique new shapes or icons.




In the above image, there are two separate icons 1 and 2 and they overlap. Since they have the transparency in their background the speaker icon (#2) shows partly.

In our case, both of the icons are drawn onto separate canvas elements so when you try to export them using getimagedata and putimagedate on a bigger merged canvas the transparency is lost.




As you see the partial speaker (#2) that was visible initially is lost when you do a putimagedata.

After much research it became apparent that the putimagedata is very limited. It replaces entire set of pixels of the destination canvas. Ideally it should be able to apply some filters like (OR, AND, XOR etc) that solve and provide some interesting image manipulation techniques.

After reading some material on the net it seems like putimagedata is also better performing than other methods. The other method "drawImage" on the other hand respects the transparency and the good part is you don't have to do any getimagedata. You can simply pass in the source canvas element and draw to the target canvas and boom you get a merged canvas.


And here is the result as desired


In our case, each icon is on its own canvas so to get a merged PDF or PNG, it needed a bigger temporary canvas to be generated and then each element is copied to the merged canvas. So even though putimagedata may be better performing than drawimage, practically we are saving a call to the getimagedata on each individual element. So I guess that should be good for performance as there no benchmarks done to prove it either way.

On a side note, the wireframe application now has all the major components being fully completed or atleast in proof of concept mode.

With the above merged canvas technique, this completes the POC for the PDF and PNG generation. And the good part is you can selectively export the elements to PDF or PNG.

Here is a sample mockup page of dashboard widgets


I then select only few of the widgets



And now when I do an export, I get only the selected ones on the output


Neat,huh ?

Get MockupTiger downloaded on your PC

Posted in Other

Would you like to build your application?

Start by sketching your idea into a wireframe in few clicks