Paint on a canvas like Van Gogh
I've been reading Dive into HTML 5, an excellent book from Mark Pilgrim which introduces many aspects and innovations of HTML 5. As always, I thought that reading alone could not suffice, and to improve my learning I started exercising with the browser. Practicing is by far a better way to retain information in comparison to simple reading and studying, and forces you to immediately deal with possible issues in coding with these new features.
So I won't try to code complex examples like bright, moving rainfalls and ancient paintings, but just what you need to get started. The <canvas> element is supported in Firefox 3, where this code has been tested, and many other browsers.
The additions in the DOM
The canvas has a coordinate system, which starts from the top left corner, like in every computer graphical system (this convention was originally borrowed from televisions).
Once you have access a canvas, you can ask it for his context, which is the main object in a canvas, where you call every single method. Only the 2d context esists yet, but there is the possibility of including multiple functionalities in the future.
Besides the context, another important concept is the path: a set of element with equal styling properties (for example color), that can be drawn and managed at the same time. Whenever you want to start drawing an isolated set of lines, for example with a new fancy color, you probably want to create a new path so that your changes to the stroking style are not reflected to the whole drawing.
More featuresSome features are not treated here, but be aware that they are available in most browsers the have started implementing the draft HTML 5 specification. For example you may draw:
- arcs and circles
- Bezier curves
- images by insertion (already existing ones).
I have talked too much for today, so let's give you my code. The basic features of <canvas> are exercised here: feel free to paste it in a blank HTML document and start hacking with your browser, or to suggest what to explore next.
(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)