HTML5 playing and learning (2) Basic plotting Implementation Method

Source: Internet
Author: User

Comments: In the previous blog, we tested the usage of the canvas label and obtained the rendering context object of the canvas label, but did not use it to draw any graphics. In this article, let's first take a look at some basic concepts of HTML5 plotting, and then draw a few graphics to play.

I. Coordinate System

In fact, anyone who has played a little graphic programming knows that the coordinate system on the computer is slightly different from the coordinate system on mathematics. The coordinate origin is in the upper left corner of the drawing area (Canvas, the X axis is forward to right, and the Y axis is forward to face down, as shown in figure

Statement:The author reserves all rights for the original article! You are welcome to reprint it. Please indicate the author.Left BranchAnd SourceBlog

 

Ii. Stroke and Fill

In HTML5, graphics are classified into two categories:

The first class is called Stroke. My understanding is outline, outline, or line. In short, a graph is composed of lines;

The second type is Fill, which is the filling area.

There are two ways to draw rectangles in the context object, which makes us better understand the differences between the two types of images:

One is strokeRect and the other is fillRect.

The following code uses these two methods to draw a rectangle. You can click the two buttons to see what is different, so as to understand the difference between stroke and fill.
Set canvas

The Code is as follows:
<Canvas id = "test1" width = "200" height = "200" style = "background-color: gray"> your browser does not support & lt; canvas & gt; label. Use Chrome or FireFox </canvas>
<Input type = "button" value = "strokeRect" onclick = "strokeRect ();"/>
<Input type = "button" value = "fillRect" onclick = "fillRect ();"/>


StrokeRect and fillRect

The Code is as follows:
Function strokeRect (){
Var canvas = document. getElementById ('test1 ');
Var ctx = canvas. getContext ("2d ");
Ctx. clearRect (0, 0, 200,200 );
Ctx. strokeStyle = "blue ";
Ctx. strokeRect (10, 10, 180,180 );
}
Function fillRect (){
Var canvas = document. getElementById ('test1 ');
Var ctx = canvas. getContext ("2d ");
Ctx. clearRect (0, 0, 200,200 );
Ctx. fillStyle = "blue ";
Ctx. fillRect (180,180 );
}
 

Your browser does not support <canvas> labels. Use Chrome or FireFox.

 

3. Color

The context object has two attributes that can be used to set colors: strokeStyle and fillStyle.

The value of strokeStyle determines the color of the line to be drawn.

The value of fillStyle determines the color of the area to be filled.

The color value should be a valid string that complies with the CSS3 color value standard. The following examples indicate the same color.

// These fillStyle values are 'Orange 'and ctx is the context object.
Ctx. fillStyle = "orange ";
Ctx. fillStyle = "# FFA500 ";
Ctx. fillStyle = "rgb (255,165, 0 )";
Ctx. fillStyle = "rgba (255,165 )";

For more information about the color, see later.

 

4. Basic plotting

In addition to the two methods shown above for drawing a rectangle, there are several ways for the context object to draw some basic images, as shown below:

MoveTo(X, y): The moveTo method cannot draw anything. It just moves the current point of the paint brush to (x, y ).

LineTo(X, y): draws a straight line from the current point to (x, y. Note: after the painting is complete, the current vertex becomes (x, y), unless you change it using the moveTo method.

Arc(X, y, radius, startAngle, endAngle, anticlockwise): draw an arc.

QuadraticCurveTo(Cp1x, cp1y, x, y)
BezierCurveTo(Cp1x, cp1y, cp2x, cp2y, x, y)

Rect(X, y, width, height): draws a rectangle. Note: when it is called, The moveTo method will be automatically called. The parameter is (0, 0), so the starting coordinate is restored to the initial origin.

With basic figures like straight lines, arcs, curves, squares, and circles, we can combine more complex figures.

 

5. Understand the Drawing Path

As mentioned in the previous article, the image we draw is first drawn to an abstract context object (in memory), and then output the context object to the display device, we do not need to worry about the process of output to the display device. However, sometimes we do not want to output every draw action immediately. Maybe I want to make a group of draw actions and then concentrate one output. For example, a go board consists of 19x19 straight lines, under normal circumstances, you need to output 19 × 19 times to the desired display device, but if we suspend the output to the display device, wait in the context (in memory) after all the lines are drawn, output to the display device only once.

This situation is called the draw path in HTML5. It consists of several context object methods:

BeginPath(): Start path, which means that after you call this method, the image you draw will not be output to the screen, but will only be drawn to the context object (in memory)

Stroke(): Outputs all lines drawn after you call beginPath to the display device at one time.

ClosePath(): If you call the beginPath method and draw a series of images in the context object, but the resulting image is not closed, this method will help you add the last line, close your graph.

Note::ClosePath does not output images to the screen, but just adds a line to the context object. This step is not required..

Fill():

If the image composed of your drawing path is closed, this method will fill the image with the color set by fillStyle, and then immediately output to the screen;

If the drawing path is not closed, this method will first close the image and then fill in the output.

Note:All fill images, such as fillRect, are immediately output to the screen. They do not have the concept of creating paths.

 

The following code draws a simple filled triangle.

Note: When creating a triangle,The Default background color is white, and the default foreground color is black..
Set canvas

The Code is as follows:
<Canvas id = "test2" width = "200" height = "200" style = "border: 1px solid # c3c3c3;"> your browser does not support & lt; canvas & gt; label. Use Chrome or FireFox </canvas>
<Input type = "button" value = "Draw triangle" onclick = "drawTri ();"/>
<Input type = "button" value = "clear" onclick = "clearTri ();"/>



Draw triangles

The Code is as follows:
<Script type = "text/javascript">
Function drawTri (){
Var canvas = document. getElementById ('test2 ');
Var ctx = canvas. getContext ("2d ");
Ctx. beginPath ();
Ctx. moveTo (75, 50 );
Ctx. lineTo (100,75 );
Ctx. lineTo (100,25 );
Ctx. fill ();
}
Function clearTri (){
Var canvas = document. getElementById ('test2 ');
Var ctx = canvas. getContext ("2d ");
Ctx. clearRect (0, 0, 200,200 );
}
</Script>

Your browser does not support <canvas> labels. Use Chrome or FireFox.

Your browser does not support <canvas> labels. Use Chrome or FireFox.

 

6. Coordinates of half units

Let's look back at the coordinates. The code below is to draw a grid on the canvas. Click the "Draw grid" button to see the effect.
Set canvas

The Code is as follows:
<Canvas id = "test2" width = "200" height = "200" style = "border: 1px solid # c3c3c3;"> your browser does not support & lt; canvas & gt; label. Use Chrome or FireFox </canvas>
<Input type = "button" value = "Draw triangle" onclick = "drawTri ();"/>
<Input type = "button" value = "clear" onclick = "clearTri ();"/>



Draw triangles

The Code is as follows:
<Script type = "text/javascript">
Function drawTri (){
Var canvas = document. getElementById ('test2 ');
Var ctx = canvas. getContext ("2d ");
Ctx. beginPath ();
Ctx. moveTo (75, 50 );
Ctx. lineTo (100,75 );
Ctx. lineTo (100,25 );
Ctx. fill ();
}
Function clearTri (){
Var canvas = document. getElementById ('test2 ');
Var ctx = canvas. getContext ("2d ");
Ctx. clearRect (0, 0, 200,200 );
}
</Script>

Your browser does not support <canvas> labels. Use Chrome or FireFox.

Your browser does not support <canvas> labels. Use Chrome or FireFox.

 

One strange thing in this Code is that the coordinate loop starts from 0.5. Why?

For example, if I want to draw a line from () to (), because the default width of the line is a pixel, I should plot itDark greenThat is, the width of each half pixel on both sides of coordinate 1.

However, the minimum unit of the browser is one pixel, so it will expand to both sides, actually drawnLight GreenThat occupies the width of two pixels. In this way, the lines we draw are not accurate on the coordinates.

For example, if the starting coordinates are (1.5, 0) and (1.5, 3), the width of the line is the correct pixel.

 

 

7. Clear the canvas

In the above two sections of code, we used to clear the canvas. The method used is as follows:

ClearRect (x, y, width, height ):

It accepts four parameters. x and y specify the position in the upper left corner of the rectangle (relative to the origin). width and height indicate the width and height of the rectangle. Call this method to clear all the drawn images in the given rectangular area to reveal the canvas background.


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.