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

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().
主站蜘蛛池模板: 湘西| 云阳县| 阳西县| 普兰店市| 泰和县| 双城市| 静宁县| 揭东县| 海宁市| 铁岭市| 年辖:市辖区| 尼勒克县| 察隅县| 巴里| 威宁| 陵水| 姜堰市| 甘泉县| 乌海市| 石屏县| 定安县| 金堂县| 镇巴县| 扎鲁特旗| 来凤县| 凤冈县| 景东| 天镇县| 浙江省| 福清市| 荆州市| 红原县| 札达县| 同心县| 辽宁省| 清新县| 康乐县| 霍城县| 苏尼特左旗| 滨州市| 平和县|