首页 > 解决方案 > 难以在画布上绘制多个多边形。请看一看

问题描述

我想在背景为图像的画布上绘制多个多边形。我从 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 = [];
}

我错过了什么?谢谢!

标签: javascripthtmlcanvaspolygon

解决方案


推荐阅读