gpt4 book ai didi

javascript - HTML 5/Canvas 多边形绘制工具?

转载 作者:行者123 更新时间:2023-11-30 00:28:40 26 4
gpt4 key购买 nike

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

有人知道像上面示例这样的独立工具吗?

最佳答案

您可以在已绘制到 Canvas 上的图像上绘制笔触。

它非常简单,您甚至不需要附加库。只需使用 native 路径命令!

  • 监听用户的鼠标点击并创建他们的点击点数组

    // 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>

关于javascript - HTML 5/Canvas 多边形绘制工具?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30456562/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com