使用canvas可以根据点的集合来绘制不规则的多边形,绘制代码如下
const canvas = document.querySelector('#canvas')
const c2 = canvas.getContext('2d')
// 设置属性控制图形的外观
c2.fillStyle = 'rgba(255, 255, 255, 0)'
// 外部使用外边框
c2.strokeStyle = '#ff0000'
// 线宽
c2.lineWidth = 2
c2.beginPath()
for (let i = 0; i < pointList.length; i++) {
const data = pointList[i]
if (i === 0) {
c2.moveTo(data.x, data.y)
}else {
c2.lineTo(data.x , data.y)
}
}
c2.closePath()
c2.fill()
c2.stroke()
完整代码如下
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<canvas id="canvas" width="400" height="400"></canvas>
<script>
drawPolygon()
function drawPolygon() {
const pointList = [
{
"x": 45.031,
"y": 246.894
},
{
"x": 49.689,
"y": 357.143
},
{
"x": 116.46,
"y": 361.801
},
{
"x": 234.472,
"y": 352.484
},
{
"x": 295.031,
"y": 336.957
},
{
"x": 347.826,
"y": 263.975
},
{
"x": 350.932,
"y": 204.969
},
{
"x": 291.925,
"y": 184.783
}
]
const canvas = document.querySelector('#canvas')
const c2 = canvas.getContext('2d')
// 设置属性控制图形的外观
c2.fillStyle = 'rgba(255, 255, 255, 0)'
// 外部使用外边框
c2.strokeStyle = '#ff0000'
// 线宽
c2.lineWidth = 2
c2.beginPath()
for (let i = 0; i < pointList.length; i++) {
const data = pointList[i]
if (i === 0) {
c2.moveTo(data.x, data.y)
}else {
c2.lineTo(data.x , data.y)
}
}
c2.closePath()
c2.fill()
c2.stroke()
}
</script>
</body>
</html>
预览效果如下
也可以结合canvas绘制文本,例如在多边形上添加坐标点,代码如下
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<canvas id="canvas" width="800" height="800"></canvas>
<script>
drawPolygon()
function drawPolygon() {
const pointList = [
{
"x": 45.031,
"y": 246.894
},
{
"x": 49.689,
"y": 357.143
},
{
"x": 116.46,
"y": 361.801
},
{
"x": 234.472,
"y": 352.484
},
{
"x": 295.031,
"y": 336.957
},
{
"x": 347.826,
"y": 263.975
},
{
"x": 350.932,
"y": 204.969
},
{
"x": 291.925,
"y": 184.783
}
]
const canvas = document.querySelector('#canvas')
const c2 = canvas.getContext('2d')
// 外部使用外边框
c2.strokeStyle = '#ff0000'
// 线宽
c2.lineWidth = 2
c2.beginPath()
for (let i = 0; i < pointList.length; i++) {
const data = pointList[i]
if (i === 0) {
c2.moveTo(data.x, data.y)
}else {
c2.lineTo(data.x , data.y)
}
c2.fillStyle = '#000000'// 设置填充画笔颜色,即字体颜色
c2.font = `14px serif` // 设置字体大小
c2.fillText(`(${data.x},${data.y})`, data.x, data.y) // 绘制 "实心" 文字;
}
// 设置属性控制图形的外观
c2.fillStyle = 'rgba(255, 255, 255, 0)'
c2.closePath()
c2.fill()
c2.stroke()
}
</script>
</body>
</html>
预览效果如下