HTML 5 / Canvas Polygon Draw Tool?

时间:2015-05-26 10:56:59

标签: javascript canvas

对于一个upcomming项目,我们正在研究使用HTML绘制形状的可能性。 Google地图(http://googlegeodevelopers.blogspot.nl/2011/11/make-your-map-interactive-with-shape.html)中使用的绘图库非常适合使用。已经在Mapbox(https://www.mapbox.com/guides/adding-features-and-data/)上找到类似的东西,但它们都是基于地图的,我们只需要一张空白的工作表来绘制一些形状......

任何人都知道上面例子中的独立工具吗?

1 个答案:

答案 0 :(得分:1)

您可以在绘制到画布上的图像上绘制笔划。

这很简单,你甚至不需要一个附加库。只需使用本机Path命令!

  • 倾听用户的鼠标点击并创建其点击点数组

    // some test points
    // In production, these would be gathered through user mouseclicks
    var points=[]
    points.push({x:100,y:300});
    points.push({x:150,y:250});
    points.push({x:235,y:225});
    points.push({x:190,y:300});
    points.push({x:80,y:340});
    
  • 这会绘制折线:

    function drawPolyline(points){
        for(var i=0;i<points.length;i++){
            ctx.beginPath();
            ctx.moveTo(points[0].x,points[0].y);
            for(var i=1;i<points.length;i++){
                ctx.lineTo(points[i].x,points[i].y);
            }
            ctx.strokeStyle='blue';
            ctx.lineWidth=5;
            ctx.stroke();    
        }
    }
    
  • 这会画一个圆圈来突出航点:

    function drawWaypoints(points){
        for(var i=0;i<points.length;i++){
            ctx.beginPath();
            ctx.arc(points[i].x,points[i].y,4,0,Math.PI*2);
            ctx.closePath();
            ctx.strokeStyle='black';
            ctx.lineWidth=1;
            ctx.stroke();
            ctx.fillStyle='white';
            ctx.fill();
        }
    }
    

示例代码和演示:

enter image description here

var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var cw=canvas.width;
var ch=canvas.height;

// some test points
// In production, these would be gathered through user mouseclicks
var points=[]
points.push({x:100,y:300});
points.push({x:150,y:250});
points.push({x:235,y:225});
points.push({x:190,y:300});
points.push({x:80,y:340});

var img=new Image();
img.onload=start;
img.src="https://dl.dropboxusercontent.com/u/139992952/multple/googlemap1.png";
function start(){
  canvas.width=img.width;
  canvas.height=img.height;
  ctx.drawImage(img,0,0);
  drawPolyline(points);
  drawWaypoints(points);
}

function drawPolyline(points){
  for(var i=0;i<points.length;i++){
    ctx.beginPath();
    ctx.moveTo(points[0].x,points[0].y);
    for(var i=1;i<points.length;i++){
      ctx.lineTo(points[i].x,points[i].y);
    }
    ctx.strokeStyle='blue';
    ctx.lineWidth=5;
    ctx.stroke();    
  }
}

function drawWaypoints(points){
  for(var i=0;i<points.length;i++){
    ctx.beginPath();
    ctx.arc(points[i].x,points[i].y,4,0,Math.PI*2);
    ctx.closePath();
    ctx.strokeStyle='black';
    ctx.lineWidth=1;
    ctx.stroke();
    ctx.fillStyle='white';
    ctx.fill();
  }
}
body{ background-color: ivory; }
#canvas{border:1px solid red;}
<canvas id="canvas" width=300 height=300></canvas>