Canvas Examples – Add Text | Add Image | Resize Image | Change Canvas Color

How to add text to Canvas?

For add text we can do that using fillText(‘text’, x, y) or strokeText(“text”, x, y) method. The text is rendered using the current stroke or fill style, which can be a color, gradient, or pattern. You can specify a number of text settings, such as the font family, size, and weight, and the text alignment and baseline.

 

The textBaseline attribute’s keywords which correspond to the alignment points in the font, where:

  • top corresponds to the top of the em square
  • hanging is the hanging baseline
  • middle is the middle of the em square
  • alphabetic is the alphabetic baseline
  • ideographic is the ideographic baseline
  • bottom corresponds to the bottom of the em square

 

Here is example for add text with gradient, font family, size, weight, shadow.

canvas = document.getElementById(‘myCanvas’);

context = canvas.getContext(‘2d’);

context.font=”italic 30px Georgia”;

context.strokeStyle = “rgba(237,229,0,1)”;

context.shadowOffsetX = 2;

context.shadowOffsetY = 2;

context.shadowBlur = 1;

context.shadowColor = “rgba(0,0,0,1)”;

var gradient = context.createLinearGradient(200,70,200,110);

gradient.addColorStop(0, “#f55b5b”);

gradient.addColorStop(1, “#3112a3”);

context.fillStyle = gradient;

context.fillText(“Hello World”, x, y);

 

How to add image to Canvas?

 

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 is relative to the top left corner of the image.

 

The drawImage function includes three parameters and is expressed in the form drawImage(object image, float x, float y). The image file formats supported within the canvas element and drawImage function are .jpg, .gif, and .png.

 

The drawImage() method requires an image object, we must first create an image and wait for it to load before instantiating drawImage(). We can do this by using the onload property of the image object.

 

Here is example for add image to Canvas.

canvas = document.getElementById(‘myCanvas’);

context = canvas.getContext(‘2d’);

var imgObj = new Image();

imgObj.onload = function() {

context.drawImage(imgObj, 10, 10);

}

imgObj.src = “image/nature.jpg”;

 

How to resize image?

Now we have drawImage() method for draw image on Canvas, for resize image we can use same method with optional height and width parameters and is expressed in the form drawImage(object image, float x, float y, [optional width], [optional height]).

 

Here is example for add and resize image to Canvas.

canvas = document.getElementById(‘myCanvas’);

context = canvas.getContext(‘2d’);

var imgObj = new Image();

imgObj.onload = function() {

context.drawImage(imgObj, 10, 10, 200, 100);

}

imgObj.src = “image/nature.jpg”;

 

 

Canvas Examples – Draw Line | Rectangle | Circle | Undo

Canvas Examples – Draw Line | Rectangle | Circle | Undo

What is Canvas?

Canvas is an HTML5 element which can be used to draw graphics using scripting (usually JavaScript).

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. Canvas has several methods for drawing paths, boxes, circles, characters, and adding images.

Internet Explorer 9, Firefox, Opera, Chrome, and Safari support the canvas element.

 

Add Canvas to HTML

A canvas is a rectangular area on an HTML page, and it is specified with the canvas element.

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

Note: Always specify an id attribute (to be referred to in a script), and a width and height attribute to define the size of the canvas

 

Draw Line to Canvas

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

 

Example for line draw

var canvas = document.getElementById(“myCanvas”);

var context=canvas.getContext(“2d”);

context.beginPath();

context.moveTo(x, y);

context.lineTo(x, y);

context.stroke();

Draw Rectangle On Canvas

To create a rectangle using HTML5 Canvas, we can use rect(x,y,w,h) method, and for rectangle visible use stroke() method.

The rect() method have four parameter ie “x, y, width, height”, x is the upper left x co-ordinate, y is the upper left y co-ordinate of rectangle, then width of rectangle and height of rectangle.

var canvas = document.getElementById(“myCanvas”);

var context=canvas.getContext(“2d”);

context.rect(x, y, w, h);

context.stroke();

 

strokeRect(x,y,w,h) and fillRect(x,y,w,h) also use for draw rectangle, strokeRect() method done same as rect() and stroke() method. And fillRect() method use to draw rectangle with fill color. If you are not use fillStyle property then fillRect method draw rectangle with default black color.

 

context.fillStyle= “#ff00ff”;

context.fillRect(x, y, w, h);

OR

context.fillStyle= “rgb(255, 0, 255)”;

context.fillRect(x, y, w, h);

Also we can clear the canvas with clearRect(x,y,w,h) method.

context.clearRect(0, 0, canvas.width, canvas.height);
Draw Circle On Canvas

To draw a circle with HTML5 Canvas, we can use arc() method. and for circle visible use stroke() method.

Arcs are defined by a center point ie (x,y), a radius, a starting angle, an ending angle, and the drawing direction (either clockwise or anticlockwise, true for clockwise and false for anticlockwise, default is true;).

 

For draw full arc we can use starting angle is 0 and ending angle is 2* PI.

var canvas = document.getElementById(“myCanvas”);

var context=canvas.getContext(“2d”);

context.beginPath();

context.arc(x, y, r, 0, 2*Math.PI);

context.stroke();

 

We can styled circle with fillStyle, strokeStyle and lineWidth properties.

var canvas = document.getElementById(“myCanvas”);

var context=canvas.getContext(“2d”);

context.beginPath();

context.arc(x, y, r, 0, 2*Math.PI);

context.fillStyle = ‘#DA2C35’;

context.fill();

context.lineWidth = 3;

context.strokeStyle = ‘#003300’;

context.stroke();

Undo

There is not much we have to do add undo functionality to a Canvas application. We can achieve that by saving the state after each event in an array. These are simple JavaScript arrays where we are storing the images using push() and pop() methods. The canvas image is retrieved using the context.toDataURL(“image/png”) method and when we undo. we take that image and paint it again on the canvas after clearing the current canvas.

 

Saving Canvas state.

var restorePoints = [];

var canvas = document.getElementById(“myCanvas”);

var context=canvas.getContext(“2d”);

var imgSrc = canvas.toDataURL(“image/png”);

restorePoints.push(imgSrc);

 

Repaint Canvas

var oImg = new Image();

oImg.onload = function() {

var canvas = document.getElementById(“myCanvas”);
var canvasContext = canvas.getContext(“2d”);
canvasContext.clearRect(0, 0, canvas.width, canvas.height);
canvasContext.drawImage(oImg, 0, 0);
}

oImg.src = restorePoints.pop();

HTML5 form with example

Once our site is set the main thing we require is user input, by saying user input the first thing that comes to our mind is FORM. HTML5 has several new input types for form. These new features allows us better input control and validation. Not all major browsers support all the new input types. However, we can still use them, If they are not supported, they will behave as regular text fields.

If you have missed out our previous post on HTML5 features and structure elements

Please have a look at the Form below, it explains some of the input types and attributes. Try submitting empty fields, to check how everything works.

 

Demonstrating attribute Autofocus and Required

The autofocus attribute is a boolean attribute. When present, it specifies that an <input> element should automatically get focus when the page loads.
The required attribute is a boolean attribute.When present, it specifies that an input field must be filled out before submitting the form. Works with the input types: text, search, url, tel, email, password, date pickers, number, checkbox, radio, and file.

It can be implemented as,
<input id=’name’ name=’name’ type=’text’ required autofocus />
Attribute autofocus works with only any one field for a form if applied to multiple, it will reflect on the first one only. Autofocus works in all browsers except IE, whereas required works with Firefox, Chrome and Opera

 

Demonstrating input type Email and attribute placeholder

The input type email can be used for input fields that should contain an e-mail address, it will only take a valid email address as input, if not provided it will generate error.
The placeholder attribute specifies a short hint that describes the expected value of an input field (e.g. a sample value or a short description of the expected format). It is displayed in the input field when it is empty, and disappears when the field gets focus.It works with input types text, search, url, tel, email, and password.

It can be implemented as,
<input id=’email’ name=’email’ type=’email’ placeholder=’example@domain.com’ required />
Type email works with Firefox, Chrome and Opera.

 

Demonstrating input type number and attributes min max

The number type can be used for input fields that should contain a numeric value, with its MIN and MAX attribute we can also set restrictions on what numbers are accepted.
The min and max attributes specify the minimum and maximum value for an <input> element.These attributes work with input types: number, range, date, datetime, datetime-local, month, time and week.

It can be implemented as
<input id=’siblings’ name=’siblings’ type=’number’ min=’1′ max=’5′ required />
It works best with Chrome.

 

Demonstrating input type date

The date type allows the user to select a date.

It can be implemented as
<input id=’Birthdate’ name=’Birthdate’ type=’date’ required />
It works best with Opera, which provides a calender to select date from.

 

Demonstrating input type url

The url type can be used for input fields that should contain a URL address.The value of the url field is automatically validated when the form is submitted.

It can be implemented as
<input id=’url’ name=’url’ type=’url’ required />
It works best with Chrome and Firefox.

 

Demonstrating element datalist and attribute list

The <datalist> element specifies a list of pre-defined options for an <input> element.
The <datalist> element can be used to provide an autocomplete feature on <input> elements. Users will see a drop-down list of pre-defined options as they input data. To accomplish this we need the <input> element’s list attribute and bind it together with the <datalist> element. The value of list attribute of input should be a valid id of datalist element.

So now both the users and the developers will not require to write more, i.e. users can easily select from the predefined set of input values and the developers will not need to write Great Logics to provide autocomplete facilities to users.


Try typing any initial letter of the name of any popular browser, and a drop down will be shown.

It is implemented as,


<input list="browsers" name="brow" />
<datalist id="browsers">
<option value="Internet Explorer" />
<option value="Firefox" />
<option value="Chrome" />
<option value="Opera" />
<option value="Safari" />
</datalist>
 

Demonstrating attribute multiple

The multiple attribute is a boolean attribute. When present, it specifies that the user is allowed to enter more than one value in the <input> element. The multiple attribute works with input types: email, and file. Thus we can now select multiple images via a single input, and the best part is it works in all browsers except IE.

It can be implemented as
<input id=’pics’ name=’pics’ type=’file’ multiple required />

 
 

Demonstrating type color

The color type is used for input fields that should contain a color.

It can be implemented as
<input type=”color” name=”mycolor” required />
Works with opera.

 
 

Beside the one’s covered above the other input types are

DATETIME The datetime type allows the user to select a date and time (with time zone).
DATETIME-LOCAL The datetime-local type allows the user to select a date and time (no time zone).
MONTH The month type allows the user to select a month and year
RANGE The range type can be used for input fields that should contain a value from a range of numbers.Similar to type NUMBER, we can also set restrictions on what numbers are accepted.
SEARCH The search type can be used for search fields (currently a search field behaves like a regular text field as it is not supported by many browser).
TIME The time type allows the user to select a time no time zone is defined currently.
WEEK The week type allows the user to select a week and year.

With an implementation of these new input types we can save alot of Javascript validation.

 

Attributes for Form and Input tag

autocomplete The autocomplete attribute specifies whether a form or input field should have autocomplete on or off. When autocomplete is on, the browser automatically complete values based on values that the user has entered before. It is possible to have autocomplete “on” for the form, and “off” for specific input fields, or vice versa.
novalidate The novalidate attribute is a boolean attribute. When present, it specifies that the form-data (input) should not be validated when submitted.
form The form attribute helps us to specifie us that an <input> element belongs to one or more forms. To refer to more than one form, we can use a space-separated list of form ids.
formaction The formaction attribute specifies the URL of a file that will process the input control when the form is submitted. The formaction attribute overrides the action attribute of the <form> element.It is used with type=”submit” and type=”image”.
formenctype The formenctype attribute specifies how the form-data should be encoded when submitting it to the server (only for forms with method=”post”). The formenctype attribute overrides the enctype attribute of the <form> element.It is used with type=”submit” and type=”image”.
formmethod The formmethod attribute defines the HTTP method for sending form-data to the action URL. The formmethod attribute overrides the method attribute of the <form> element.The formmethod attribute can be used with type=”submit” and type=”image”.
formnovalidate The novalidate attribute is a boolean attribute. When present, it specifies that the <input> element should not be validated when submitted. The formnovalidate attribute overrides the novalidate attribute of the <form> element. The formnovalidate attribute can be used with type=”submit”.
formtarget The formtarget attribute specifies a name or a keyword that indicates where to display the response that is received after submitting the form.
The formtarget attribute overrides the target attribute of the <form> element. The formtarget attribute can be used with type=”submit” and type=”image”.
pattern The pattern attribute specifies a regular expression that the <input> element’s value is checked against.
step The step attribute specifies the legal number intervals for an <input> element. Example: if step=”3″, legal numbers could be -3, 0, 3, 6, etc.The step attribute can be used together with the max and min attributes to create a range of legal values. Works with the following input types: number, range, date, datetime, datetime-local, month, time and week. The pattern attribute works with the input types: text, search, url, tel, email, and password.

More to come on HTML5 features, API’s and also on other Web Development topics (CSS, PHP, AJAX, etc…) in our upcoming posts. So Keep visiting…

HTML5 features and structure elements

A Lot has already been written for HTML5 though it is still in draft mode but the other side of the coin is 90% of its features already supported by Modern Browsers. Moreover the big giants of the web ( Apple, Facebook , Google, Yahoo etc…) have already started using it. HTML5 has many new and helpful features, which makes it very robust and independent. It is like a boom to mobile and web applications. Instead of writing all aspect of HTML5 we are mainly focusing on core features of HTML5, the topics that will be covered are enough to get started with HTML5 from a developers point of view.

HTML has been in continuous evolution since it was introduced to the Internet in the early 1990s. The HTML5 draft reflects an effort, started in 2004, to study contemporary HTML implementations and deployed content. The draft:

  1. Defines a single language called HTML5 which can be written in HTML syntax and in XML syntax.
  2. Defines detailed processing models to foster inter operable implementations.
  3. Improves markup for documents.
  4. Introduces markup and APIs for that can be very helpful for making Web Development easy.

HTML5 is still a draft, because the contents of HTML5, are still being discussed on the HTML Working Group and WHATWG (Web Hypertext Application Technology Working Group) mailing lists.

Document Type

If we start writing a normal HTML page the first thing that comes to our mind is the DOCTYPE (a doctype specifies a document type), HTML5 provides a New Doctype.

Usually a doctype was written as shown below,

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "//www.w3.org/TR/html4/loose.dtd">
totally confusing, for beginners it was terror, to understand all this, well not any more HTML5 has introduced a simple doctype
<!DOCTYPE html>

which itself defines what it is, i.e. it is an HTML document.

In fact, doctype is even not necessary in HTML5? However, it’s used for current, and older browsers that require a specified doctype. Browsers that do not understand this doctype will simply render the contained markup in standards mode.

Structure Elememts of HTML5

Once a doctype is specified the second thing that comes to mind is the structure of the document, HTML5 provides a complete new set of Structure Elements that will help us to define the structure of our document. Moreover these tags are self explanatory which will help us to distinguish one part of document from another.

Before discussing upon all these new elements have a look on the image below. The image itself gives all the explanation for the new structure elements.

<header> tag defines the header of a page.

<article> tag defines the article or the primary content on a page.

<section> tag to define sections of pages/article.

There can be multiple <section> tags inside the <article> tag or the <aside> tag.

<aside> tag defines extra content of a page like a sidebar on a page.

We can use multiple header and footer tags in our file and can even nest them.

Besides the Structure Elements covered above there are some others too that can be of great use to us, they are briefed below.

<bdi> Isolates a part of text that might be formatted in a different direction
from other text outside it
<command> Defines a command button that a user can invoke
<details> Defines additional details that the user can view or hide
<summary> Defines a visible heading for a <details> element
<figure> Specifies self-contained content, like illustrations, diagrams, photos, code
listings, etc.
<figcaption> Defines a caption for a <figure> element
<hgroup> Groups a set of <h1> to <h6> elements when a heading has multiple levels
<mark> Defines marked/highlighted text
<meter> Defines a scalar measurement within a known range (a gauge)
<nav> Defines navigation links
<progress> Represents the progress of a task
<ruby> Defines a ruby annotation (for East Asian typography)
<rt> Defines an explanation/pronunciation of characters (for East Asian
typography)
<rp> Defines what to show in browsers that do not support ruby annotations
<section> Defines a section in a document
<time> Defines a date/time
<wbr> Defines a possible line-break

These new elements are no different than styling a div element then why to use them? The main reason to use these new basic page structure elements is not because they add some new powerful tools to web development. What they add instead is readability to your HTML markup. Instead of trudging through multiple div elements to find the navigation section of the page wouldn’t it be quicker and easier to do a simple find for the nav element?

Making HTML5 Structure work with older Browsers

As these elements are new, they are not defined for old browsers and IE, so there is a lack of support for these features across browsers is less than ideal, but in fact it doesn’t really matter for our purposes very much.

We can get HTML5 elements working across all browsers today with the minimum of effort.

If we put an element into a web page that the browser doesn’t recognize, by default the browser will just treat it like a <span>, i.e., an anonymous inline element. These new elements are supposed to behave like block elements, therefore the easiest way to make them behave properly in older browsers is by setting them to display:block; in our CSS. we can do this by including the following CSS rule at the top of your CSS, whether it is contained in the head of your HTML file, or an external CSS file.

article, section, aside, hgroup, nav, header, footer, figure, figcaption {
display: block;
}

This solves all your problems for all browsers except one. Older versions of Internet Explorer refuse to allow styling of unknown elements, but this can be fixed by inserting a line of JavaScript into the head of your document for each element, like so:

<script>
document.createElement('article');
document.createElement('section');
document.createElement('aside');
document.createElement('hgroup');
document.createElement('nav');
document.createElement('header');
document.createElement('footer');
document.createElement('figure');
document.createElement('figcaption');
</script>

IE will now magically apply styles to those elements. There is also a problem with these styles STILL not being carried through to the printer when you try to print HTML5 documents from IE. This print problem can be solved using the HTML5 Shiv JavaScript library created by Remy Sharp, which also handles adding the document.createElement lines for us, we should wrap it up in Conditional comments for IE less than IE9, so that the modern browsers don’t execute the JS.

Features of HTML5

HTML5 supports a complete new set of features along with some API’s, the features/API’s are as listed below.

  • HTML 5 Form
  • Geolocation
  • Communication
  • Web Workers
  • Web Storage
  • Web Socket
  • Canvas
  • Offline Web Application
  • Audio and Video

Individually, there is a lot to discuss about the features of HTML5, hence for now they are just listed above, light on all features will be put down in our upcoming posts.