Introduction
Definition
What can it do?
- Shapes: Lines, rectangles, paths, arcs, Bezier curves, quadratic curves
- Effects: strokes, fill, shadows, linear gradients, radial gradients
- Text
- Pixel manipulation
- Compositing: alpha, Composite operation
- Transformations: scale, rotate, transformation matrix, translate
- Image Drawing: load image, canvas, video elements and also allows encoding the image as a png.
Real-Life Usage
- Charts/Graphs
- Images created based on user preferences
- Demonstrations of interesting scientific phenomena
- User-friendly UI apps such as color selector
- Render complex scenes
- Optimized images
- Animations
- Special effects for text
- Drawing applications
Sample Application
In this application, we will consider a sports league website that offers a
feature to design your team logo. To scope the article sample, we allow the user to enter their team name, select a forecolor and a back-color.
On clicking the button, the canvas API is used within javascript to render a
logo image, using the text and colors specified by the user.
For the sake of the demonstration, we draw a rectangular linear-gradient,
combining the font color and the back color, render the background-color
specified by the user, and finally the logo text using the color and text
specified by the user.
Sample in Action
Source Code (save as canvaslogo.htm)


Image: Various logos generated by the application
- <!DOCTYPE html>
- <html>
- <body>
- <form name="logoform">
- <table border=0>
- <tr>
- <td>Team Name (up to 7 characters) </td>
- <td>
- <input type="text" id="teamname" maxlength=7/>
- </td>
- </tr>
- <tr>
- <td>Font color</td>
- <td>
- <input type="color" id="teamfcolor"/>
- </td>
- </tr>
- <tr>
- <td> Backcolor</td>
- <td>
- <input type="Color" id="teambcolor"/>
- </td>
- </tr>
- <tr>
- <td colspan=2>
- <input type="button" value="Preview Logo" onclick="PreviewLogo();"/>
- </td>
- </tr>
- </table>
- <br/>
- <canvas id="myCanvas" width="200" height="100" style="border:1px solid #c3c3c3;">
- Your browser does not support the canvas element.
- <canvas>
- <script type="text/javascript">
- function PreviewLogo()
- {
- var c=document.getElementById("myCanvas");
- var ctx=c.getContext("2d");
- ctx.fillStyle = logoform.teambcolor.value;
- ctx.fillRect(0, 0, 200, 100);
- ctx.font = "40pt Arial";
- ctx.fillStyle = logoform.teamfcolor.value;
- ctx.fillText(logoform.teamname.value, 25, 60);
- var grd=ctx.createLinearGradient(0,0,25,100);
- grd.addColorStop(0,logoform.teamfcolor.value);
- grd.addColorStop(1,logoform.teambcolor.value);
- ctx.fillStyle=grd;
- ctx.fillRect(0,0,25,100);
- }
- </script>
- </form>
- </body>
- </html>
Dipal ChoksiPosted Oct 27, 2011, 2:34 AM
As with any HTML5 feature, please remember to check if the client browser supports the feature that you are trying to use in the application. Happy Coding!