HTML5 Canvas Basics

The HTML5 Canvas element is an HTML tag similar to the <div>, <a>, or <table> tag, with the exception that its contents are rendered with JavaScript.  In order to leverage the HTML5 Canvas, we’ll need to place the canvas tag somewhere inside the HTML document, access the canvas tag with JavaScript, create a context, and then utilize the HTML5 Canvas API to draw visualizations.

When using canvas, it’s important to understand the difference between the canvas element and the canvas context, as often times people get these confused.  The canvas element is the actual DOM node that’s embedded in the HTML page.  The canvas context is an object with properties and methods that you can use to render graphics inside the canvas element.  The context can be 2d or webgl (3d).

Before we start up with canvas drawing..better understand the Canvas Coordinate System

To know what’s so great about this canvas and what applications we can create with?? clickhere

What is Canvas Element:

We will include <canvas> tag in html body as DOM and call its attributes through javascript with API to draw visualizations..

<body>
<canvas id=”myCanvas” width=”578″ height=”200″></canvas>

</body>

<script>
var canvas = document.getElementById(‘myCanvas’); //declare canvas in js by id
var context = canvas.getContext(‘2d’); // defining context type 2d or webgl(3d)

// do cool things with the context
context.font = ’40pt Calibri’; // applying font attribute to context
context.fillStyle = ‘blue’; // applying color to text
context.fillText(‘Hello World!’, 150, 100); // write text with x & y coordinates..here text starts at x-axis=150 position and y axis = 100.
</script>

Canvas Line Tutorial

To draw a line using HTML5 Canvas, we can use the beginPath(), moveTo(), lineTo(), and stroke() methods.

First, we can use the beginPath() method to declare that we are about to draw a new path.  Next, we can use the moveTo() method to position the context point (i.e. drawing cursor), and then use the lineTo() method to draw a straight line from the starting position to a new position.  Finally, to make the line visible, we can apply a stroke to the line using stroke().  Unless otherwise specified, the stroke color is defaulted to black.

context.beginPath(); //declaring canvas
context.moveTo(100, 150); // position of point
context.lineTo(450, 50); // line starting position to end
context.stroke(); // stroke will only allow you to visible your drawing

I knew, you to got same sort of doubt like me right? what is the difference between moveTo and lineTo??

-The coordinate you pass moveTo is the starting point of a new line (or shape); As if picking up your pen off the paper and setting it in a new location (the new coordinates).

-The function of lineTo is what “move(s) the pen across the paper to draw a line” (to a new coordinate you’ve given it, since you need two points to draw a line, obviously)

-You can place multiple lineTo calls one after another and it will use the last point you ended on, to continue the line, like so:

ctx.moveTo(100,50);
ctx.lineTo(25,175);
ctx.lineTo(175,175);
ctx.lineTo(100,50);
ctx.stroke();

here’s a simple fiddle showing the outcome: http://jsfiddle.net/fbZKu/

Brief explaination: Say we are drawing a graph on graph sheet, i took my pencil and initially point to a position of x-axis=100 and y-axis=50. Here i just draw a point, means placed a dot on paper,thats it. Now i took a position of x-axis=25 and y-axis=175 where connects to my initial dot. similarly next two lines too..now we had a triangle out points on graph where we can draw line and connect all points. Thats what explained in jsfiddle program. In order to understand moveTo, better keep it as (0,0) then you can easily figure it out 😀

23-06-2014 11-47-15

I hope its clear now

Canvas Line Width Tutorial

To define the width of an HTML5 Canvas line, we can use the lineWidth property of the canvas context.  The lineWidth property must be set before calling stroke().

context.beginPath();
context.moveTo(100, 150);
context.lineTo(450, 50);
context.lineWidth = 15;
context.stroke();

23-06-2014 11-54-40

Canvas Line Color Tutorial

To set the color of an HTML5 Canvas line, we can use the strokeStyle property of the canvas context, which can be set to a color string such asredgreen, or blue, a hex value such as #FF0000 or #555, or an RGB value such as rgb(255, 0, 0).

context.beginPath();
context.moveTo(100, 150);
context.lineTo(450, 50);
context.lineWidth = 10;

// set line color
context.strokeStyle = ‘#ff0000’;
context.stroke();

23-06-2014 11-54-49

Canvas Line Cap Tutorial

To add a cap to an HTML5 Canvas line, we can use the lineCap property. Lines can have one of three cap styles: butt, round, or square. Unless otherwise specified, HTML5 Canvas lines are defaulted with the butt cap style.  The lineCap property must be set before calling stroke().

context.beginPath();
context.moveTo(200, canvas.height / 2 – 50);
context.lineTo(canvas.width – 200, canvas.height / 2 – 50);
context.lineWidth = 20;
context.strokeStyle = ‘#0000ff’;
context.lineCap = ‘butt’; (or) context.lineCap = ’round’; (or) context.lineCap = ‘square’;
context.stroke();

23-06-2014 11-54-58

Canvas Arc Tutorial

To create an arc with HTML5 Canvas, we can use the arc() method. Arcs are defined by a center point, a radius, a starting angle, an ending angle, and the drawing direction (either clockwise or anticlockwise).  Arcs can be styled with the lineWidth, strokeStyle, and lineCap properties.

html5-canvas-arcs-diagram

An arc is nothing more than a section of the circumference of an imaginary circle. This imaginary circle can be defined by x, y, and radius.

Next, we can define the arc itself with two points along the imaginary circle’s circumference defined by startAngle and endAngle. These two angles are defined in radians and form imaginary lines that originate from the center of the circle and intersect the ends of the arc that we wish to create.

The final argument of the arc method is antiClockwise which defines the direction of the arc path between its two ending points. Unless otherwise specified, this argument is defaulted to false, which causes the arc to be drawn clockwise.

<body>
<canvas id=”myCanvas” width=”578″ height=”250″></canvas>
<script>
var canvas = document.getElementById(‘myCanvas’);
var context = canvas.getContext(‘2d’);
var x = canvas.width / 2; // defining x position
var y = canvas.height / 2; // defining y position
var radius = 75; // arc radius
var startAngle = 1.1 * Math.PI; // startangle point
var endAngle = 1.9 * Math.PI; // end angle
var counterClockwise = false; // set true or false to direction

context.beginPath();
context.arc(x, y, radius, startAngle, endAngle, counterClockwise);
context.lineWidth = 15;

// line color
context.strokeStyle = ‘black’;
context.stroke();
</script>
</body>

Note: Just keep changing start angle and end angle like 1,0.5 etc etc as explained in above figure for better understanding. x & y also can be modified to understand the position where we are going to draw an arc

Canvas Quadratic Curve Tutorial

To create a quadratic curve with HTML5 Canvas, we can use the quadraticCurveTo() method. Quadratic curves are defined by the context point, a control point, and an ending point.  Quadratic curves can be styled with the lineWidth, strokeStyle, and lineCap properties.

html5-canvas-quadratic-curves-diagram

A control point defines the curvature of your quadratic curve by creating two imaginary tangential lines which are connected to the context point and the ending point. The context point is defined by the moveTo() method. Moving the control point farther away from the context point and the ending point will create sharper curves, and moving the control point closer to the context point and the ending point will create broader curves.

context.beginPath();
context.moveTo(20,20);
context.quadraticCurveTo(20,100,200,20);
context.lineWidth = 10;

context.strokeStyle = ‘black’;
context.stroke();

Explanation:

A quadratic Bézier curve requires two points. The first point is a control point that is used in the quadratic Bézier calculation and the second point is the ending point for the curve. The starting point for the curve is the last point in the current path. If a path does not exist, use the beginPath() and moveTo() methods to define a starting point.

img_quadraticcurve

23-06-2014 12-53-50
Parameter Description
cpx The x-coordinate of the Bézier control point
cpy The y-coordinate of the Bézier control point
x The x-coordinate of the ending point
y The y-coordinate of the ending point

Note :You can generate quadratic curve by interface dynamically using this

Canvas Bezier Curve Tutorial

o create a Bezier curve with HTML5 Canvas, we can use the bezierCurveTo() method. Bezier curves are defined with the context point, two control points, and an ending point. Unlike quadratic curves, Bezier curves are defined with two control points instead of one, allowing us to create more complex curvatures.  Bezier curves can be styled with the lineWidth, strokeStyle, and lineCap properties.

html5-canvas-bezier-curves-diagram

A bezier curve is defined by the current context point, two control points, and an ending point. The first part of the curve is tangential to the imaginary line that is defined by the context point and the first control point. The second part of the curve is tangential to the imaginary line that is defined by the second control point and the ending point.

context.beginPath();
context.moveTo(20,20);
context.bezierCurveTo(20,100,200,100,200,20);
context.stroke();

A cubic bezier curve requires three points. The first two points are control points that are used in the cubic Bézier calculation and the last point is the ending point for the curve.  The starting point for the curve is the last point in the current path. If a path does not exist, use the beginPath() and moveTo() methods to define a starting point.

img_beziercurve

23-06-2014 12-49-46
context.bezierCurveTo(cp1x,cp1y,cp2x,cp2y,x,y);
Parameter Description
cp1x The x-coordinate of the first Bézier control point
cp1y The y-coordinate of the first Bézier control point
cp2x The x-coordinate of the second Bézier control point
cp2y The y-coordinate of the second Bézier control point
x The x-coordinate of the ending point
y The y-coordinate of the ending point

Note :You can generate Bezier curve by interface dynamically using this

Canvas Path Tutorial

To create a path with HTML5 Canvas, we can connect multiple subpaths.  The ending point of each new subpath becomes the new context point.  We can use the lineTo(), arcTo(), quadraticCurveTo(), and bezierCurveTo() methods to construct each subpath which makes up our path.  We can also use the beginPath() method each time we want to start drawing a new path.

html5-canvas-paths-diagram

context.beginPath();
context.moveTo(100, 20);

// line 1
context.lineTo(200, 160);

// quadratic curve
context.quadraticCurveTo(230, 200, 250, 120);

// bezier curve
context.bezierCurveTo(290, -40, 300, 200, 400, 150);

// line 2
context.lineTo(500, 90);

context.lineWidth = 5;
context.strokeStyle = ‘blue’;
context.stroke();

Canvas Line Join Tutorial

To set the line join style of an HTML5 Canvas path, we can set the lineJoin context property.  Paths can have one of three line joins: miter,round, or bevel.  Unless otherwise specified, the HTML5 Canvas line join property is defaulted with the miter style.

context.beginPath();
context.moveTo(99, 150);
context.lineTo(149, 50);
context.lineTo(199, 150);
context.lineJoin = ‘miter’; (or) context.lineJoin = ’round’; (or) context.lineJoin = ‘bevel’;
context.stroke();

23-06-2014 13-14-00

Canvas Rounded Corners Tutorial

To created rounded corners using HTML5 Canvas, we can use the arcTo() method which is defined by a control point, an ending point, and a radius.

<body>
<canvas id=”myCanvas” width=”578″ height=”200″></canvas>
<script>
var canvas = document.getElementById(‘myCanvas’);
var context = canvas.getContext(‘2d’);
var rectWidth = 200;
var rectHeight = 100;
var rectX = 189;
var rectY = 50;
var cornerRadius = 50;

context.beginPath();
context.moveTo(rectX, rectY);
context.lineTo(rectX + rectWidth – cornerRadius, rectY);
context.arcTo(rectX + rectWidth, rectY, rectX + rectWidth, rectY + cornerRadius, cornerRadius);
context.lineTo(rectX + rectWidth, rectY + rectHeight);
context.lineWidth = 5;
context.stroke();
</script>
</body>

Tip: In the above example replace arcTo with context.arcTo(389, 50, 389, 100, 50); and change the radius last value to ‘0’.

23-06-2014 13-19-07

Syntax : context.arcTo(x1,y1,x2,y2,r);

x1 The x-coordinate of the beginning of the arc
y1 The y-coordinate of the beginning of the arc
x2 The x-coordinate of the end of the arc
y2 The y-coordinate of the end of the arc
r The radius of the arc

Reference: http://www.html5canvastutorials.com/

http://www.w3schools.com

Advertisements

One thought on “HTML5 Canvas Basics

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