Example of Canvas in HTML5

Source: Internet
Author: User
Tags rotate image

Canvas not only can draw lines (paths), but also can draw many other images, this chapter describes the canvas of the other two kinds of drawing APIs.


One, simple graphics, the entire set of properties and methods used specifically to draw a rectangle:

1, FillStyle can be set to a CSS color, a pattern or a color gradient. FillStyle The default is pure black, you can set it to any color you like. As soon as the page is open, each drawing context records its own properties, unless you reset it.
2. FillRect (x,y,width,height) draws a rectangle and fills it with the current FillStyle.
3, Srtokestyle and FillStyle can be set to a CSS color, a pattern, or a color gradient.
4, Strokerect (x,y,width,height) uses the current Storke style to draw a rectangle, Strokerect does not fill the middle area, but only the edges of the rectangle.
5, Clearrect (x,y,width,height) clears the pixels of the specified rectangular region.
Second, the path
By convention, whatever shape you start to draw, the first thing you need to call is Beginpath. This simple function takes no arguments and is used to inform the canvas that a new graphic is about to be drawn. For canvas, the greatest use of the Beginpath function is that canvas need to compute the inner and outer ranges of the graph to complete subsequent strokes and fills.
The path tracks the current coordinates, and the default value is the origin. The canvas itself also tracks the current coordinates, but may be modified by drawing code.
Each canvas has a path that defines the path as if it were painted in pencil. You can draw at will, but it is not necessarily part of the final work until you pick up the brush and ink to depict the path.
MoveTo (x,y): Do not draw, just move the current position to the new target coordinate (x,y) and as the line start point.
LineTo (X,y): Draws the line to the specified target coordinate (x,y) and draws a line between the two coordinates. Regardless of which one is invoked, no graphics are actually drawn, because we do not yet have the master, calling stroke (drawing) and Fil (fill) functions. Currently, only in the location where the path is defined so that it is used when drawing later.
Closepath (), this function is similar to LineTo, the only difference is that Closepath will automatically target the starting coordinates of the path as the destination coordinates. The Closepath also notifies canvas that the current drawing is closed or that a fully enclosed area is formed. The connection starting point, the function of the closed path.
Third, the text
You manipulate canvas text in the same way that you manipulate other path objects: You can paint the text outline and fill the interior of the text, and all transformations and styles that can be applied to other shapes can be used for text. The text drawing function of a context object consists of two functions:
Filltext (Text,x,y,maxwidth)
Troketext (Text,x,y,maxwidth)
Two parameters are exactly the same, and the required parameters include text parameters and coordinate parameters for the specified text position. MaxWidth is an optional parameter that restricts the font size, forcing the text font to be shrunk to a specified size. In addition, there is a measuretext function that returns a measure object that contains the actual display width of the specified text in the current context.
To ensure that the text is displayed properly under each browser, the following font attributes are available in the drawing context
1, font can be any value in the CSS font rules. Includes font styles, font variants, font size and weight, row heights, and font names.
2, TextAlign control the alignment of text. It is similar to the (but not exactly the same) text-align in CSS. The possible values are: start,end,left,right, and center.
3, Textbaseline control the text relative to the starting point position. Top,hanging,middle,alphabetic,ideographic and bottom can be evaluated. For simple English letters, you can safely use top,middle or bottom as a text baseline.
Four, color gradient
Once we have the drawing context, we can begin to define a color gradient. Gradients are smoothing over two or more colors. The canvas drawing context supports two types of gradients:
1. Createlineargradient (x0,y0,x1,x1) draws a gradient along a straight line from (x0,y0) to (x1,y1).
2. Createradialgradient (X0,Y0,R0,X1,Y1,R1) draws a gradient along the cone between two circles. The first three parameters represent the starting circles, the center of the Circle is (x0,y0) and the radius is r0. The last three parameters represent the end of the circle, the Center is (x1,y1), and the radius is R1.
Five, pictures
Several ways to draw pictures are defined in the canvas drawing context:
1, Drawiamge (Image,dx,dy) accept a picture and draw it into canvaa. The given coordinates (DX,DY) represent the upper-left corner of the picture. For example, the coordinates (0,0) will draw the picture to the upper-left corner of the canvas.
2. DRAWIAMGE (IMAGE,DX,DY,DW,DH) accepts a picture, scales it to the width DW and the high DH, and then draws it to the canvas (dx,dy) position.
3, Drawiamge (IMAGE,SX,SY,SW,SH,DX,DY,DW,DH) to accept a picture, through the parameters (Sx,sy,sw,sh) to specify the range of picture clipping, zoom to (DW,DH) the size, and finally draw it to the canvas (dx,dy Location
To draw an image on the canvas, you need to have a picture first. This image can be an existing html5_canvas_ attribute, definition and method (learning notes) element, or created through JS. Either way, you need to fully load this picture before drawing the canvas. Browsers typically load pictures asynchronously while the page script executes. If you try to render the picture to canvas before it is fully loaded, canvas will not display any pictures.
VI. Gradient
Gradients are the use of a step-by-step sampling algorithm on a color set and apply the results to stroke styles and fill styles. Using a gradient requires three steps:
(1) Create a Gradient object
(2) Set a color for the gradient object, indicating the transition mode
(3) Setting a gradient for a fill style or stroke style on the context
To set which color to display, use the Addcolorstop function on the gradient object. This function allows you to specify two parameters: color and offset. The color parameter refers to the color that the developer wants to stroke or fill at the offset position. The offset is a number from 0.0 to 1.0, representing how far the gradient along the gradient line is.
In addition to being able to convert to other colors, you can set alpha values for the color (such as transparency), and the alpha value can also be changed. To achieve this effect, you need to use another representation of the color value, such as the CSSRGBA function of the built-in alpha component.
In addition to linear gradients, the HTML5 Canvas API also supports a radioactive gradient, which is that the color is smoothed over a tapered area between two specified circles. The color termination points used by the radioactive gradient and the linear gradient are the same: the parameters are as follows:
Createradialgradient (X0,Y0,R0,X1,Y1,R1)
In code, the first three arguments represent (X0,Y0) as the center of the circle, the r0 is the radius, and the last three arguments are centered on (x1,y1) and the other circle of the radius is R1. The gradient appears in the middle of two circles.
Vii. Background Map
There are many uses for drawing images directly, but in some cases it is useful to use pictures as a background as CSS. The Html5canvas API also supports picture tiling. Call the Createpattern function.
Drawing curve (two times curve)
The starting point of the Quadraticcurveto function drawing curve is the current coordinate, with two sets of (x,y) parameters, and the second group refers to the end of the curve. The first group represents the control point. The so-called control points are located next to the curve (not above the curve), which acts as a force on the curve. By adjusting the position of the control point, you can change the curvature of the curve.
Other curve features of the HTML5 Canvas API also involve Beziercurveto, arcto, and ARC functions. These functions make the curve more malleable through a variety of control points, such as radii, angles, and so on.
Ix. Scaling Canvas Objects
Scale (X,y), which contains two parameters to represent the values in X,y two dimensions respectively. The amount of the image to enlarge (or shrink) on the axis of this direction when the image is displayed canvas each parameter. If the X value is 2, it means that all elements in the drawn image will be twice times wider. If the Y value is 0.5, all the elements of the image plotted will become half as high as before.
Note: To perform the transformation of graphics and paths at the origin, the execution is completed and then the translation is unified. The reason is that bloom (scale) and rotation (rotate) and other transformation operations are directed at the origin. If you rotate a shape that is not in the origin of a person, the rotate transformation function rotates the shape around the origin instead of in situ. Similarly, if the scaling operation is not placed to the appropriate coordinates, then all path coordinates are scaled at the same time. Depending on the size of the scaling, the new coordinates may be all beyond the canvas range, causing confusion to the developer, why does my zoom operation erase the image?
Ten, transform
The transformation operation is not limited to scaling and peace shift, we can use function context.rotate (angle) to rotate the image, even directly modify the underlying transformation matrix to complete some advanced operations, such as clipping the image of the drawing path. such as: Context.rotate (1.57), rotation angle parameters in radians.
Beginpath (): Start
MoveTo (x,y): Start coordinates
LineTo (x,y): target coordinates
Closepath (): Connection start, closed path
Translate (): Mobile
Rotate (): Rotate
Restore (): Recovering
Scale (): Scaling
Save (): Saving
Rotate (angle): Rotate image
Quadraticcurveto (): Drawing curves
Stroke (): Drawing
Stroketext (): depicting text outlines
Strokestyle (): Color settings
Strokerect (): Draws a rectangle with the current Storke style, and draws only the edges of the rectangle.
Fill: Padding
FillRect (): Draws a rectangle and fills it with the current FillStyle
FillStyle (): Style fill
Filltext: Populating text content
Drawiamge (): Picture fill
Createpattern (): Fill with background picture
Addcolorstop (): Gradient fill
Createradialgradient (): Radioactive gradient
Clearrect (): Clears pixels from specified rectangular area
. LineCap (Butt | Square | Round): Specifies the style at the end of the line
. FillStyle: Set to a CSS color, a pattern, or a color gradient
. LineWidth: Line width setting
. LineJoin (Round): Modifies the way segments in the current shape are connected so that the corners become more rounded
. Shadowcolor: Color values in any CSS, you can use Transparency (alpha)
. SHADOWOFFSETX: Pixel values, positive values, moving shadows to the right, negative values, moving shadows to the left
. shadowoffsety: Pixel values, positive values, move shadows down, negative values, move shadows up
. Shadowblur: Gaussian blur value, the larger the value, the more blurred the shadow


Rectangular

In the last chapter we drew a rectangle with only a thread, which we can actually draw at once, using the following function:

Ctx.fillrect (x, y, width, height)

Draw a filled rectangle, x, Y is the rectangle's upper left coordinate, and the remaining two are not the lower right coordinates but the width and height.
Ctx.strokerect (x, y, width, height)

Similar, but only draw lines do not fill.
Ctx.clearrect (x, y, width, height)

Deletes the specified area.

Let's start with three canvas (HTML code below):

<canvas id= "C1" width= "140" height= "140" ></canvas>
<canvas id= "C2" width= "140" height= "140" ></canvas>
<canvas Id= "C3" Width= "140" height= "140" ></canvas>

And then we have our drawing parameters:

Javascript


onload = function () {
DRAW1 ();
DRAW2 ();
DRAW3 ();
};
/* FillRect () * *
function Draw1 () {
var canvas = document.getElementById (' C1 ');
if (! Canvas | |! canvas.getcontext) {return false;}
var ctx = Canvas.getcontext (' 2d ');
Ctx.beginpath ();
Ctx.fillrect (20, 20, 80, 40);
}
/* Strokerect () * *
function Draw2 () {
var canvas = document.getElementById (' C2 ');
if (! Canvas | |! canvas.getcontext) {return false;}
var ctx = Canvas.getcontext (' 2d ');
Ctx.beginpath ();
Ctx.strokerect (20, 20, 80, 40);
}
/* Clearrect () * *
function draw3 () {
var canvas = document.getElementById (' C3 ');
if (! Canvas | |! canvas.getcontext) {return false;}
var ctx = Canvas.getcontext (' 2d ');
Ctx.beginpath ();
Ctx.fillrect (20, 20, 100, 100);
Ctx.beginpath ();
Ctx.clearrect (50, 70, 60, 30);
}
As shown in the following figure, you do not provide the actual demo file, please enter the confirmation yourself.

The last time we used the line painting, we used the fill and stroke method, and now we don't need it.

Circle (ARC)

First look at the parameters:

Ctx.arc (x, y, radius, startangle, Endangle, anticlockwise)
Draw a circle or circular arc. X,y is the center coordinate, radius is the radius, Startangle,endangle is the angle of the start/end stroke, anticlockwise is the circle counterclockwise (true is counterclockwise, false is clockwise).
Note that the angle here is radian, so if you draw a positive circle, it is 0-> Math.PI * 2, and the picture of 60°, is 0-> * math.pi/180, the most extreme is that this and our general geometry in the x direction of the direction of the 0°,y 90° in turn ... Use the above canvas, then draw a circle try:

Javascript


onload = function () {
DRAW1 ();
DRAW2 ();
DRAW3 ();
};
/* Whole Circle * *
function Draw1 () {
var canvas = document.getElementById (' C1 ');
if (! Canvas | |! canvas.getcontext) {return false;}
var ctx = Canvas.getcontext (' 2d ');
Ctx.beginpath ();
Ctx.arc (0, math.pi*2, false);
Ctx.stroke ();
}
/* 10°~ 80°, no Fill * *
function Draw2 () {
var canvas = document.getElementById (' C2 ');
if (! Canvas | |! canvas.getcontext) {return false;}
var ctx = Canvas.getcontext (' 2d ');
Ctx.beginpath ();
Ctx.arc (math.pi/180, * math.pi/180), true);
Ctx.stroke ();
}
/* 10°~ 80°, filling/*
function draw3 () {
var canvas = document.getElementById (' C3 ');
if (! Canvas | |! canvas.getcontext) {return false;}
var ctx = Canvas.getcontext (' 2d ');
Ctx.beginpath ();
Ctx.arc (math.pi/180, * math.pi/180), true);
Ctx.fill ();
}
As a result of the above three cases, please also enter a deeper impression.


The following figure is the case of startangle=1.1pi,endangle=1.9pi,anticlockwise to false, note that starting with the X axis and starting from the angle.

Canvas (color) in the HTML5

Specify color

So far we have painted the graphics are black, this is the default color canvas, to change a color, you have to specify the color before the actual painting.

Ctx.strokestyle = Color

--Specifies the color of the drawing line

Ctx.fillstyle = Color

--Specifies the color of the fill
Take a look at the actual example:

Javascript

onload = function () {
Draw ();
};
function Draw () {
var canvas = document.getElementById (' C1 ');
if (! Canvas | |! canvas.getcontext) {return false;}
var ctx = Canvas.getcontext (' 2d ');
Ctx.beginpath ();
Ctx.fillstyle = ' RGB (192, 80, 77) '; Red
Ctx.arc (0, math.pi*2, false);
Ctx.fill ();
Ctx.beginpath ();
Ctx.fillstyle = ' rgb (155, 187, 89) '; Green
Ctx.arc (n, 0, math.pi*2, false);
Ctx.fill ();
Ctx.beginpath ();
Ctx.fillstyle = ' rgb (128, 100, 162) '; Purple
Ctx.arc (0, math.pi*2, false);
Ctx.fill ();
}

The effect of the following figure:

Specify transparency

As with the normal CSS, we can also specify a color with an alpha value (but not much, IE9 not supported before). Look at the code:


onload = function () {
Draw ();
};
function Draw () {
var canvas = document.getElementById (' C1 ');
if (! Canvas | |! canvas.getcontext) {return false;}
var ctx = Canvas.getcontext (' 2d ');
Ctx.beginpath ();
Ctx.fillstyle = ' Rgba (192, 80, 77, 0.7) '; //
Ctx.arc (0, math.pi*2, false);
Ctx.fill ();
Ctx.beginpath ();
Ctx.fillstyle = ' Rgba (155, 187, 89, 0.7) '; //
Ctx.arc (n, 0, math.pi*2, false);
Ctx.fill ();
Ctx.beginpath ();
Ctx.fillstyle = ' Rgba (128, 100, 162, 0.7) '; //
Ctx.arc (0, math.pi*2, false);
Ctx.fill ();
}

The result is the following:


And the above code basically does not change, is the RGB (R, G, b) into Rgba (R, G, B, a) only, the value of a is 0~1,0 for full transparency, 1 is completely opaque (so the value of alpha is actually "opacity").

Global transparency

We added 0.7 alpha values to each circle, but each of our rounded alpha is the same, and it's a bit of a hassle to write each one (say I'm not bothered ...). Just don't say so can not draw out this new function AH:

Ctx.globalalpha = Alpha

This parameter specifies the global alpha value, so that when you set it, all the pictures will have a bit of transparency, unless you specifically specify it. So change our first example a little bit:

onload = function () {
Draw ();
};
function Draw () {
var canvas = document.getElementById (' C1 ');
if (! Canvas | |! canvas.getcontext) {return false;}
var ctx = Canvas.getcontext (' 2d ');
Ctx.globalalpha = 0.7; That's one more thing.
Ctx.beginpath ();
Ctx.fillstyle = ' RGB (192, 80, 77) ';
Ctx.arc (0, math.pi*2, false);
Ctx.fill ();
Ctx.beginpath ();
Ctx.fillstyle = ' rgb (155, 187, 89) ';
Ctx.arc (n, 0, math.pi*2, false);
Ctx.fill ();
Ctx.beginpath ();
Ctx.fillstyle = ' rgb (128, 100, 162) ';
Ctx.arc (0, math.pi*2, false);
Ctx.fill ();
}
And then our results are exactly the same as 2:

When you paint more, you can still play a lot of words less.

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.