javascript - 难以在画布上绘制多个多边形。请看一看
问题描述
我想在背景为图像的画布上绘制多个多边形。我从 json 文件加载多边形点并将其存储到数组中,然后遍历数组以绘制多边形。但到目前为止,无论如何都只绘制了第一个多边形,在这个问题上花了三天时间。请看一下并帮助我继续我的项目的下一步。谢谢你!
例如,下面的 json:
var jsonf = {
"shapes": [
{
"line_color": [0, 255, 255, 255],
"points": [[217, 44], [210, 43], [208, 35], [209, 28], [215, 25], [219, 31], [219, 39]],
"fill_color": [0, 0, 0, 128],
"label": "Haemorrhages-Resized"
},
{
"line_color": [0, 255, 255, 255],
"points": [[384, 60], [378, 56], [378, 48], [384, 45], [388, 51], [385, 58]],
"fill_color": [0, 0, 0, 128],
"label": "Haemorrhages-Resized"
}
]
}
这个 json 可能有很多“形状”条目,为了简洁起见,我在这里只显示其中两个!
现在,从 json 中提取点并将其存储到 'points' 数组中并使用它来绘制多边形,代码如下:
var points = [];
var canvas = document.getElementById("myCanvas");
var cw=canvas.width;
var ch=canvas.height;
var ctx = canvas.getContext("2d");
ctx.clearRect(0,0,cw,ch);
for (var i=0; i<jsonf.shapes.length; i++) {
for (var j=0; j<jsonf.shapes[i].points.length; j++) {
points.push({x: jsonf.shapes[i].points[j][0], y: jsonf.shapes[i].points[j][1]});
}
ctx.fillStyle = 'rgba(0, 0, 0, 128)';
ctx.strokeStyle = 'rgba(0, 255, 255, 255)';
ctx.lineWidth= 1;
ctx.beginPath();
ctx.moveTo(points[0].x, points[0].y);
for(var index=1; index<points.length; index++) {
ctx.lineTo(points[index].x, points[index].y);
}
ctx.closePath();
ctx.fill();
ctx.stroke();
points = [];
}
我错过了什么?谢谢!
解决方案
推荐阅读
- numpy - 将具有多个维度的 numpy 数组转换为具有嵌套 numpy 数组的二维数组
- input - 用户输入,用户输入数据到列表中
- elasticsearch - elasticsearch edgengram copy_to 字段部分搜索不起作用
- javascript - 引导复选框无法正常工作
- ejabberd - 如何将居住者/用户添加到 MUC 房间?
- python - tkinter 小部件实现
- firebase - 在 Angular 单元测试中使用 firestore.Timestamp.now()
- javascript - 为什么 Date.UTC 会返回一串毫秒
- wordpress - 如何将 Img 帖子缩略图设置为整个帖子的背景
- python-3.x - 在 tf.layers 中使用 float64