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

HTML5 Canvas

<canvas> is a HTML element which can be used to draw graphics using scripting (usually JavaScript). This can, for instance, be used to draw graphs, make photo composition or simple (and not so simple) animations. 

<canvas> was first introduced by Apple for the Mac OS X Dashboard and later implemented in Safari and Google Chrome. Gecko 1.8-based browsers, such as Firefox 1.5, also support this element. This tutorial describes how to use the <canvas> element to draw 2D graphics, starting with the basics. Using the <canvas> element isn’t very difficult but you do need a basic understanding of HTML and JavaScriptThe default size of the canvas is 300px * 150px (width * height). But custom sizes can be defined using CSS height and width property. 

The basics of using canvas

Creating a canvas context on your page is as simple as adding the <canvas> element to your HTML document like so:

<canvas id="myCanvas" width="300" height="150">
Fallback content, in case the browser does not support Canvas.
</canvas>

You need to define an element ID so you can find the element later in your JavaScript code, and you also need to define the width and height of the canvas.

That’s your drawing pad created, so now let’s put pen to paper. To draw inside your canvas you need to use JavaScript. First you find your canvas element using getElementById, then you initialize the context you want.

 In this tutorials we’ll focus on the fundamental drawing capabilities of the HTML5 Canvas, including line and curve drawing, path drawing, shape drawing, gradients, patterns, images, and text.

HTML5 Canvas Basic Tutorials Prerequisites

All you need to get started with Basic Tutorials is a modern browser such as Google Chrome, Firefox, Safari, Opera, or IE9, a good working knowledge of JavaScript, and a simple text editor like notepad.

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).

Each canvas element can only have one context.  If we use the getContext() method multiple times, it will return a reference to the same context object.

What’s so Great About HTML5 Canvas?

Here are some reasons you might want to consider learning to use HTML5’s canvas feature:

  • Interactivity. Canvas is fully interactive. It can respond to a user’s actions by listening for keyboard, mouse, or touch events. So a developer is not restricted to only static graphics and images.
  • Animation. Every object drawn on the canvas can be animated. This allows for all levels of animations to be created, from simple bouncing balls to complex forward and inverse kinematics.
  • Flexibility. Developers can create just about anything using canvas. It can display lines, shapes, text, images, etc. — with or without animation. Plus, adding video and/or audio to a canvas application is also possible.
  • Browser/Platform Support. HTML5 Canvas is supported by all major browsers and can be accessed on a wide range of devices including desktops, tablets, and smart phones.
  • Popularity. Canvas popularity is rapidly and steadily growing so there is no shortage of resources available.
  • It’s a web standard. Unlike Flash and Silverlight, Canvas is open technology that’s part of HTML5. And although not all of its features are implemented in all browsers, developers can be certain canvas will be around indefinitely.
  • Develop once, run everywhere. HTML5 Canvas offers great portability. Once created, Unlike Flash and Silverlight, a canvas application can run almost anywhere — from the largest computers to the smallest mobile devices.
  • Free and accessible development tools. The basic tools for creating HTML5 canvas applications are just a browser and a good code editor. Plus, there are many great and free libraries and tools to help developers with advanced canvas development.

What Applications Can You Create with HTML5 Canvas?

OK, canvas is great. But what exactly can use it for? Let’s see.

  • Gaming. The HTML5 Canvas’ feature set is an ideal candidate for producing all sorts of 2D and 3D games.
  • Advertising. HTML5 Canvas is a great replacement for Flash-based banners and ads. It has all the needed features for attracting buyers’ attention.
  • Data Representation. HTML5 can collect data from global data sources and use it to generate visually appealing and interactive graphs and charts with the canvas element.
  • Education and Training. HTML5 canvas can be used to produce effective and attractive learning experiences, combining text, images, videos, and audio.
  • Art and Decoration. With a little bit of imagination and canvas’s wide variety of colors, gradients, patterns, transparency, shadows, and clipping features, all kinds of artistic and decorative graphics can be drawn.

Now that we know why we should learn canvas, let’s look at the basics of HTML5 Canvas and how to start using it.

Canvas Rendering Contexts

Every HTML5 canvas element must have a context. The context defines what HTML5 Canvas API you’ll be using. The 2d context is used for drawing 2D graphics and manipulating bitmap images. The 3d context is used for 3D graphics creation and manipulation. The latter is actually called WebGL and it’s based on OpenGL ES.

HTML5 Canvas Template

<body>
  <canvas id="myCanvas" width="578" height="200"></canvas>
  <script>
    var canvas = document.getElementById('myCanvas');
    var context = canvas.getContext('2d');
     // do stuff here
  </script>
</body>

HTML5 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.

For Complete HTML Canvas Tutorial : Clickhere