HTML5 Fast Learning Two Canvas

Source: Internet
Author: User

This article begins by explaining one of the core features of HTML5: Canvas

Canvas lets you dynamically generate and display graphics, charts, images, and animations.

The Canvas API features a lot, and we'll discuss the most common features.

Let's start by creating a canvas to look at.

We add a frame to the canvas, which makes it easier to see.

As you can see, the canvas creates a rectangular area, by default the resulting size is 300*150 pixels.

After adding the canvas to the page, we can control her from the ground by JS.

For example, add pictures, lines, and text, or you can draw in them, or even add advanced animations.

Note

Using canvas as a normal tag, you can change the style by applying CSS, and some CSS properties can be inherited by elements within the canvas.

For example, font styles, which add text within a canvas, are styled by default to be the same as the canvas element itself.

article outline
    • Points
    • Theoretical basis/preconditions
    • Detailed steps
    • Summarize
Key points

Master the important process of using the canvas API

Master the Common canvas API: such as MoveTo, LineTo, Beginpath, Closepath,stroke,fill, etc.

Fully understand the examples

theoretical basis-canvas coordinates

For example, the coordinates in the canvas start from the upper-left corner, the x-axis extends right along the horizontal direction (in pixels), and the y-axis extends vertically.

The top-left corner coordinates (0,0) are the Origin points.

detailed steps-using the HTML5 canvas APIDetection of browser support

We do two things.

    1. We use a script to determine the browser support situation.

      If not supported, you can display the prompt information in a specific location.

      For example, we used a id= "support" div to display the information that prompted the upgrade.

    2. We write an alternate content in the canvas.

      For example, if not supported, the canvas will display the alternate content.

Browser support

Turn IE into IE7 mode test does not support the situation:

draw a diagonal line with canvas

Make some changes to the example above

Draw a diagonal line in the canvas

According to the above JS code, the use of the canvas API to summarize the important process .

    1. Gets the canvas object access based on the canvas ID value, and then defines a context variable that invokes the GetContext method of the canvas object.
    2. Perform the action based on this context (here is a diagonal line)
    3. Complete the drawing of the line through Context.stroke ().

Note

There is a hole here. I originally set the canvas to be long and wide in the style. Such as.

Why the problem occurred:

Canvas's width and height are the actual widths and heights of the canvas, and the drawing is drawn on top of the canvas.

The width and height of the canvas's style are the height and width at which the canvas is rendered in the browser.

Therefore, you need to be aware that setting the width is outside.

Use Transformations (transformation) to draw diagonal lines

Here's another way to draw an image on a canvas: Using Transformations (transformation).

Transformation is the best way to implement complex canvas operations (it seems to be a bit more complicated to draw diagonally on a single top)

Understanding Transformations (transformation):

Think of it as a layer of correction between a developer-issued instruction and the canvas display result (modification layer)

note that the remediation layer always exists regardless of whether transformations are used in development.

The results of each drawing operation are corrected by the correction layer before being displayed on the canvas.

While this adds additional complexity, it adds more powerful functionality to the drawing system.

Note

Not calling a transform function in your code does not mean that you can improve the performance of your canvas.

When the canvas executes, the transformation is implicitly called by the rendering engine, regardless of whether the developer is calling directly.

An important piece of advice for reusable code:

The general drawing should begin with the origin, apply transformations (zoom, pan, rotate, etc.), and then constantly modify the code until the desired effect is reached.

Example

The result of this code is identical to the above.

Notice the difference between the two types of code:

For the second way, translate (70,140) represents moving the origin to the (70,140) position.

In other words, all of the next operations are done relative to (70,140) this position.

The first case is (70,140) à (140,70),

The second case is (0,0) à (70,140) à (70,-70)

The second case (70,-70) is relative to the new origin (70,140) point, relative to the beginning of the Origin coordinate is (70+70,-70+140), it is easy to see the results of the two cases are equivalent, understand it?

Let's have a look.

Let's summarize the above actions:

    1. Gets the canvas object access based on the canvas ID value, and then defines a context variable that invokes the GetContext method of the canvas object.
    2. Save the context that has not yet been modified so that you can revert to the original state (via the Restore function later) even if the drawing and transformation operations are done
    3. Move the origin through the translate, as explained above.
    4. Perform line-drawing actions based on a moving context
    5. Complete the drawing of the line through Context.stroke ().
    6. Finally, restore the context to its original state so that subsequent canvas operations will not be affected by the translation operation just now.
painting a tree

Now learn a slightly more complicated graph.

A diagonal line drawn above is considered a simple path.

The path can actually be complex: multiple lines, curved segments, or even sub-paths.

If you want to draw any shape on the canvas, you need to focus on the path API

By convention, no matter what kind of drawing you start, the first thing you need to call is Beginpath, and for canvas, the most useful thing for the Beginpath function is that the canvas needs to calculate the internal and external extents of the graph to complete subsequent strokes and fills.

The path tracks the current coordinates, and the default value is the Origin point.

After calling Beginpath, you can use the various methods of the context to draw the desired shape.

A few simple context path functions have been used so far.

MoveTo (x, y)

LineTo (x, y)

The difference between the above two functions is that moveto is like lifting a brush and moving it to a new position;

Instead, LineTo tells Canvas to draw a line from the old coordinates on the paper to the new coordinates with a brush.

Note that no matter which one is called, the graph is not actually drawn because we have not yet called the stroke or fill function.

Currently we just define the location of the path so that it can be used when drawing later.

Also introduce a path function Closepath, this function and LineTo very much like, the only difference is that the starting coordinates of the path automatically as the target coordinates.

Clothpath also notifies canvas that the currently drawn drawing is completely closed or has a completely closed area, which is useful for future fills and strokes.

At this point, you can continue to create additional sub-paths in the existing path, or call Beginpath at any time to redraw the new path and completely clear all previous paths.

1. Draw the canopy

function for drawing canopy

To visualize the trend of the line, I drew a sketch from the start point to the vertex, as follows

Functions for drawing trees on canvas:

The final result is as follows

Below we do some landscaping on the canopy, add the following code before the stroke

into a thicker, smoother brown line.

Further beautification, fill the closed path with Green inside.

Notice that the border on the right side is also thinner.

When we fill the first stroke, we fill half the border.

If you do not fill the border, you need to use the first fill and then the stroke, as follows.

2. Use FillRect to draw the trunk (fill rectangular area)

Let's change the value of the translate to give out the position of the tree trunk.

Context.translate (130,150);

Draw the trunk by FillRect (x, y, width, height).

Note that this paragraph will be in the Context.restore (), before the position of the painting is wrong.

Final Result:

Note

FillRect (X,y,width,height)

Summary

You can initially see the power of canvas, without the use of third-party technology to draw.

Of course, the current painting is relatively simple, the next article will be on the basis of this tree to add other elements and special effects, complete a rain animation effect of the Boulevard map.

OK, today is here, welcome everyone to comment, let the next article better:)

HTML5 Fast Learning Two Canvas

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.