【发布时间】:2022-12-10 06:33:45
【问题描述】:
我从数据库中获取了一组多边形。每个形状可以是三角形、矩形、正方形或任何多边形。
我想在每个多边形的中心绘制文本。字体大小必须根据每个多边形的大小是动态的。文本颜色应与线条颜色匹配。
来自数据库的示例:
这是我的代码:
var polygons = [
{
text: "ROI", color: "#00ff00",
jointLength: 5, lineWidth: 3,
X: [890, 893, 409, 21, 27], Y: [658, 205, 199, 556, 659],
}, {
text: "Lane 3", color: "#ff0000",
jointLength: 4, lineWidth: 3,
X: [915, 911, 643, 879], Y: [5, 682, 683, 2],
}, {
text: "Lane 4", color: "#ff0000",
jointLength: 4, lineWidth: 3,
X: [888, 656, 170, 701], Y: [2, 680, 682, 1],
}, {
text: "Lane 5", color: "#ff0000",
jointLength: 5, lineWidth: 3,
X: [712, 182, 4, 4, 590], Y: [1, 681, 682, 532, 1],
}, {
text: "Speed", color: "#0000ff",
jointLength: 4, lineWidth: 3,
X: [290, 911, 873, 5], Y: [367, 357, 668, 664],
}
];
polygons.forEach((polygon) => {
const ctx = document.getElementById("canvas").getContext("2d");
ctx.strokeStyle = polygon.color;
ctx.lineWidth = polygon.lineWidth;
ctx.beginPath();
ctx.moveTo(polygon.X[0], polygon.Y[0]);
for (let i = 1; i < polygon.jointLength; i++) {
ctx.lineTo(polygon.X[i], polygon.Y[i]);
}
ctx.closePath();
ctx.stroke();
});
<canvas id="canvas" width=999 height=999></canvas>
【问题讨论】:
-
你能和我们分享一下多边形数组吗?
-
哪个center?
-
哪个中心,Circumscribed 或 Centroid 并不重要
标签: javascript canvas html5-canvas