You are currently viewing HTML Canvas

HTML Canvas

  • Post author:
  • Post category:Animation
  • Post comments:0 Comments
  • Post last modified:November 23, 2024
  • Reading time:11 mins read

The Canvas Element

<canvas id="cv1" width="300" height="150">
Fallback content here
</canvas>
widthThe width of the canvas element(default is 300)
heightThe height of the canvas element(default is 150)
toDataURL(type)Convert content into a data URL static image; the type parameter indicates image type, such as “image/png”
getContext(type)Retrieves the drawing context for the canvas

The Canvas Drawing Context

var ctx = theCanvas.getContext("2d");

Canvas Rectangles

// Rectangle Fill specifications:
ctx.fillStyle = "green";
ctx.fillRect(0, 0, 100, 150);

// Rectangle Stroke specifications:
ctx.strokeStyle = "blue";
ctx.strokeRect(0, 0, 100, 150);

Canvas Lines

moveTo(x,y)Moves the drawing pen to (x, y); does not perform any drawing
lineTo(x,y)Draws a line from the current pen position to (x, y)
lineWidthGets or sets the width of the pen
lineCapGets or sets the line end-cap type: butt, round, square
lineJoinGets or sets the method used to join lines (default: miter)
miterLimitGets or sets the limit at which line (default: 10)
beginPath()Begins a set of multiple drawing commands as a single path
stroke()Strokes the currently open path that was started by beginPath()
Only for lines

setLineDash()Specifies a custom set of spaces to create a dashed line
getLineDash()Retrieves the current line dash settings
lineDashOffsetSpecifies the initial offset to use when creating dashed lines
Rectangles and Lines

The Canvas Drawing State

save()Saves the current drawing context
restore()Restore the most recent saved drawing context and makes it current

The Canvas Curves

bezierCurveTo(cx1, cy1, cx2, cy2, end1, end2)Draw a Bezier curve starting at the current pen position using the control points cx1, cy1 and cx2, and cy2, and ending at end1, end2
quadraticCurveTo(cx, cy, x, y)Draw a quadratic curve starting at the current pen position using the control point cx, cy and ending at the x, y point

Drawing Text on Canvas

fillText(str, x, y, [maxW])Renders the text at x, y but no wider than [maxW]
strokeText(str, x, y, [maxW])Renders the text at x, y but no wider than [maxW]
measureText(str)Returns a TextMetrics object containing width of str
fontFont to use for drawing text; same as what you would use in a CSS style rule: family, size, weight, etc.
textAlignStart” (default), “end“, “left”, “right”, “center”
textBaseline“top”, “hanging”, “middle”, “alphabetic” (default), “ideographic”, “bottom”

Canvas Shadows

shadowColorColor to use when drawing a shadow; any CSS color will work
shadowOffsetXHorizontal offset of the shadow (defaults to 0)
shadowOffsetYVertical offset of the shadow (defaults to 0)
shadowBlurAmount to blur (default to 0); must be > 0 to have effect
Canvas shadow drawing properties

Canvas Patterns

createPattern(elem, repeat)Creates a pattern using the elem as the source and the specified repeat options
(no-repeat, repeat, repeat-x, or repeat-y)
// Create a pattern from an image
var patImg = new Image();
patImg.onload = function () {
	ctx.fillStyle = ctx.createPattern(patImg, "repeat");
	ctx.fillRect(0, 0, width, height);
};
patImg.src = "images/classic_car.jpg";
// Create a pattern from a video
setTimeout(function () {
	var vid = document.getElementById("vidEl");
	var theCanvas = document.getElementById("Canvas1");
	var ctx = theCanvas.getContext("2d");
	var vidPat = ctx.createPattern(vid, "repeat");
	ctx.fillStyle = vidPat;
	ctx.fillRect(0, 0, width, height);
}, 5000);
// Create a pattern from another canvas
var patCanvas = document.getElementById("patCan");
var patCtx = patCanvas.getContext("2d");
// draw a line in the canvas
patCtx.strokeStyle = "red";
patCtx.lineWidth = 1;
patCtx.beginPath();
patCtx.moveTo(0, 0);
patCtx.lineTo(25, 25);
patCtx.stroke();

// now use that canvas as a pattern
var strokePat = ctx.createPattern(patCanvas, "repeat");
ctx.lineWidth = 25;
ctx.strokeStyle = strokePat;
ctx.strokeRect(25, 25, 100, 100);

Canvas Gradients

createLinearGradient(x0, y0, x1, y1)Creates a linear gradient using the two points to indicate the direction of the gradient
createRadialGradient(x0, y0, r0, x1, y1, r1)Creates a radial gradient using the given points to specify two circles where the gradient starts and ends
addColorStop(position, color)Adds a color stop to the gradient; The position argument should be between 0.0 and 1.0 to indicate where the stop should be added along the pat; The color argument is a CSS-style color specification

Canvas Draw Image

drawImage(src, x, y)Draws the given source image at the x, y point on the canvas
drawImage(src, x, y, w, h)Draws the given source image at the x, y point on the canvas and scales it to fit the given width and height
drawImage(src, sx, sy, sw, sh, dx, dy, dw, dh)Draws the given source image on the canvas; Gets source image data from the sx, sy point and within the width and height given by sw, sh, and draws the image on the destination canvas at dx, dy and scales it to fit the given dw, dh width and height

Canvas Clipping Paths

clip()Creates a new clipping path by calculating the intersection of the current clipping region and the current path; The new clip region replaces the current clip region.

Canvas Transformations

Canvas Translate

translate(x, y)Moves the origin of the canvs by the amounts specified by x, y

Canvas Scale

scale(x, y)Scales the canvs by the amounts specified by x, y

Canvas Rotate

rotate(angle)Rotates subsequent drawing operations by given angle amount

Custom Transform

<script type="text/javascript">
	window.onload = function () {
	var theCanvas = document.getElementById("Canvas1");
	if (theCanvas && theCanvas.getContext) {
		var ctx = theCanvas.getContext("2d");
		if (ctx) {
🔵		ctx.fillStyle = "blue";
		ctx.fillRect(0, 0, 100, 50);
		
		// Now translate the origin to the middle of the canvas
		// using a custom translation matrix
		// (a translate operation is defined as:)
		//  1  0  tx
		//  0  1  ty
		//  0  0  1
		var tx = ctx.canvas.width / 2;
		var ty = ctx.canvas.height / 2;
🔴		ctx.fillStyle = "red";
		ctx.save()
		ctx.transform(1, 0, 0, 1, tx, ty)
		ctx.fillRect(0, 0, 100, 50);
		ctx.restore()
		
		// Now let's set the current transform to a skewing one
		// (a skew transform is defined as:)
		//  1  sx 0
		//  sy 1  0
		//  0  0  1
		
		// Y skew
		var sx = 0;
		var sy = 0.3;
🟢		ctx.fillStyle = "green";
		ctx.save()
		ctx.setTransform(1, sy, sx, 1, 0, 0);
		ctx.fillRect(200, 20, 100, 50);
		ctx.restore()
		
		// X skew
		var sx = 0.3;
		var sy = 0;
🟣		ctx.fillStyle = "purple";
		ctx.save()
		ctx.setTransform(1, sy, sx, 1, 0, 0);
		ctx.fillRect(200, 20, 100, 50);
		ctx.restore()
		}
	}
	};
</script>

Compositing and globalAlpha

globalCompositeOperation:
              "source-over",
              "source-in",
              "source-out",
              "source-atop",
              "lighter",
              "xor",
              "destination-over",
              "destination-in",
              "destination-out",
              "destination-atop",
              "darker",
              "copy",

globalAlpha:
              between 0.0 and 1.0

Canvas Accessing Raw Pixel Data

Leave a Reply