<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>绘制路径</title>
<style type="text/css">
*{
margin: 0;
padding: 0;
}
html,body{
background-color: #bfa;
}
#test{
background-color: pink;
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
margin: auto;
}
</style>
</head>
<body>
<canvas id="test" width="300" height="300">
<span>当前浏览器版本不支持,请升级至IE-9或更换其他浏览器</span>
</canvas>
<script type="text/javascript">
//图形的基本元素是路径,路径通过不同颜色、宽度的线段或曲线相连形成
window.onload = function(){
var canvas = document.querySelector('#test');
if(canvas.getContext){
var ctx = canvas.getContext('2d');
ctx.fillStyle = 'deeppink';
ctx.strokeStyle = 'black';
ctx.lineWidth = 5
//1. 创建路径起始点
ctx.moveTo(100,100);
//2. 使用画图命令画出路径
ctx.lineTo(100,200);
ctx.lineTo(200,200);
ctx.lineTo(200,100);
//3. 封闭路径
ctx.closePath(); //自动封闭路径
//ctx.lineTo(50,50) 回到起点
//4. 路径生成,可以通过描边或填充路径区域渲染图形
ctx.stroke() //描边 不会自动调用
ctx.fill() //填充 自动调用closePath来封闭路径
//每次调用之前,为避免对前面的路径产生影响,需要清空路径
ctx.beginPath(); //清空路径容器
ctx.moveTo(10,10)
ctx.lineTo(10,50);
ctx.lineTo(50,50);
ctx.closePath();
ctx.stroke();
ctx.fill();
}
}
</script>
</body>
</html>
效果图: