Home › Documentation › HTML5: Painting with Canvas
HTML5: Painting with Canvas
Canvas is a new element in HTML5, it used to create scriptable graphics. Canvas element is based on on the WHATWG canvas specification.
Before canvas element appears in HTML that was a pain for developers to create dynamic graphics on the web page. To paint something, without canvas, you need to implement some trics with CSS or use third party plugins like Flash or Java applets. With canvas all you need just to put element on your page and paint anything your want with JScript.
Canvas element is not so interesting. To put it on the page you just need to add something like this to your page body:
All the magic is in the JScript. From the script you can:
Drawing tools
Effects
Transformations
And much more...
In this article we will see how to paint on the page with canvas element on a simple example. This will be a simple painting application.
You can play online with this application here. Source code is attached to this article.
To create our painting application we need to complete several important steps.
All we need is to create minimal HTML document
Here is
In this example canvas element has only one attribute id to find this element on the page. Other attribute like width and height will be setupped on the script side.
First we need to initialize our canvas and mouse handling functions:
Canvas width and height is equals to window width and height, because we are going to use entire screen for paint. context variable will hold pointer to the canvas context, what will be passed to painting functions. Actually all the painting is goings on the canvas context, but not on canvas itself.
Next we setup listener functions to handle mouse down and touch events (for touch screens).
initColorPicker - setups color picker for our application:
Color picker is created dynamically. If you like to add more colors to color picker just add more colors to colors array. If element of color picker will be clicked - color of this element will be selected as brush color. Here is a click handler:
First selected color is parsed and next choosen color is saved in global variable strokeColor for future use.
Let see on mouse handling functions:
As you can see on mouse down and touch event beginStroke is called and new listeners is created. We need a new listeners to get know - when to finish to paint using our brush.
Brush is a class what implements some painting function and brush functionality. Why Brush implemented as separated class? Answer is simple - if you going to add more brushes all you need is just to create more brush classes. Let see on Brush implementation:
Most interesting thing here is a doStroke function. This function paint lines on the canvas context each time user holds the mouse button and moves cursor around canvas.
lineWidth - width of line, you can play with this parameter to see how it affects the resulted line
strokeStyle - color of the line
beginPath - start paint the path
moveTo - move start point to the specified position
lineTo - paint the line from the start point (moveTo) to the specified point
stroke - paint final line on the context
That is all. As you can see painting on the web page is not complex. all is simple. Put canvas on your page, get canvas context and paint anything you need with script.
Before canvas element appears in HTML that was a pain for developers to create dynamic graphics on the web page. To paint something, without canvas, you need to implement some trics with CSS or use third party plugins like Flash or Java applets. With canvas all you need just to put element on your page and paint anything your want with JScript.
Canvas element is not so interesting. To put it on the page you just need to add something like this to your page body:
<canvas id='canvas'></canvas>
All the magic is in the JScript. From the script you can:
Drawing tools
- Rectangles
- Arcs
- Ellipsis
- Paths, line drawing
- Bezier, quadratic curves
Effects
- Fills and strokes
- Shadows
- Linear and radial gradients
- Alpha transparency
- Compositing
Transformations
- Scaling
- Rotation
- Translation
- Transformation matrix
And much more...
In this article we will see how to paint on the page with canvas element on a simple example. This will be a simple painting application.
You can play online with this application here. Source code is attached to this article.
To create our painting application we need to complete several important steps.
- Settings up HTML file with canvas element
- Setting up a script to paint on canvas context
- Setting up mouse event handlers
- Setting up painting functions
HTML file
All we need is to create minimal HTML document
<!DOCTYPE HTML> <html lang="en"> <head> <script type="text/javascript" src="script/brush.js"></script> <script type="text/javascript" src="script/main.js"></script> </head> <body> <div> <div id='picker' class='picker'></div> <canvas id='canvas'></canvas> </div> </body> </html>
Here is
<div id='picker' class='picker'>is a element for future use, this element will hold a color picker.
In this example canvas element has only one attribute id to find this element on the page. Other attribute like width and height will be setupped on the script side.
Script file
First we need to initialize our canvas and mouse handling functions:
function init() { canvasWidth = window.innerWidth; canvasHeight = window.innerHeight; canvas = document.getElementById("canvas"); canvas.width = canvasWidth; canvas.height = canvasHeight; canvas.style.cursor = 'crosshair'; context = canvas.getContext("2d"); brush = new Brush(context); window.addEventListener('mousemove', onWindowMouseMove, false); canvas.addEventListener('mousedown', onCanvasMouseDown, false); canvas.addEventListener('touchstart', onCanvasTouchStart, false); initColorPicker(); }
Canvas width and height is equals to window width and height, because we are going to use entire screen for paint. context variable will hold pointer to the canvas context, what will be passed to painting functions. Actually all the painting is goings on the canvas context, but not on canvas itself.
Next we setup listener functions to handle mouse down and touch events (for touch screens).
initColorPicker - setups color picker for our application:
function initColorPicker() { picker = document.getElementById('picker'); var colors = ["#000000", "#FFAEC9", "#CC666A", "#B97A57", "#ED1C24", "#6B442E", "#993333", "#EFE4B0", "#FFF880"]; for(var i = 0; i < colors.length; ++i) { color = document.createElement("div"); color.className = "color"; color.style.backgroundColor = colors[i]; color.addEventListener('mousedown', onStrokeColor, false); picker.appendChild(color); } }
Color picker is created dynamically. If you like to add more colors to color picker just add more colors to colors array. If element of color picker will be clicked - color of this element will be selected as brush color. Here is a click handler:
function onStrokeColor(event) { var colorParts = this.style.backgroundColor.toString().match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/); if(colorParts != null && colorParts.length == 4) { strokeColor = "rgba(" + colorParts[1] + "," + colorParts[2] + "," + colorParts[3] + ",0.1)"; } }
First selected color is parsed and next choosen color is saved in global variable strokeColor for future use.
Let see on mouse handling functions:
function onCanvasTouchStart(event) { if(event.touches.length == 1) { event.preventDefault(); brush.beginStroke(strokeColor, event.touches[0].pageX, event.touches[0].pageY); window.addEventListener('touchmove', onCanvasTouchMove, false); window.addEventListener('touchend', onCanvasTouchEnd, false); } } function onCanvasMouseDown(event) { brush.beginStroke(strokeColor, event.clientX, event.clientY); window.addEventListener('mousemove', onCanvasMouseMove, false); window.addEventListener('mouseup', onCanvasMouseUp, false); } function onCanvasMouseMove(event) { brush.doStroke(event.clientX, event.clientY); } function onCanvasMouseUp() { brush.endStroke(); window.removeEventListener('mousemove', onCanvasMouseMove, false); window.removeEventListener('mouseup', onCanvasMouseUp, false); }
As you can see on mouse down and touch event beginStroke is called and new listeners is created. We need a new listeners to get know - when to finish to paint using our brush.
Brush is a class what implements some painting function and brush functionality. Why Brush implemented as separated class? Answer is simple - if you going to add more brushes all you need is just to create more brush classes. Let see on Brush implementation:
function Brush(context) { this.init(context); } Brush.prototype = { mouseX: null, mouseY: null, context: null, strokeColor: null, init: function(context) { this.context = context; }, beginStroke: function(color, mouseX, mouseY) { this.mouseX = mouseX; this.mouseY = mouseY; this.strokeColor = color; }, doStroke: function(mouseX, mouseY) { this.context.lineWidth = 1; this.context.strokeStyle = this.strokeColor; this.context.beginPath(); this.context.moveTo(this.mouseX, this.mouseY); this.context.lineTo(mouseX, mouseY); this.context.stroke(); }, endStroke: function(mouseX, mouseY) { } }
Most interesting thing here is a doStroke function. This function paint lines on the canvas context each time user holds the mouse button and moves cursor around canvas.
lineWidth - width of line, you can play with this parameter to see how it affects the resulted line
strokeStyle - color of the line
beginPath - start paint the path
moveTo - move start point to the specified position
lineTo - paint the line from the start point (moveTo) to the specified point
stroke - paint final line on the context
That is all. As you can see painting on the web page is not complex. all is simple. Put canvas on your page, get canvas context and paint anything you need with script.
5
Average: 5 (1 vote)