官术网_书友最值得收藏!

How it works...

As you can see from the preceding code, we need to wait for the page to load before trying to access the canvas tag by its ID. We can accomplish this with the window.onload initializer. Once the page loads, we can access the canvas DOM element with document.getElementById() and we can define a 2D canvas context by passing 2d into the getContext() method of the canvas object. As we will see in the last two chapters, we can also define 3D contexts by passing in other contexts such as webgl, experimental-webgl, and others.

When drawing a particular element, such as a path, sub path, or shape, it's important to understand that styles can be set at any time, either before or after the element is drawn, but that the style must be applied immediately after the element is drawn for it to take effect, We can set the width of our line with the lineWidth property, and we can set the line color with the strokeStyle property. Think of this behavior like the steps that we would take if we were to draw something onto a piece of paper. Before we started to draw, we would choose a colored marker (strokeStyle) with a certain tip thickness (lineWidth).

Now that we have our marker in hand, so to speak, we can position it onto the canvas using the moveTo() method:

context.moveTo(x,y);

Think of the canvas context as a drawing cursor. The moveTo() method creates a new sub path for the given point. The coordinates in the top-left corner of the canvas are (0,0), and the coordinates in the bottom-right corner are (canvas width, canvas height).

Once we have positioned our drawing cursor, we can draw the line using the lineTo() method by defining the coordinates of the line's end point:

context.lineTo(x,y);

Finally, to make the line visible, we can use the stroke() method. Unless, otherwise specified, the default stroke color is black.

To summarize, here's the typical drawing procedure we should follow when drawing lines with the HTML5 canvas API:

  1. Style your line (like choosing a colored marker with a specific tip thickness).
  2. Position the canvas context using moveTo() (like placing the marker onto a piece of paper).
  3. Draw the line with lineTo().
  4. Make the line visible using stroke().
主站蜘蛛池模板: 庆安县| 迁安市| 和田市| 枝江市| 广昌县| 于都县| 大港区| 富宁县| 浙江省| 普兰县| 册亨县| 林周县| 灵石县| 平凉市| 巫山县| 合江县| 苍溪县| 洪洞县| 安庆市| 孟连| 新沂市| 洛浦县| 沈丘县| 修文县| 新龙县| 连云港市| 元阳县| 连平县| 峨眉山市| 合作市| 裕民县| 潼关县| 雅安市| 镇远县| 淅川县| 周口市| 民勤县| 平江县| 平和县| 阜城县| 浑源县|