HTML5 Canvas Basics Part 2

This is the continuation post of canvas basics

Canvas Custom Shape Tutorial

To create a custom shape with HTML5 Canvas, we can create a path and then close it using the closePath() method.  We can use the lineTo(),arcTo(), quadraticCurveTo(), or bezierCurveTo() methods to construct each subpath which makes up our shape.

<body>
<canvas id=”myCanvas” width=”578″ height=”200″></canvas>
<script>
var canvas = document.getElementById(‘myCanvas’);
var context = canvas.getContext(‘2d’);

// begin custom shape
context.beginPath();
context.moveTo(170, 80);
context.bezierCurveTo(130, 100, 130, 150, 230, 150);
context.bezierCurveTo(250, 180, 320, 180, 340, 150);
context.bezierCurveTo(420, 150, 420, 120, 390, 100);
context.bezierCurveTo(430, 40, 370, 30, 340, 50);
context.bezierCurveTo(320, 5, 250, 20, 250, 50);
context.bezierCurveTo(200, 5, 150, 20, 170, 80);

// complete custom shape
context.closePath();
context.lineWidth = 5;
context.strokeStyle = ‘blue’;
context.stroke();
</script>
</body>

Above code creates a visual like

23-06-2014 14-44-13

Canvas Rectangle Tutorial

To create a rectangle using HTML5 Canvas, we can use the rect() method rather than constructing the shape with 4 connecting lines.  An HTML5 Canvas rectangle is positioned with x and y parameters, and is sized with width and height parameters.  The rectangle is positioned about its top left corner.
context.beginPath();
context.rect(88, 100, 400, 200); // x,y,width,height
context.fillStyle = ‘yellow’;
context.fill();
context.lineWidth = 7;
context.strokeStyle = ‘black’;
context.stroke();

Canvas Circle Tutorial

To draw a circle with HTML5 Canvas, we can create a full arc using the arc() method by defining the starting angle as 0 and the ending angle as 2 * PI.

The arc() method creates an arc/curve (used to create circles, or parts of circles).

Tip: To create a circle with arc(): Set start angle to 0 and end angle to 2*Math.PI.

Tip: Use the stroke() or the fill() method to actually draw the arc on the canvas.

img_arc

23-06-2014 14-52-10

Syntax: context.arc(x,y,r,sAngle,eAngle,counterclockwise);

x The x-coordinate of the center of the circle
y The y-coordinate of the center of the circle
r The radius of the circle
sAngle The starting angle, in radians (0 is at the 3 o’clock position of the arc’s circle)
eAngle The ending angle, in radians
counterclockwise Optional. Specifies whether the drawing should be counterclockwise or clockwise. False is default, and indicates clockwise, while true indicates counter-clockwise.

Eg: context.beginPath();
context.arc(300, 100, 70, 0, 2 * Math.PI, false);
context.fillStyle = ‘green’;
context.fill();
context.lineWidth = 5;
context.strokeStyle = ‘#003300’;
context.stroke();

ColorFill:

To fill an HTML5 Canvas shape with a solid color, we can set the fillStyle property to a color string such as blue, a hex value such as #0000FF, or an RGB value such as rgb(0,0,255), and then we can use the fill() method to fill the shape.  Unless otherwise specified, the default fill style for an HTML5 Canvas shape is black.

Note: When setting both the fill and stroke for a shape, make sure that you use fill() before stroke(). Otherwise, the fill will overlap half of the stroke.

context.fillStyle = ‘#8ED6FF’;
context.fill();
context.strokeStyle = ‘blue’;
context.stroke();

Linear Gradient:

To create a linear gradient with HTML5 Canvas, we can use the createLinearGradient() method. Linear gradients are defined by an imaginary line which defines the direction of the gradient. Once we’ve created our gradient, we can insert colors using the addColorStop property.

The direction of the linear gradient moves from the starting point to the ending point of the imaginary line defined with createLinearGradient().  In this tutorial, we’ve used two color stops, a light blue that originates at the starting point of the gradient, and a dark blue that ends with the ending point. Color stops are placed along the imaginary line somewhere between 0 and 1, where 0 is at the starting point, and 1 is at the ending point.

<canvas id=”myCanvas” width=”578″ height=”200″></canvas>
<script>
var canvas = document.getElementById(‘myCanvas’);
var context = canvas.getContext(‘2d’);
context.rect(0, 0, canvas.width, canvas.height);

// add linear gradient
var grd = context.createLinearGradient(0, 0, canvas.width, canvas.height);
// light blue
grd.addColorStop(0, ‘#8ED6FF’);
// dark blue
grd.addColorStop(1, ‘#004CB3’);
context.fillStyle = grd;
context.fill();
</script>

23-06-2014 15-17-49

Radial Gradient:

To create a radial gradient with HTML5 Canvas, we can use the createRadialGradient() method. Radial gradients are defined with two imaginary circles – a starting circle and an ending circle, in which the gradient starts with the start circle and moves towards the end circle.

context.rect(0, 0, canvas.width, canvas.height);

// create radial gradient
var grd = context.createRadialGradient(238, 50, 10, 238, 50, 300);
// light blue
grd.addColorStop(0, ‘#8ED6FF’);
// dark blue
grd.addColorStop(1, ‘#004CB3’);

context.fillStyle = grd;
context.fill();

23-06-2014 15-20-18

Pattern:

To create a pattern with the HTML5 Canvas, we can use the createPattern() method of the canvas context which returns a pattern object, set thefillStyle property to the pattern object, and then fill the shape using fill().  The createPattern() method requires an image object and a repeat option, which can be repeat, repeat-x, repeat-y, or no-repeat.  Unless otherwise specified, the repeat option is defaulted to repeat.

<canvas id=”myCanvas” width=”578″ height=”200″></canvas>
<script>
var canvas = document.getElementById(‘myCanvas’);
var context = canvas.getContext(‘2d’);

var imageObj = new Image();
imageObj.onload = function() {
var pattern = context.createPattern(imageObj, ‘repeat’);

context.rect(0, 0, canvas.width, canvas.height);
context.fillStyle = pattern;
context.fill();
};
imageObj.src = ‘http://www.html5canvastutorials.com/demos/assets/wood-pattern.png&#8217;;
</script>

23-06-2014 15-23-09

Canvas Image:

To draw an image using HTML5 Canvas, we can use the drawImage() method which requires an image object and a destination point. The destination point defines the top left corner of the image relative to the top left corner of the canvas.

The drawImage() method draws an image, canvas, or video onto the canvas.

The drawImage() method can also draw parts of an image, and/or increase/reduce the image size.

JavaScript Syntax

Position the image on the canvas:

JavaScript syntax: context.drawImage(img,x,y);

Position the image on the canvas, and specify width and height of the image:

JavaScript syntax: context.drawImage(img,x,y,width,height);

Clip the image and position the clipped part on the canvas:

JavaScript syntax: context.drawImage(img,sx,sy,swidth,sheight,x,y,width,height);

 

img Specifies the image, canvas, or video element to use
sx Optional. The x coordinate where to start clipping
sy Optional. The y coordinate where to start clipping
swidth Optional. The width of the clipped image
sheight Optional. The height of the clipped image
x The x coordinate where to place the image on the canvas
y The y coordinate where to place the image on the canvas
width Optional. The width of the image to use (stretch or reduce the image)
height Optional. The height of the image to use (stretch or reduce the image)

Eg:

<canvas id=”myCanvas” width=”578″ height=”400″></canvas>
<script>
var canvas = document.getElementById(‘myCanvas’);
var context = canvas.getContext(‘2d’);
var imageObj = new Image();

imageObj.onload = function() {
context.drawImage(imageObj, 32, 50,440,600);
};
imageObj.src = ‘http://www.html5canvastutorials.com/demos/assets/darth-vader.jpg&#8217;;
</script>

image size:

To set the size of an image using HTML5 Canvas, we can add two additional arguments to the drawImage() method, width and height.

<canvas id=”myCanvas” width=”578″ height=”200″></canvas>
<script>
var canvas = document.getElementById(‘myCanvas’);
var context = canvas.getContext(‘2d’);
var x = 188;
var y = 30;
var width = 200;
var height = 137;
var imageObj = new Image();

imageObj.onload = function() {
context.drawImage(imageObj, x, y, width, height);
};
imageObj.src = ‘http://www.html5canvastutorials.com/demos/assets/darth-vader.jpg&#8217;;
</script>

Image crop:

To crop an image using HTML5 Canvas, we can add six additional arguments to the drawImage() method, sourceX, sourceY, sourceWidth,sourceHeight, destWidth and destHeight.  These arguments define the location and size of a rectangle that we want to cut out of an image.

html5-canvas-image-crop-diagram

<body>
<canvas id=”myCanvas” width=”578″ height=”200″></canvas>
<script>
var canvas = document.getElementById(‘myCanvas’);
var context = canvas.getContext(‘2d’);
var imageObj = new Image();

imageObj.onload = function() {
// draw cropped image
var sourceX = 150;
var sourceY = 0;
var sourceWidth = 150;
var sourceHeight = 150;
var destWidth = sourceWidth;
var destHeight = sourceHeight;
var destX = canvas.width / 2 – destWidth / 2;
var destY = canvas.height / 2 – destHeight / 2;

context.drawImage(imageObj, sourceX, sourceY, sourceWidth, sourceHeight, destX, destY, destWidth, destHeight);
};
imageObj.src = ‘http://www.html5canvastutorials.com/demos/assets/darth-vader.jpg&#8217;;
</script>
</body>

Advertisements
Categories PHP

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s