Canvas exercises on Monday, canvas

Source: Internet
Author: User

Canvas exercises on Monday, canvas

Since the last week, my ears have been getting sick, and I have a big slice in it. It hurts when I touch it. If I cannot eat, I cannot wait )...... I would like to remind you that the weather has been very hot recently and you must pay attention to the heat and fire prevention measures ~

Next, I'm drinking five pieces of medicine and learning canvas ......

Canvas is a new label element added to html5. it is used to define images, such as tables and other images. <Canvas> labels are only graphical containers and must be drawn using scripts (usually javascript.

Differences between canvas and svg

Canvas is a new element provided by HTML5 <canvas>. The history of svg is longer than that of canvas for more than a decade. Svg is not a proprietary html5 label. Originally, svg used xml technology (hypertext extension language, custom tags or attributes) to describe two-dimensional graphics. First, canvas can be regarded as a canvas in terms of its functions. The drawn image is a scalar image. Therefore, images in jpg or png format can be introduced in the canvas. In actual development, large-scale online games are all made using canvas, and canvas technology is now quite mature. In addition, we like to use canvas for some statistical charts, such as bar chart or pie chart. The svg plot is a vector graph, so its usage is limited. Because only vector images can be drawn, common images cannot be introduced in svg. Because vector images do not have distortion, we will use dynamic small icons in projects. However, because it is essentially a vector image, it can be infinitely magnified without distortion. This is suitable for map use, while Baidu map uses svg technology. In addition, the graphics drawn in the canvas cannot be captured by the engine. For example, we want to let an image in the canvas follow the mouse event: canvas. onmouseover = function (){}. The graphics in svg can be captured by the engine and event binding is supported. In addition, we usually use JavaScript to draw images in the canvas. svg is more implemented by labels. For example, to draw a positive rectangle in svg, <rect> is required, the attribute style = "width: XXX; height: XXX;" cannot be defined here. Let me introduce a javascript library of svg: TWO. js. This includes two. js and three. js. The former is used to draw two-dimensional images, and the latter is used to draw three-dimensional images. TWO. JS supports three formats: svg (default), canvas, and WEBGL. Of course, it can also be introduced in a common div. To remove an element from a <canvas> flag of the same image, you need to erase it and re-draw it. svg is easy to edit and only needs to remove the element from its description. The above is what we saw in other blogs, so I will reference it first. After that, I will be familiar with canvas and svg and then write my own experiences. See http://blog.csdn.net/helloword_chen/article/details/49788309 for details


1. Basic syntax
<Canvas id = "canvasMain" width = "800" height = "600"> canvas is not supported in your browser. </canvas>

When the width and height are not set, the canvas is initialized with a width of PX and a height of PX. When the browser does not support the canvas label, the text is displayed.

In the canvas coordinate system, the upper left corner is the coordinate origin, the right is the positive direction of the X axis, and the downward is the positive direction of the Y axis, such:

To draw the canvas context, call the API to draw the image.

var canvas = document.getElementById("canvasMain"),    ctx = canvas.getContext("2d");

The content to be replaced is displayed in a browser that does not support the <canvas> label. You can also check whether the getContext () method is supported (Some browsers will create default html element objects for elements outside the html Specification)

var canvas = document.getElementById("canvasMain");if(canvas.getContext("2d")) {    var ctx = canvas.getContext("2d");    // drawing code here} else {    // canvas-unsupported code here}

Export the image drawn on the <canvas> element and receive a parameter, that is, the MIME type format of the image. If the image drawn to the canvas comes from different domains, this method reports an error.

Var canvas = document. getElementById ("canvasMain"); if (canvas. getContext) {// retrieve the image data URI var imgURI = canvas. toDataURL ('image/png '); // display the image var image = document. createElement ('img '); image. src = imgURI; document. body. appendChild (image );}

2. 2D Context

  • Fill and stroke

  Fill: Fill the image with the specified style (color, gradient, image); stroke: draw lines at the edge of the image. The two attributes are fillStyle strokeStyle, the attribute value can be a string, gradient object, or pattern object.

  • Draw a rectangle

Method for drawing a rectangle: fillRect () strokeRect () clearRect () parameters are in sequence: rectangular x coordinate, y coordinate, width, height

Var drawing = document. getElementById ('Drawing '); if (drawing. getContext) {var context = drawing. getContext ('2d '); context. strokeStyle = 'rgba (0, 0,255, 0.5) '; // stroke attribute context. fillStyle = 'pink '; // fill in the attribute context. lineWidth = 3; // stroke line width context. lineCap = 'square '; // the shape of the end of the line (butt Flat Head, round head, square head) context. lineJoin = 'round '; // The method of line intersection (round intersection, bevel skew, miter skew) context. fillRect (10, 10, 50, 50); // fill the rectangular context. fillStyle = 'green'; context. fillRect (30, 30, 50, 50); context. strokeRect (100, 10, 50, 50); // stroke rectangular context. clearRect (40, 40, 15, 15); // clear the rectangular area on the canvas}
  • Draw path

ClosePath () draws a line connecting to the starting point of the path

Fill () fill path stroke () stroke path clip () create a cut area on the path

IsPointInPath (x, y) determines whether a point on the canvas is located on the path

Var drawing = document. getElementById ('Drawing '); if (drawing. getContext) {/* draw path */var context = drawing. getContext ('2d '); context. strokeStyle = 'pink '; context. beginPath (); // start to draw a new path // draw an excircle context. arc2 (100,100, 99, 0, 2 * Math. PI, false); // The parameters are the center coordinate x, y, radius, and starting angle (expressed in radians) whether the end angle and start angle are calculated counterclockwise (flase is clockwise) context. moveTo (194,100); // move the drawing cursor to (x, y) without drawing a line // draw the inner circle context. arc2 (100,100, 94, 0, 2 * Math. PI, false); // draw the sub-needle context. VPC: moveTo (100,100); context. lineTo (100, 25); // draw a straight line from the previous point until (x, y) // draw the context of the hour. VPC: moveTo (100,100); context. lineTo (35,100); // draw the text context. font = 'bold 14px arial'; // indicates the text style, size, and font context. textAlign = 'center'; // text alignment (start, end, left, right, and center). We recommend that you use start and end instead of left and right context. textBaseline = 'middle'; // context of the text baseline (top, hanging, middle, alphabetical, ideopgraphic, and bottom. fillText ('12', 100, 20); // stroke path context. stroke (); // additional exercise context. moveTo (230, 10); // arcTo (x1, y1, x2, y2, radius): draw an arc from the previous point to (x2, y2, and pass through (x1, y1) context with the given radius. arcTo (280, 60,330, 10, 50); // bezierCurveTo (c1x, c1y, c2x, c2y, x, y): Draw a curve from the previous point to (x, y), and (c1x, c1y) (c2x, c2y) as the control point context. bezierCurveTo (210, 70,290, 90,300,100); context. moveTo (320, 10); // quadraticCurveTo (cx, cy, x, y): Draw a quadratic curve from the previous point to (x, y, and uses (cx, cy) as the control point context. quadraticCurveTo (420,100,400, 10); // rect (x, y, width, height): draws a rectangle from a vertex (x, y, this method draws a rectangular path instead of an independent context shape. rect (450, 10, 50, 50); context. stroke ();}
  • Draw text

  FillText () draws the text strokeText () as the text stroke parameter: text string, x coordinate, y coordinate, optional maximum pixel width

  • Transform

  

Var drawing = document. getElementById ('Drawing '); if (drawing. getContext) {// convert var context = drawing. getContext ('2d '); context. strokeStyle = 'rgba (0, 0,255, 0.5) '; context. beginPath (); context. arc2 (100,100, 99, 0, 2 * Math. PI, false); context. VPC: moveTo (194,100); context. arc2 (100,100, 94, 0, 2 * Math. PI, false); // converts the origin context. translate (100,100); // move the coordinate origin to this point // rotate the context of the table needle. rotate (1); // rotate the image angle radian around the origin // draw the sub-needle context. moveTo (0, 0); context. lineTo (0,-80); // draw the context of the hour. moveTo (0, 0); context. lineTo (-65, 0); context. stroke (); context. rotate (-1); context. fillStyle = 'rgba (0, 0,255, 0.5) '; context. save (); // save the context state. Only the settings and transformations of the drawing context are saved, and the context of the drawing context is not saved. fillStyle = 'pink '; context. translate (-100,-100); context. save (); context. fillStyle = 'green'; context. fillRect (220, 10, 50, 50); context. restore (); // return the previously saved settings context. fillRect (280, 10, 50, 50); context. restore (); context. fillRect (340, 10, 50, 50 );}
  • Draw Images

  DrawImage () can also pass in the <canvas> element as the first parameter, indicating to draw the content of the other canvas to the current canvas.

Possible problem: the drawImage () image is not displayed on the canvas, probably because the image has not been loaded when you take the image.

Window. onload = function () {var drawing = document. getElementById ('Drawing '); if (drawing. getContext) {// image var context = drawing. getContext ('2d '); var image = document. images [0]; // parameters are represented in sequence as: image elements, source image x coordinates, y coordinates, target width, and height context. drawImage (image, 0, 0,150,250); // The parameters are represented as follows: image Element, source image x coordinate, y coordinate, source image width, height, target image x coordinate, y coordinate, target image width, height context. drawImage (image, 100,300,500,600, 0, 0, 70, 80 );}};
  • Shadow, gradient, Mode

  

The pattern is the same as the gradient pattern. It starts from the canvas origin (0, 0) and sets the fill style as a pattern object, which only displays duplicate images in a specific area, instead of drawing duplicate images from a certain position.

The first parameter of createPattern () can also be a <video> element or another <canvas> element.

Window. onload = function () {var drawing = document. getElementById ('Drawing '); if (drawing. getContext) {// shadow var context = drawing. getContext ('2d '); context. shadowColor = 'rgba (0, 0, 0, 0.5) '; // shadow color, black context by default. shadowOffsetX = 5; // The Shadow offset in the X axis direction. The default value is 0 context. shadowOffsetY = 5; // The Shadow offset in the Y axis. The default value is 0 context. shadowBlur = 4; // Number of blurred records. The default value is 0 context. fillStyle = 'rgba (0, 0,255, 0.5) '; context. fillRect (10, 10, 50, 50); Context. fillStyle = 'pink '; context. fillRect (30, 30, 50, 50); // gradient var gradient = context. createLinearGradient (100, 10,130,130); // create a linear gradient and return an instance of the CanvasGradient object. Parameters: start point x coordinate, y coordinate, end point x coordinate, and y coordinate gradient. addColorStop (0, 'white'); // specify the color. Parameter: color position (number between 0 and 1, 0 indicates the color of the start, and 1 indicates the color of the end), css color value gradient. addColorStop (1, 'black'); context. fillStyle = gradient; context. fillRect (100, 10, 50, 50); var createLinearGradient = function (context, x, y, width, height) {return context. createLinearGradient (x, y, x + width, y + height) ;}; var gradientNew = createLinearGradient (context, 180, 10, 50, 50); gradientNew. addColorStop (0, 'red'); gradientNew. addColorStop (1, 'green'); context. fillStyle = gradientNew; context. fillRect (180, 10, 50, 50); var gradientRound = context. createRadialGradient (275, 35, 10,275, 35, 30); // radial gradient. parameters: center and radius of the Start circle, center and radius of the end circle, gradientRound. addColorStop (0, 'pink '); gradientRound. addColorStop (1, 'Blue '); context. fillStyle = gradientRound; context. fillRect (250, 10, 50, 50); // pattern, that is, duplicate image, which can be used to fill or stroke the image var image = document. images [0], pattern = context. createPattern (image, 'Repeat-x'); // create a new mode. parameters: image elements, repeat-x, repeat-y, no-repeat) context. fillStyle = pattern; context. fillRect (350, 10,350,350 );}}
  • Use Image Data

GetImageData () can obtain original image data. Parameter: x coordinate, y coordinate, width, and height of the image area to be obtained. The returned object is an ImageData instance, which has three attributes: width, height, and data. Data is an array, saving the image

Each pixel is represented by four elements, namely red, green, blue, and transparency. Therefore, the data of the first pixel is stored in the 0th to 3rd elements of the array.

Note: image data can be obtained only when the canvas is "clean" (that is, the image is not from another domain.

  • Synthesis

  GlobalAlpha: A value between 0 and 1 (including 0 and 1), used to specify transparency. The default value is 0.

GlobalComositionOperation: indicates how a post-drawn image is combined with a pre-drawn image.

  

  

3. WebGL

 WebGL is a 3D context for canvas and is not a W3C standard.

 

This article is being updated ~

 

 

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.