使用closePath()闭合图形
首先我们用最普通的方法绘制一个矩形。
JavaScript Code复制内容到剪贴板
- nbsp;html>
- "en">
-
-
"UTF-8">
-
-
-
- nbsp;html>
- "zh">
-
-
"UTF-8">
- 绘制矩形
-
-
"canvas-warp">
-
- 你的浏览器居然不支持Canvas?!赶快换一个吧!!
-
-
- <script> </script>
-
window.onload = function(){
-
var canvas = document.getElementById("canvas");
- canvas.width = 800;
- canvas.height = 600;
-
var context = canvas.getContext("2d");
-
- context.beginPath();
- context.moveTo(150,50);
- context.lineTo(650,50);
- context.lineTo(650,550);
- context.lineTo(150,550);
-
context.lineTo(150,50);
- context.lineWidth = 5;
-
context.strokeStyle = "black";
- context.stroke();
-
- }
-
-
-
-
-
运行结果:
乍一看没啥问题,但是视力好的童鞋已经发现了,最后一笔闭合的时候有问题,导致左上角有一个缺口。这种情况是设置了lineWidth导致的。如果默认1笔触的话,是没有问题的。但是笔触越大,线条越宽,这种缺口就越明显。那么这种情况该怎么避免呢?
标题已经剧透了,使用clothPath()闭合图形。
JavaScript Code复制内容到剪贴板
- nbsp;html>
- "zh">
-
-
"UTF-8">
- 绘制矩形
-
-
"canvas-warp">
-
- 你的浏览器居然不支持Canvas?!赶快换一个吧!!
-
-
- <script> </script>
-
window.onload = function(){
-
var canvas = document.getElementById("canvas");
- canvas.width = 800;
- canvas.height = 600;
-
var context = canvas.getContext("2d");
-
- context.beginPath();
- context.moveTo(150,50);
- context.lineTo(650,50);
- context.lineTo(650,550);
- context.lineTo(150,550);
-
context.lineTo(150,50);
-
context.closePath();
-
- context.lineWidth = 5;
-
context.strokeStyle = "black";
- context.stroke();
-
- }
-
-
-