绘制各种图形步骤
1 开始新路径
beginPath() 开始新路径 绘制矩形和填充矩形可省略此步骤
2 设置路径
moveTo(x,y) 移动起始点到x,y
lineTo(x,y) 绘制目前端点到x,y的直线
arc(x,y,r,startAngle,endAngle,antiClockwise) 绘制圆形或圆弧
fillRect(x,y,width,height) 绘制填满矩形
strokeRect(x,y,width,height) 绘制轮廓矩形(只有边框,不填充颜色)
3 将路径头尾相连
closePath() 关闭路径
4 将路径绘制到canvas绘图区
Stroke() 绘制边框
Fill() 填充图形
绘制直线
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="content-type" content="text/html" />
<title>绘制直线</title>
<script type="text/javascript">
function drawline(){
var canvas = document.getElementById('myCanvas');
var ctx = canvas.getContext('2d');
//开始绘图
ctx.strokeStyle="#ff0066"; //设定边框颜色
ctx.beginPath(); //路径开始
ctx.moveTo(50, 50); //将起始点移到(50,50)
ctx.lineTo(150, 50); //线条终点(150,50)
ctx.lineTo(200, 100); //线条终点(150,50)
ctx.lineTo(350, 100); //线条终点(150,50)
ctx.stroke(); //绘出边框
}
</script>
<style type="text/css">
canvas{border: 1px solid black;}
</style>
</head>
<body>
<input type="button" value="画线" onclick="drawline();"/>
<canvas id="myCanvas" width="400" height="200"></canvas>
</body>
</html>