HTML5 Canvas Overview

Source: Internet
Author: User
Tags unsupported

Comments: Canvas is a new HTML element, which can be used by the Script language (usually JavaScript) to draw graphics. For example, you can use it to draw images, synthesize images, or make simple (and less simple) animations.

<Canvas> is a new HTML element, which can be used by the Script language (usually JavaScript) to draw graphics. For example, you can use it to draw images, synthesize images, or make simple (and less simple) animations. The image on the right shows some <canvas> application examples. We will see their implementation in this tutorial.

<Canvas> it was first introduced on Apple's Mac OS X Dashboard and then applied to Safari. Gecko1.8-based browsers, such as Firefox 1.5, also support this new element. Element <canvas> is part of the WhatWG Web applications 1.0 standard HTML 5 that everyone knows.

In this tutorial, I will try to show you how to use the <canvas> element on your own webpage. The provided example should give you some clear concepts, that is, what can be done with <canvas>. These examples can also be used as the starting point for your <canvas> application.

Before getting started
It is not difficult to use the element <canvas>, as long as you have basic knowledge of HTML and JavaScript.

As mentioned above, not all modern browsers support the <canvas> element, therefore, you need Firefox 1.5 or an updated version, or other Gecko-based browsers such as Opera 9 or Safari of the latest version to see all the actions of the example.

<Canvas> element

Let's start this tutorial by looking at the <canvas> element itself.
Let's start with the definition of the <canvas> element.

<canvas id="tutorial" width="150" height="150"></canvas>

This looks a lot like the element, the only difference is that it doesn' t have the src and alt attributes. <canvas> it looks like . The only difference is that it does not contain the src and alt attributes. The <canvas> element has only two attributes-WidthAndHeight. These are both optional and can also be set using DOM properties or CSS rules. It has only two attributes,WidthAndHeightBoth are optional and can be set by DOM or CSS. When no width and height attributes are specified, the canvas will initially be300 pixelsWide and150 pixelsHigh. If width and height are not specified, the default value is300 pixels in width,Up to 150 pixels. The element can be sized arbitrarily by CSS, but during rendering the image is scaled to fit its layout size. (If your renderings seem distorted, try specifying your width and height attributes explicitly in the <canvas> attributes, and not with CSS .) although you can adjust the size of the canvas through CSS, the rendered image scales to adapt to the layout. (If you find that the rendering result looks distorted, you do not have to rely on CSS, you can explicitly specify the width and height attribute values of the canvas ).

The id attribute isn't specific to the <canvas> element but is one of default HTML attributes which can be applied to (almost) every HTML element (like class for instance ). it's always a good idea to supply an id because this makes it much easier to identify it in our script.
The id attribute is not <canvas> exclusive. Like the standard HTLM tag, any HTML element can specify its id value. Generally, it is a good idea to specify an id for the element, which makes it easier to apply the id in the script.

The <canvas> element can be styled just like any normal image (margin, border, background, etc ). these rules however don't affect the actual drawing on the canvas. we'll see how this is done later in this tutorial. when no styling rules are applied to the canvas it will initially be fully transparent. <canvas> An element can specify its style (margin, border, background, etc.) like a normal image ). However, these styles do not affect the image actually generated by the canvas. The following shows how to apply a style. If no style is specified, canvas is completely transparent by default.

Alternative content

Because the <canvas> element is still relatively new and isn' t implemented in some browsers (such as Firefox 1.0 and Internet Explorer ), we need a means of providing fallback content when a browser doesn't support the element.

Because <canvas> is relatively new, Some browsers are not implemented, such as Firefox 1.0 and Internet Explorer, we need to provide alternative display content for browsers that do not support canvas.

Luckily this is very straightforward: we just provide alternative content inside the canvas element. browsers who don't support it will ignore the element completely and render the fallback content, others will just render the canvas normally.
For instance we cocould provide a text description of the canvas content or provide a static image of the dynamically rendered content. This can look something like this:

We only need to insert the alternative content directly in the canvas element. Browsers that do not support canvas will ignore the canvas Element and directly render the alternative content. The supported browsers will render the canvas normally. For example, you can enter some text or images in the canvas as the alternative content:

<canvas id="stockGraph" width="150" height="150">  current stock price: $3.15 +0.15</canvas><canvas id="clock" width="150" height="150">  </canvas>
The end tag </canvas> is required.

In the Apple Safari implementation, <canvas> is an element implemented in much the same way is; it does not have an end tag. however, for <canvas> to have widespread use on the web, some facility for fallback content must be provided. therefore, Mozilla's implementationRequiresAn end tag (</canvas> ).

In Apple Safari, the implementation of <canvas> is similar to that of . It does not end with a tag. However, to make <canvas> widely available in the web world, you need to provide a place for the alternative content. Therefore, in Mozilla's implementation, the end label (</canvas>) is required.

If fallback content is not needed, a simple <canvas id = "foo"...> </canvas> will be fully compatible with both Safari and Mozilla -- Safari will simply ignore the end tag.

If there is no alternative content, <canvas id = "foo"...> </canvas> is fully compatible with Safari and Mozilla-Safari simply ignores the end tag.

If fallback content is desired, some CSS tricks must be employed to mask the fallback content from Safari (which shocould render just the canvas ), and also to mask the CSS tricks themselves from IE (which shocould render the fallback content ).

If there is alternative content, you can use some CSS techniques to hide the alternative content for Safari only, because the alternative content needs to be displayed in IE but not in Safari.

Rendering Context)

<Canvas> creates a fixed size drawing surface that exposes one or moreRendering contexts, Which are used to create and manipulate the content shown. we'll focus on the 2D rendering context, which is the only currently defined rendering context. in the future, other contexts may provide different types of rendering; for example, it is likely that a 3D context based on OpenGL ES will be added.

<Canvas> one or more rendering contexts (Rendering context), We can use them to control the content to be displayed. We focus on 2D rendering, which is currently the only option. We may add a 3D context based on OpenGL ES in the future.

The <canvas> is initially blank, and to display something a script first needs to access the rendering context and draw on it. the canvas element has a DOM method called getContext, used to obtain the rendering context and its drawing functions. getContext () takes one parameter, the type of context.

<Canvas> Initialization is blank. To draw a picture using a script, you must first use its rendering context (rendering context). It can be obtained through the getContext method of the canvas Element Object, at the same time, some functions for drawing are also obtained. GetContext () accepts a value that describes its type as a parameter.

var canvas = document.getElementById('tutorial');var ctx = canvas.getContext('2d');

In the first line we retrieve the canvas DOM node using the getElementById method. We can then access the drawing context using the getContext method.

The first line above uses the getElementById method to obtain the DOM node of the canvas object. Then, the getContext method is used to obtain the Painting Operation context.

Check browser support

The fallback content is displayed in browsers which do not support <canvas>; scripts can also check for support when they execute. this can easily be done by testing for the getContext method. our code snippet from above becomes something like this:

In addition to displaying alternative content on unsupported browsers, you can also use scripts to check whether the browser supports canvas. The method is simple. You can check whether getContext exists.

var canvas = document.getElementById('tutorial');if (canvas.getContext){  var ctx = canvas.getContext('2d');  // drawing code here} else {  // canvas-unsupported code here}
Code Template

Here is a minimalistic template, which we'll be using as a starting point for later examples. You can download this file to work with on your system.

We will use the following simplified code template (which will be used in subsequent examples) as the starting point. You can download the file to the local backup.

If you look at the script you'll see I 've ve made a function called draw, which will get executed once the page finishes loading (via the onload attribute on the body tag ). this function cocould also have been called from a setTimeout, setInterval, or any other event handler function just as long the page has been loaded first.

Carefully, you will find that I have prepared a function named draw, which will be executed once after the page is loaded (by setting the onload attribute of the body Tag). Of course, it can also be set in setTimeout, setInterval, or other event processing functions.

A simple example

To start off, here's a simple example that draws two intersecting rectangles, one of which has alpha transparency. We'll learn e how this works in more detail in later examples.

At the beginning, let's make it simple: draw two staggered rectangles, one of which has the alpha transparency effect. In the following example, we will show you in detail how it works.


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.