用线条绘制图形
1. 前言
本小节我们学习如何用线条绘制矩形和三角形。
2. 线条绘制矩形
先看整体案例,请在firefox浏览器中查看本案例。
<!DOCTYPE html>
<html>
<head>
<Meta charset="utf-8">
<title>网Wiki</title>
<style>
#imooc{
border:px solid #ccc;
}
</style>
</head>
<body>
<canvas id="imooc">您的浏览器不支持 HTML5 canvas 标签</canvas>
<script>
const canvas = document.getElementById('imooc');
const ctx = canvas.getContext('2d');
ctx.moveto(,);
ctx.lineto(,);
ctx.lineto(,);
ctx.lineto(,);
ctx.lineto(,);
ctx.strokeStyle="blue"
ctx.linewidth=
ctx.stroke();
</script>
</body>
</html>
如果你使用的是 firefox 浏览器,你会看到这样的效果:
chrome浏览器下的效果是这样的:
closePath() 方法用于创建从笔触当前点到开始点的路径。
先看整体案例,依然是在 firefox 浏览器下查看效果。
<!DOCTYPE html>
<html>
<head>
<Meta charset="utf-8">
<title>网Wiki</title>
<style>
#imooc{
border:px solid #ccc;
}
</style>
</head>
<body>
<canvas id="imooc">您的浏览器不支持 HTML5 canvas 标签</canvas>
<script>
const canvas = document.getElementById('imooc');
const ctx = canvas.getContext('2d');
ctx.moveto(,);
ctx.lineto(,);
ctx.lineto(,);
ctx.lineto(,);
// ctx.lineto(10,10); //去掉了这一行
ctx.closePath(); //最后一笔路径使用了closePath方法
ctx.strokeStyle="blue"
ctx.linewidth=
ctx.stroke();
</script>
</body>
</html>
运行结果:
3. 线条绘制三角形
我们利用 closePath
再绘制一个三角形,先看整体案例。
<!DOCTYPE html>
<html>
<head>
<Meta charset="utf-8">
<title>网Wiki</title>
<style>
#imooc{
border:px solid #ccc;
}
</style>
</head>
<body>
<canvas id="imooc">您的浏览器不支持 HTML5 canvas 标签</canvas>
<script>
const canvas = document.getElementById('imooc');
const ctx = canvas.getContext('2d');
ctx.moveto(,);
ctx.lineto(,);
ctx.lineto(,);
ctx.closePath(); //最后一笔路径使用了closePath方法
ctx.strokeStyle="blue"
ctx.linewidth=
ctx.stroke();
</script>
</body>
</html>
运行结果:
可以看到左上角闭合地非常完美。
4. 路径方法整理
4.1 closePath(x, y)
closePath()
方法主要作用是创建从笔触当前点到 moveto
的点的路径,它的优势在于会自动处理接口闭合的问题。同学们可以用前面学过的知识绘制一个三角形,深刻体会一下 closePath()
的不同之处。