HTML5 Canvas
Notes for Professionals
HTML5
Canvas
Notes for Professionals
100+ pages
of professional hints and tricks
GoalKicker.com
Free Programming Books
Disclaimer
This is an unocial free book created for educational purposes and is
not aliated with ocial HTML5 Canvas group(s) or company(s).
All trademarks and registered trademarks are
the property of their respective owners
Contents
About
...................................................................................................................................................................................
1
............................................................................................
................................................................................................
.......................................................................................................................
.........................................................................................................................................................
........................................................................................................................
Chapter 1: Getting started with HTML5 Canvas
Section 1.1: Detecting mouse position on the canvas
Section 1.2: Canvas size and resolution
Section 1.3: Rotate
Section 1.4: Save canvas to image file
Section 1.5: How to add the Html5 Canvas Element to a webpage
Section 1.6: An index to Html5 Canvas Capabilities & Uses
Section 1.7: O screen canvas
Section 1.8: Hello World
......................................................................................................................................
.................................................................................................................................................
.........................................................................
4
......................................................................................
Chapter 2: Text
...............................................................................................................................................................
8
...............................................................................................................................................
8
..............................................................................................................................
..................................................................................................................
.........................................................................................
...........................................................................................................................................
......................................................................................................................................
Section 2.1: Justified text
Section 2.2: Justified paragraphs
Section 2.3: Rendering text along an arc
Section 2.4: Text on curve, cubic and quadratic beziers
Section 2.5: Drawing Text
Section 2.6: Formatting Text
Section 2.7: Wrapping text into paragraphs
Section 2.8: Draw text paragraphs into irregular shapes
Section 2.9: Fill text with an image
............................................................................................................
.......................................................................................
28
............................................................................................................................
30
Chapter 3: Polygons
..................................................................................................................................................
31
Section 3.1: Render a rounded polygon
Section 3.2: Stars
Section 3.3: Regular Polygon
.........................................................................................................................................................
.....................................................................................................................................
....................................................................................................................
31
Chapter 4: Images
.....................................................................................................................................................
35
Section 4.1: Is "context.drawImage" not displaying the image on the Canvas?
Section 4.2: The Tained canvas
Section 4.3: Image cropping using canvas
Section 4.4: Scaling image to fit or fill
...............................................................................................................
.......................................................................................................................
.................................................................................................................................
...................................................
35
Chapter 5: Path (Syntax only)
..............................................................................................................................
39
......................................................................................
.....................................................................................................................
............................................................................................................................
..........................................................................................................................
..................................................
47
......................................................................................................................
...........................................................................................................................
.................................................................................................
.......................................................................................................
.....................................................................................................................
.........................................................................................................................
Section 5.1: createPattern (creates a path styling object)
Section 5.2: stroke (a path command)
Section 5.3: fill (a path command)
Section 5.4: clip (a path command)
Section 5.5: Overview of the basic path drawing commands: lines and curves
Section 5.6: lineTo (a path command)
Section 5.7: arc (a path command)
Section 5.8: quadraticCurveTo (a path command)
Section 5.9: bezierCurveTo (a path command)
Section 5.10: arcTo (a path command)
Section 5.11: rect (a path command)
Section 5.12: closePath (a path command)
Section 5.13: beginPath (a path command)
Section 5.14: lineCap (a path styling attribute)
Section 5.15: lineJoin (a path styling attribute)
Section 5.16: strokeStyle (a path styling attribute)
Section 5.17: fillStyle (a path styling attribute)
..............................................................................................................
.............................................................................................................
........................................................................................................
........................................................................................................
..................................................................................................
.........................................................................................................
2
2
2
3
3
5
6
6
13
17
22
25
26
27
32
33
35
36
36
39
41
Advertisement
45
45
49
50
52
53
54
55
57
58
61
62
63
65
Section 5.18: lineWidth (A path styling attribute)
Section 5.19: shadowColor, shadowBlur, shadowOsetX, shadowOsetY (path styling attributes)
Section 5.20: createLinearGradient (creates a path styling object)
Section 5.21: createRadialGradient (creates a path styling object)
.....................................................................................................
67
.......................................................................
......................................................................
..................
68
Chapter 6: Paths
Section 6.1: Ellipse
Section 6.2: Line without blurryness
Chapter 7: Navigating along a Path
..........................................................................................................................................................
........................................................................................................................................................
..........................................................................................................................
.................................................................................................................
80
..................................................................................................................................
.......................................................................................................
...........................................................................................
...............................................................................................
.....................................................................................................................
Section 7.1: Find point on curve
Section 7.2: Finding extent of Quadratic Curve
Section 7.3: Finding points along a cubic Bezier curve
Section 7.4: Finding points along a quadratic curve
Section 7.5: Finding points along a line
Section 7.6: Finding points along an entire Path containing curves and lines
Section 7.7: Split bezier curves at position
Section 7.8: Trim bezier curve
Section 7.9: Length of a Cubic Bezier Curve (a close approximation)
Section 7.10: Length of a Quadratic Curve
................................................................................................................
....................................................................................................................................
...............................................................................................................
..................................................................
......................................................
84
Chapter 8: Dragging Path Shapes & Images on Canvas
........................................................................
98
Section 8.1: How shapes & images REALLY(!) "move" on the Canvas
Section 8.2: Dragging circles & rectangles around the Canvas
Section 8.3: Dragging irregular shapes around the Canvas
Section 8.4: Dragging images around the Canvas
...................................................................
98
.............................................................................
99
................................................................................
................................................................................................
Chapter 9: Media types and the canvas
.......................................................................................................
109
Section 9.1: Basic loading and playing a video on the canvas
Section 9.2: Capture canvas and Save as webM video
Section 9.3: Drawing an svg image
Section 9.4: Loading and displaying an Image
.........................................................................................................................
......................................................................................................
.............................................................................
109
........................................................................................
Chapter 10: Animation
............................................................................................................................................
119
.........................................
..............................................................................................
................................................................................
...........................................................................................
Section 10.1: Use requestAnimationFrame() NOT setInterval() for animation loops
Section 10.2: Animate an image across the Canvas
Section 10.3: Set frame rate using requestAnimationFrame
Section 10.4: Easing using Robert Penners equations
Section 10.5: Animate at a specified interval (add a new rectangle every 1 second)
Section 10.6: Animate at a specified time (an animated clock)
Section 10.7: Don't draw animations in your event handlers (a simple sketch app)
Section 10.8: Simple animation with 2D context and requestAnimationFrame
Section 10.9: Animate from [x0,y0] to [x1,y1]
Chapter 11: Collisions and Intersections
..........................................................................................................
........................................................................................................
.........................................
..................................................
...........................................................................
........................................
125
..........................................................................................................................
..................................................................................................................
Section 11.1: Are 2 circles colliding?
Section 11.2: Are 2 rectangles colliding?
Section 11.3: Are a circle and rectangle colliding?
Section 11.4: Are 2 line segments intercepting?
Section 11.5: Are a line segment and circle colliding?
Section 11.6: Are line segment and rectangle colliding?
Section 11.7: Are 2 convex polygons colliding?
Section 11.8: Are 2 polygons colliding? (both concave and convex polys are allowed)
Section 11.9: Is an X,Y point inside an arc?
Section 11.10: Is an X,Y point inside a wedge?
Section 11.11: Is an X,Y point inside a circle?
..................................................................................................
......................................................................................................
............................................................................................
........................................................................................
..............................................................................................................
.........................................................................................................
.............................................................................................................
.......................................................................................................
....................................
135
70
73
77
77
78
80
81
82
83
84
91
94
96
97
103
106
Advertisement
111
116
117
119
120
121
121
126
127
129
129
131
131
131
131
131
133
133
134
136
137
138
Section 11.12: Is an X,Y point inside a rectangle?
....................................................................................................
138
Chapter 12: Clearing the screen
........................................................................................................................
139
............................................................................................................................................
Section 12.1: Rectangles
Section 12.2: Clear canvas with gradient
Section 12.3: Clear canvas using composite operation
Section 12.4: Raw image data
Section 12.5: Complex shapes
Chapter 13: Responsive Design
................................................................................................................
.........................................................................................
139
..................................................................................................................................
..................................................................................................................................
..........................................................................................................................
Section 13.1: Creating a responsive full page canvas
Section 13.2: Mouse coordinates after resizing (or scrolling)
Section 13.3: Responsive canvas animations without resize events
............................................................................................
...............................................................................
....................................................................
142
Chapter 14: Shadows
..............................................................................................................................................
144
Section 14.1: Sticker eect using shadows
Section 14.2: How to stop further shadowing
Section 14.3: Shadowing is computationally expensive -- Cache that shadow!
Section 14.4: Add visual depth with shadows
Section 14.5: Inner shadows
..............................................................................................................
.........................................................................................................
.....................................................................................................................................
.........................................................................................................
..................................................
145
Chapter 15: Charts & Diagrams
Section 15.1: Pie Chart with Demo
Section 15.2: Line with arrowheads
Section 15.3: Cubic & Quadratic Bezier curve with arrowheads
Section 15.4: Wedge
Section 15.5: Arc with both fill and stroke
.........................................................................................................................
............................................................................................................................
..........................................................................................................................
...........................................................................
153
..................................................................................................................................................
...............................................................................................................
Chapter 16: Transformations
..............................................................................................................................
157
Section 16.1: Rotate an Image or Path around it's centerpoint
Section 16.2: Drawing many translated, scaled, and rotated images quickly
Section 16.3: Introduction to Transformations
Section 16.4: A Transformation Matrix to track translated, rotated & scaled shape(s)
.............................................................................
....................................................
.......................................................................................................
.....................................
160
Chapter 17: Compositing
.......................................................................................................................................
167
......................................................................
...................................................................................
Section 17.1: Draw behind existing shapes with "destination-over"
Section 17.2: Erase existing shapes with "destination-out"
Section 17.3: Default compositing: New shapes are drawn over Existing shapes
Section 17.4: Clip images inside shapes with "destination-in"
Section 17.5: Clip images inside shapes with "source-in"
Section 17.6: Inner shadows with "source-atop"
Section 17.7: Change opacity with "globalAlpha"
Section 17.8: Invert or Negate image with "dierence"
Section 17.9: Black & White with "color"
Section 17.10: Increase the color contrast with "saturation"
Section 17.11: Sepia FX with "luminosity"
...............................................................................
......................................................................................
.....................................................................................................
...................................................................................................
.........................................................................................
..................................................................................................................
..................................................................................................................
.................................................................................
..............................................
168
139
139
140
140
141
141
141
144
145
146
146
151
151
152
154
155
157
158
159
167
167
168
168
169
169
170
170
171
171
Advertisement
Chapter 18: Pixel Manipulation with "getImageData" and "putImageData"
.............................
173
Section 18.1: Introduction to "context.getImageData"
...........................................................................................
173
Credits
............................................................................................................................................................................
175
You may also like
......................................................................................................................................................
176
About
Please feel free to share this PDF with anyone for free,
latest version of this book can be downloaded from:
https://goalkicker.com/HTML5CanvasBook
This HTML5 Canvas Notes for Professionals book is compiled from Stack Overflow
Documentation, the content is written by the beautiful people at Stack Overflow.
Text content is released under Creative Commons BY-SA, see credits at the end
of this book whom contributed to the various chapters. Images may be copyright
of their respective owners unless otherwise specified
This is an unofficial free book created for educational purposes and is not
affiliated with official HTML5 Canvas group(s) or company(s) nor Stack Overflow.
All trademarks and registered trademarks are the property of their respective
company owners
The information presented in this book is not guaranteed to be correct nor
accurate, use at your own risk
Please send feedback and corrections to [email protected]
GoalKicker.com – HTML5 Canvas Notes for Professionals
1
Chapter 1: Getting started with HTML5
Canvas
Section 1.1: Detecting mouse position on the canvas
This example will show how to get the mouse position relative to the canvas, such that (0,0) will be the top-left
hand corner of the HTML5 Canvas. The e.clientX and e.clientY will get the mouse positions relative to the top of
the document, to change this to be based on the top of the canvas we subtract the left and right positions of the
canvas from the client X and Y.
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
ctx.font = "16px Arial";
canvas.addEventListener("mousemove", function(e) {
var cRect = canvas.getBoundingClientRect(); // Gets CSS pos, and width/height
var canvasX = Math.round(e.clientX - cRect.left); // Subtract the 'left' of the canvas
var canvasY = Math.round(e.clientY - cRect.top); // from the X/Y positions to make
ctx.clearRect(0, 0, canvas.width, canvas.height); // (0,0) the top left of the canvas
ctx.fillText("X: "+canvasX+", Y: "+canvasY, 10, 20);
});
Runnable Example
The use of Math.round is due to ensure the x,y positions are integers, as the bounding rectangle of the canvas may
not have integer positions.
Section 1.2: Canvas size and resolution
The size of a canvas is the area it occupies on the page and is defined by the CSS width and height properties.
canvas {
width : 1000px;
height : 1000px;
}
The canvas resolution defines the number of pixels it contains. The resolution is set by setting the canvas element
width and height properties. If not specified the canvas defaults to 300 by 150 pixels.
The following canvas will use the above CSS size but as the width and height is not specified the resolution will be
300 by 150.
<canvas id="my-canvas"></canvas>
This will result in each pixel being stretched unevenly. The pixel aspect is 1:2. When the canvas is stretched the
browser will use bilinear filtering. This has an effect of blurring out pixels that are stretched.
For the best results when using the canvas ensure that the canvas resolution matches the display size.
Following on from the CSS style above to match the display size add the canvas with the width and height set to
the same pixel count as the style defines.
<canvas id = "my-canvas" width = "1000" height = "1000"></canvas>
GoalKicker.com – HTML5 Canvas Notes for Professionals
2
Section 1.3: Rotate
The rotate(r) method of the 2D context rotates the canvas by the specified amount r of radians around the origin.
HTML
<canvas id="canvas" width=240 height=240 style="background-color:#808080;">
</canvas>
<button type="button" onclick="rotate_ctx();">Rotate context</button>
JavaScript
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var ox = canvas.width / 2;
var oy = canvas.height / 2;
ctx.font = "42px serif";
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.fillStyle = "#FFF";
ctx.fillText("Hello World", ox, oy);
rotate_ctx = function() {
// translate so that the origin is now (ox, oy) the center of the canvas
ctx.translate(ox, oy);
// convert degrees to radians with radians = (Math.PI/180)*degrees.
ctx.rotate((Math.PI / 180) * 15);
ctx.fillText("Hello World", 0, 0);
// translate back
ctx.translate(-ox, -oy);
};
Live demo on JSfiddle
Section 1.4: Save canvas to image file
You can save a canvas to an image file by using the method canvas.toDataURL(), that returns the data URI for the
canvas' image data.
The method can take two optional parameters canvas.toDataURL(type, encoderOptions): type is the image
format (if omitted the default is image/png); encoderOptions is a number between 0 and 1 indicating image quality
(default is 0.92).
Here we draw a canvas and attach the canvas' data URI to the "Download to myImage.jpg" link.
HTML
<canvas id="canvas" width=240 height=240 style="background-color:#808080;">
</canvas>
<p></p>
<a id="download" download="myImage.jpg" href="" onclick="download_img(this);">Download to
myImage.jpg</a>
JavaScript
var canvas = document.getElementById("canvas");
GoalKicker.com – HTML5 Canvas Notes for Professionals
3
var ctx = canvas.getContext("2d");
var ox = canvas.width / 2;
var oy = canvas.height / 2;
ctx.font = "42px serif";
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.fillStyle = "#800";
ctx.fillRect(ox / 2, oy / 2, ox, oy);
download_img = function(el) {
// get image URI from canvas object
var imageURI = canvas.toDataURL("image/jpg");
el.href = imageURI;
};
Live demo on JSfiddle.
Section 1.5: How to add the Html5 Canvas Element to a
webpage
Html5-Canvas ...
Is an Html5 element.
Is supported in most modern browsers (Internet Explorer 9+).
Is a visible element that is transparent by default
Has a default width of 300px and a default height of 150px.
Requires JavaScript because all content must be programmatically added to the Canvas.
Example: Create an Html5-Canvas element using both Html5 markup and JavaScript:
<!doctype html>
<html>
<head>
<style>
body{ background-color:white; }
#canvasHtml5{border:1px solid red; }
#canvasJavascript{border:1px solid blue; }
Advertisement
</style>
<script>
window.onload=(function(){
// add a canvas element using javascript
var canvas=document.createElement('canvas');
canvas.id='canvasJavascript'
document.body.appendChild(canvas);
}); // end $(function(){});
</script>
</head>
<body>
<!-- add a canvas element using html -->
<canvas id='canvasHtml5'></canvas>
</body>
</html>
GoalKicker.com – HTML5 Canvas Notes for Professionals
4
Section 1.6: An index to Html5 Canvas Capabilities & Uses
Capabilities of the Canvas
Canvas lets you programmatically draw onto your webpage:
Images,
Texts,
Lines and Curves.
Canvas drawings can be extensively styled:
stroke width,
stroke color,
shape fill color,
opacity,
shadowing,
linear gradients and radial gradients,
font face,
font size,
text alignment,
text may be stroked, filled or both stroked & filled,
image resizing,
image cropping,
compositing
Uses of the Canvas
Drawings can be combined and positioned anywhere on the canvas so it can be used to create:
Paint / Sketch applications,
Fast paced interactive games,
Data analyses like charts, graphs,
Photoshop-like imaging,
Flash-like advertising and Flashy web content.
Canvas allows you to manipulate the Red, Green, Blue & Alpha component colors of images. This allows canvas to
manipulate images with results similar to Photoshop.
Recolor any part of an image at the pixel level (if you use HSL you can even recolor an image while retaining
the important Lighting & Saturation so the result doesn't look like someone slapped paint on the image),
"Knockout" the background around a person/item in an image,
Detect and Floodfill part of an image (eg, change the color of a user-clicked flower petal from green to yellow
-- just that clicked petal!),
Do Perspective warping (e.g. wrap an image around the curve of a cup),
Examine an image for content (eg. facial recognition),
Answer questions about an image: Is there a car parked in this image of my parking spot?,
Apply standard image filters (grayscale, sepia, etc)
Apply any exotic image filter you can dream up (Sobel Edge Detection),
Combine images. If dear Grandma Sue couldn't make it to the family reunion, just "photoshop" her into the
reunion image. Don't like Cousin Phil -- just "photoshop him out,
Play a video / Grab a frame from a video,
Export the canvas content as a .jpg | .png image (you can even optionally crop or annotate the image and
GoalKicker.com – HTML5 Canvas Notes for Professionals
5
export the result as a new image),
About moving and editing canvas drawings (for example to create an action game):
After something has been drawn on the canvas, that existing drawing cannot be moved or edited. This
common misconception that canvas drawings are movable is worth clarifying: Existing canvas drawings cannot
be edited or moved!
Canvas draws very, very quickly. Canvas can draw hundreds of images, texts, lines & curves in a fraction of a
second. It uses the GPU when available to speed up drawing.
Canvas creates the illusion of motion by quickly and repeatedly drawing something and then redrawing it in a
new position. Like television, this constant redrawing gives the eye the illusion of motion.
Section 1.7: O screen canvas
Many times when working with the canvas you will need to have a canvas to hold some intrum pixel data. It is easy
to create an offscreen canvas, obtain a 2D context. An offscreen canvas will also use the available graphics
hardware to render.
The following code simply creates a canvas and fills it with blue pixels.
function createCanvas(width, height){
var canvas = document.createElement("canvas"); // create a canvas element
canvas.width = width;
canvas.height = height;
return canvas;
}
var myCanvas = createCanvas(256,256); // create a small canvas 256 by 256 pixels
var ctx = myCanvas.getContext("2d");
ctx.fillStyle = "blue";
ctx.fillRect(0,0,256,256);
Many times the offscreen canvas will be used for many tasks, and you may have many canvases. To simplify the use
of the canvas you can attach the canvas context to the canvas.
function createCanvasCTX(width, height){
var canvas = document.createElement("canvas"); // create a canvas element
canvas.width = width;
canvas.height = height;
canvas.ctx = canvas.getContext("2d");
return canvas;
}
var myCanvas = createCanvasCTX(256,256); // create a small canvas 256 by 256 pixels
myCanvas.ctx.fillStyle = "blue";
myCanvas.ctx.fillRect(0,0,256,256);
Section 1.8: Hello World
HTML
<canvas id="canvas" width=300 height=100 style="background-color:#808080;">
</canvas>
JavaScript
var canvas = document.getElementById("canvas");
GoalKicker.com – HTML5 Canvas Notes for Professionals
6
var ctx = canvas.getContext("2d");
ctx.font = "34px serif";
ctx.textAlign = "center";
ctx.textBaseline="middle";
ctx.fillStyle = "#FFF";
ctx.fillText("Hello World",150,50);
Result
GoalKicker.com – HTML5 Canvas Notes for Professionals
7
Chapter 2: Text
Section 2.1: Justified text
This example renders justified text. It adds extra functionality to the CanvasRenderingContext2D by extending its
prototype or as a global object justifiedText (optional see Note A).
Example rendering.
Code to render this image is in the usage examples at the bottom.
The Example
The function as a anonymous immediately invoked function.
(function(){
const FILL = 0; // const to indicate filltext render
const STROKE = 1;
const MEASURE = 2;
var renderType = FILL; // used internal to set fill or stroke text
var maxSpaceSize = 3; // Multiplier for max space size. If greater then no justificatoin applied
var minSpaceSize = 0.5; // Multiplier for minimum space size
var renderTextJustified = function(ctx,text,x,y,width){
var words, wordsWidth, count, spaces, spaceWidth, adjSpace, renderer, i, textAlign,
useSize, totalWidth;
textAlign = ctx.textAlign; // get current align settings
ctx.textAlign = "left";
wordsWidth = 0;
words = text.split(" ").map(word => {
var w = ctx.measureText(word).width;
wordsWidth += w;
return {
width : w,
word : word,
Advertisement
GoalKicker.co...