[HTML5] Canvas basics-

Source: Internet
Author: User
The HTML5 specification introduces many new features, one of the most promising ones is the Canvas Element. HTML5Canvas provides a JavaScript method for Drawing Images. This method is simple but powerful. Each Canvas element has a "context" (as imagined on the drawing board ...,. The HTML5 specification introduces many new features, one of the most promising ones is the Canvas Element. HTML5 Canvas provides a method to draw images using JavaScript. This method is simple but powerful. Each Canvas element has a "context" (as a page on the drawing board) where any image can be drawn. The browser supports multiple Canvas contexts and provides graphical rendering through different APIs.

Most browsers support 2D Canvas context, including Opera, Firefox, Konqueror, and Safari. Some versions of Opera also support 3D Canvas, and Firefox also supports 3D Canvas through plug-ins.

This article describes the basics of 2D Canvas and how to use basic Canvas functions, such as lines, shapes, images, and text. To understand this article, you 'd better understand the basics of JavaScript.
Let's start with the following:

Canvas Basics

The Canvas creation method is simple. You only need to add
To reference a Canvas in JavaScript, it is best to set the ID for it. You also need to set the height and width for the Canvas.

JavaScript is required to draw a graph in the Canvas. First, use the getElementById function to find the Canvas Element, initialize the context, and then use the context API to draw various images. The following script can draw a rectangle in the Canvas:



  1. var elem = document.getElementById('myCanvas');if (elem && elem.getContext) {  var context = elem.getContext('2d');  if (context) {    context.fillRect(0, 0, 150, 100);  }}



You can place the above Code in the head part of the document or in an external JavaScript file.

2D context API


After introducing how to create a Canvas, let's take a look at the 2D Canvas API to see what can be done with these functions.

In the above example, we show how simple it is to draw a rectangle. The fillStyle and strokeStyle attributes allow you to easily set the filling and line of the rectangle. The color value is used in the same way as CSS: hexadecimal number, rgb (), rgba (), and hsla ().

FillRect can be used to draw a rectangle with padding; strokeRect can be used to draw a rectangle without padding. If you want to clear some of the Canvas, you can use clearRect. The parameters of the preceding three methods are the same: x, y, width, and height. The first two parameters set the coordinates (x, y), and the last two parameters set the height and width of the rectangle.
The following is a JavaScript script for a comprehensive example:

context.fillStyle   = '#00f';context.strokeStyle = '#f00';context.lineWidth   = 4;context.fillRect  (0,   0, 150, 50);context.strokeRect(0,  60, 150, 50);context.clearRect (30, 25,  90, 60);context.strokeRect(30, 25,  90, 60);






You can place the above Code in the head part of the document or in an external JavaScript file.

Path


You can draw any shape using the Canvas path. You can draw an outline first, then draw a border and fill it. It's easy to create a custom shape. Use beginPath () to start plotting, and then use straight lines, curves, and other graphics to draw your graph. After painting, call fill and stroke to add or set the border. Call closePath () to end custom image painting.

The following is a JavaScript script used to draw a triangle:

context.fillStyle   = '#00f';context.strokeStyle = '#f00';context.lineWidth   = 4;context.beginPath();context.moveTo(10, 10);context.lineTo(100, 10);context.lineTo(10, 100);context.lineTo(10, 10);context.fill();context.stroke();context.closePath();



You can place the above Code in the head part of the document or in an external JavaScript file.

Insert Image


The drawImage method allows you to insert other images (img and Canvas elements) into the Canvas ). You can draw SVG images in the Canvas in Opera. This method is complex and can have three, five, or nine parameters:

Three parameters: the most basic drawImage usage method. One parameter specifies the image position, and the other two parameters set the position of the image in the Canvas.

Five parameters: Intermediate drawImage usage, including the three parameters described above, plus two parameters to specify the width and height of the inserted image (if you want to change the image size ).

Nine parameters: the most complex drawImage usage method, including the preceding five parameters. The other four parameters are used to set the position and height width of the source image. These parameters allow you to dynamically crop the source image before displaying the image.

The following are examples of the above three methods:

context.drawImage(img_elem, dx, dy);context.drawImage(img_elem, dx, dy, dw, dh);context.drawImage(img_elem, sx, sy, sw, sh, dx, dy, dw, dh);




You can place the above Code in the head part of the document or in an external JavaScript file.

Pixel-level operations


The 2D Context API provides three methods for Pixel-level operations: createImageData, getImageData, and putImageData.

The ImageData object stores the image pixel value. Each object has three attributes: width, height, and data. The data attribute type is CanvasPixelArray, which is used to store width * height * 4 pixel values. Each pixel has an RGB value and a transparency alpha value (its value ranges from 0 to 255, including alpha .). The pixel sequence is stored from left to right, from top to bottom, by row.

Let's look at an example:

var imgd = context.createImageData(50,50);var pix = imgd.data;for (var i = 0; n = pix.length, i < n; i += 4) {  pix[i  ] = 255;  pix[i+3] = 127;}context.putImageData(imgd, 0,0); 


Note: not all browsers implement createImageData. In the supported browsers, you must use the getImageData method to obtain the ImageData object.

ImageData provides many functions. For example, Image filters or mathematical visualization (such as fragment and other special effects) can be implemented ). Let's look at an example:

var imgd = context.getImageData(x, y width, height);var pix = imgd.data;for (var i = 0, n = pix.length; i < n; i += 4) {  pix[i  ] = 255 - pix[i  ];  pix[i+1] = 255 - pix[i+1];  pix[i+2] = 255 - pix[i+2];}context.putImageData(imgd,x, y); 


You can place the above Code in the head part of the document or in an external JavaScript file.

Text


Although the Text API is supported only in the latest WebKit version and Firefox 3.1 nightly build, I decided to introduce the Text API here to ensure the integrity of the article.
You can set the following text attributes for the context object:

Font: text font, same as CSS font-family;

TextAlign: horizontal alignment of text. Optional property values: start, end, left, right, and center. Default Value: start;

TextBaseline: vertical alignment of text. Optional attribute values: top, hanging, middle, alphabetic, ideographic, and bottom. Default Value: alphabetic.

There are two ways to draw text: fillText and strokeText. The first draws the text filled with fillStyle, and the latter draws the text only with the strokeStyle border. The two parameters are the same: the coordinates of the text and text to be drawn (x, y. There is also an optional option-maximum width. If necessary, the browser will reduce the text so that it can adapt to the specified width.

The text alignment attribute affects the relative position of the text and the Set (x, y) coordinates.

ontext.fillStyle    = '#00f';context.font         = 'italic 30px sans-serif';context.textBaseline = 'top';context.fillText  ('Hello world!', 0, 0);context.font         = 'bold 30px sans-serif';context.strokeText('Hello world!', 0, 50); 


You can place the above Code in the head part of the document or in an external JavaScript file.

Shadow


Currently, only Konqueror and Firefox 3.1 build support the Shadows API. The property of the API is shadowColor. The value is consistent with the CSS color value.

ShadowBlur: sets the shadowBlur blur level. The larger the value, the blurrier the shadow. The effect is the same as that of the Gaussian blur filter in Photoshop.

ShadowOffsetX and shadowOffsetY: the offset between x and y of the shadow, in pixels.

context.shadowOffsetX = 5;context.shadowOffsetY = 5;context.shadowBlur    = 4;context.shadowColor   = 'rgba(255, 0, 0, 0.5)';context.fillStyle     = '#00f';context.fillRect(20, 20, 150, 100); 


You can place the above Code in the head part of the document or in an external JavaScript file.

Color gradient


In addition to the CSS color, the fillStyle and strokeStyle attributes can be set as CanvasGradient objects. -- Use CanvasGradient to change the color gradient for lines and fills.

To create a CanvasGradient object, you can use the createLinearGradient and createRadialGradient methods. The former creates a linear color gradient, and the latter creates a circular color gradient.

After creating a color gradient object, you can use the addColorStop method of the object to add the color median.

The following code demonstrates how to use a color gradient:

var gradient1 = context.createLinearGradient(sx,sy,dx,dy);gradient1.addColorStop(0,   '#f00');gradient1.addColorStop(0.5, '#ff0');gradient1.addColorStop(1,   '#00f');var gradient2 = context.createRadialGradient(sx,sy,sr,dx,dy, dr); 


You can place the above Code in the head part of the document or in an external JavaScript file.

Summary


Canvas is one of the most promising features of HTML5. Currently, most Web browsers support Canvas to help create games and enhance graphic user interfaces. The 2D context API provides a large number of graphic rendering functions-I hope you will learn more about the use of Canvas through this article, and you are interested in learning more!


The above section describes the basic knowledge of Canvas in [HTML5]. For more information, see the PHP Chinese website (www.php1.cn )!

Related Article

E-Commerce Solutions

Leverage the same tools powering the Alibaba Ecosystem

Learn more >

Apsara Conference 2019

The Rise of Data Intelligence, September 25th - 27th, Hangzhou, China

Learn more >

Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth $300-1200 USD

Learn more >

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.