如下代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<canvas id="canvas" style="border:1px solid #aaa;display:block;margin:50px auto;">
当前浏览器不支持Canvas,请更换浏览器后再试
</canvas>
<script>
window.onload = function(){
let canvas = document.getElementById("canvas");
canvas.width = 800;
canvas.height = 800;
let context = canvas.getContext("2d");
context.lineWidth = 10;
context.beginPath();
context.moveTo(100, 200);
context.lineTo(300, 400);
context.lineTo(100, 600);
context.strokeStyle = "red";
context.closePath();
context.stroke();
}
</script>
</body>
</html>
运行截图如下:
修改代码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<canvas id="canvas" style="border:1px solid #aaa;display:block;margin:50px auto;">
当前浏览器不支持Canvas,请更换浏览器后再试
</canvas>
<script>
window.onload = function(){
let canvas = document.getElementById("canvas");
canvas.width = 800;
canvas.height = 800;
let context = canvas.getContext("2d");
context.lineWidth = 10;
context.beginPath();
context.moveTo(100, 200);
context.lineTo(300, 400);
context.lineTo(100, 600);
context.fillStyle = "red";
context.closePath();
context.fill();
}
</script>
</body>
</html>
运行截图如下:
如上例子,closePath会让多边形封口。