The main properties and methods of the CanvasRenderingContext2D object required to draw polygons using HTML5 Canvas (those with "()" are methods) are as follows:
属性或方法 |
基本描述 |
strokeStyle |
用于设置画笔绘制路径的颜色、渐变和模式。该属性的值可以是一个表示css颜色值的字符串。如果你的绘制需求比较复杂,该属性的值还可以是一个CanvasGradient 对象或者CanvasPattern 对象 |
globalAlpha |
定义绘制内容的透明度,取值在0.0(完全透明)和1.0(完全不透明)之间,默认值为1.0。 |
lineWidth |
定义绘制线条的宽度。默认值是1.0,并且这个属性必须大于0.0。较宽的线条在路径上居中,每边各有线条宽的一半。 |
lineCap |
指定线条两端的线帽如何绘制。合法的值是 butt、round和square。默认值是"butt"。 |
beginPath() |
开始一个新的绘制路径。每次绘制新的路径之前记得调用该方法。 |
moveTo(int x, int y) |
定义一个新的绘制路径的起点坐标 |
lineTo(int x, int y) |
定义一个绘制路径的中间点坐标 |
stroke(int x, int y) |
沿着绘制路径的坐标点顺序绘制直线 |
closePath() |
如果当前的绘制路径是打开的,则闭合该绘制路径。 |
Draw a triangle
JavaScript CodeCopy content to clipboard
-
-
-
-
"UTF-8">
-
HTML5 Canvas Drawing Triangle Getting Started Example
-
-
-
-
-
-
Your browser does not support the canvas tag.
-
-
-
-
-
-
The corresponding display effect is as follows:
Drawing rectangles
The reason why Canvas drawing rectangles are mentioned separately is because the Canvas brush tool-CanvasRenderingContext2D object provides a dedicated method for drawing rectangles.
XML/HTML CodeCopy content to clipboard
-
>
-
<html>
-
<head>
-
<meta charset="UTF- 8">
-
<title>HTML5 Canvas Drawing Rectangle Getting Started Example title>
-
head>
-
<body>
-
-
-
<canvas id="myCanvas" width="400px" height="300px" style="border: 1px solid red;">
-
Your browser does not support the canvas tag.
-
canvas>
-
-
<script type="text/ javascript">
-
//Get the Canvas object (canvas)
-
var canvas = document.getElementById("myCanvas");
-
//Simply detect whether the current browser supports the Canvas object to avoid prompting syntax errors in some browsers that do not support html5
-
if(canvas.getContext){
-
//Get the corresponding CanvasRenderingContext2D object (brush)
-
var ctx = canvas.getContext("2d");
-
-
//Start a new drawing path
-
ctx.beginPath();
-
//Set the line color to blue
-
ctx.strokeStyle = "blue";
-
//Using the coordinate point (10,10) in the canvas as the drawing starting point, draw a rectangle with a width of 80px and a height of 50px
-
ctx.rect(10, 10, 80, 50);
-
//Draw a straight line according to the specified path
-
ctx.stroke();
-
//Close drawing path
-
ctx.closePath();
-
}
-
script>
-
body>
-
html>
The corresponding rectangular effect is displayed as follows: