SVG 地图配置,配置动态连线

下面是我在开发过程中的技术验证demo,核心代码也是在网上找的
分享下我在应用中遇到的几个坑
1、绘制区块添加事件,添加不上,设置z-index不生效,经过查找发现 需要配置 pointer-events:visiblePainted; 属性;
2、动态加载地图底图时,会出现绘制区域坐标偏移情况,需要配置图片预加载 

$(".dirdragme").on("load", function () {
$("containerDir").width($(".dirdragme").width());
$("containerDir").height($(".dirdragme").height());

svger.setAttribute("width", $(".dirdragme").width());
svger.setAttribute("height", $(".dirdragme").height());
svger.setAttribute("viewBox", "0 0 " + $(".dirdragme").width() + " " + $(".dirdragme").height());
});

下面示例demo复制即可使用;

 
<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>获取坐标点位置,并连接点</title>
        <style>
        *{margin:0 ;padding:0;}
        .container{width:800px;height:600px;position: relative; overflow: auto;}
        .container{border:1px solid #ccc;cursor: pointer;position: relative;}
        .dot{width:10px;height:10px;border-radius:50%;position:absolute;background:#0078B6;margin-top:-5px;margin-left:-5px;}
        .initdot{top:0;left:0;}
        svg{
            position: absolute;
            left: 0;
            top: 0;
            margin: 0 auto;
            display: block;
            bottom: 0;
            right: 0;
        }
        </style>
    </head>
    <body >
        <div style="overflow-x:scroll;overflow-y:scroll;">
            <div class="container" id="container" onmousedown="whichButton(event)">
                <!-- <div class="dot initdot"></div> -->
                <img src="sd.jpg" id="image" class="dragme" alt="image for resizing" style="z-index: -1;position: relative;margin:0 auto;display: block;">
            </div>
        </div>
    </body>
</html>
<script src="jquery.min.js" type="text/javascript"></script>
<script>
    var arr=[];
    var mark=0;
    var firstSk;
    var endSk;
    var arrsk=[];
    var points;
    var container=document.getElementById("container");
    var img=document.getElementById("image");
    //var txt=get();
    //var svgcontainer=document.getElementById("svgcontainer");
    //创建svg 注:动态创建svg ie8及以下不支持该方法
    var svgns="http://www.w3.org/2000/svg";
    var svger=document.createElementNS(svgns,"svg");
    svger.setAttribute("width",$(".dragme").width());
    svger.setAttribute("height",$(".dragme").height());
    svger.setAttribute("viewBox","0 0 "+$(".dragme").width()+" "+$(".dragme").height());
    container.appendChild(svger);
     
    svger.onclick=function(e){
        if(mark==0)
        {
            var e=e||window.event;//事件对象
            //获取点击地鼠标位置
            var mousePosition=mousePos(e);
            //新增点
            creatdot(mousePosition.x,mousePosition.y);
            arr.push(mousePosition.x+" "+mousePosition.y);
            //points=mousePosition.x+","+mousePosition.y
            //连接点
            var dots=$("div[class='dot']");
            if(dots.length>1)
            {
                points+=" "+(parseInt(mousePosition.x)-parseInt(container.offsetLeft)).toString()+","+(parseInt(mousePosition.y)-parseInt(container.offsetTop)).toString();
                linedot(dots[dots.length-2],dots[dots.length-1]);
            }
            else{
                points=(parseInt(mousePosition.x)-parseInt(container.offsetLeft)).toString()+","+(parseInt(mousePosition.y)-parseInt(container.offsetTop)).toString();
            }
        }
    }
     
    //位置像素 数值化
    function intpixel(str){
        return str.substring(0,str.length-2)*1;
    }
     
    //获取鼠标坐标
    function mousePos(e){
        if(e.pageX){
            //IE9及以上支持pageX属性 相对文档
            return {x:e.pageX,y:e.pageY}
        }else{
            return {x:e.clientX+document.body.scrollLeft-document.body.clientLeft,
                    y:e.clientY+document.body.scrollTop-document.body.clientTop}
        }
    }
    //新增点
    function creatdot(posX,posY){
        //相对container坐标
        var newposX=posX-container.offsetLeft;
        var newposY=posY-container.offsetTop;
        var dot=document.createElement("div");
        dot.setAttribute("class","dot");
        //定位
        dot.style.left=newposX+"px";
        dot.style.top=newposY+"px";
        container.appendChild(dot);
    }
    //连接点
    function linedot(dot1,dot2){
        // clearTimeout(timepath);
        var imgOffleft=img.offsetLeft;
        var imgOffTop=img.offsetTop;
        var dot1x=(parseInt(dot1.style.left)-imgOffleft).toString()+"px";
        var dot1y=(parseInt(dot1.style.top)-imgOffTop).toString()+"px";

 

        var dot2x=(parseInt(dot2.style.left)-imgOffleft).toString()+"px";
        var dot2y=(parseInt(dot2.style.top)-imgOffTop).toString()+"px";

 

        var start={x:intpixel(dot1x),y:intpixel(dot1y)};
        var end={x:intpixel(dot2x),y:intpixel(dot2y)};
        var current={x:start.x,y:start.y};
        //创建直线
        var line=document.createElementNS(svgns,"line");
        line.setAttribute("x1",dot1x);
        line.setAttribute("y1",dot1y);
        line.setAttribute("x2",dot1x);
        line.setAttribute("y2",dot1y);
        line.setAttribute("stroke","red");
        line.setAttribute("fill","none");
        svger.appendChild(line);
        //角度
        var tangle={
                        sin:(end.y-start.y)/Math.sqrt((end.y-start.y)*(end.y-start.y)+(end.x-start.x)*(end.x-start.x)),
                        cos:(end.x-start.x)/Math.sqrt((end.y-start.y)*(end.y-start.y)+(end.x-start.x)*(end.x-start.x))
                        };
        //动画
        var step=function(){
            //定义每帧移动位移大小为10
            if(Math.abs(current.x-end.x)<10&&Math.abs(current.y-end.y)<10){
                current.x=end.x;
                current.y=end.y;
            }else{
                current.x+=10*tangle.cos;
                current.y+=10*tangle.sin;
                var timepath=setTimeout(step,17);//浏览器重绘速度为60帧每秒
            }
            line.setAttribute("x2",current.x+"px");
            line.setAttribute("y2",current.y+"px");
        }
        step();
    }
        function whichButton(event) {
            var btnNum = event.button;
            if(btnNum==2){
                mark=1;
                alert(arrsk[0]+"   "+arrsk[arrsk.length-1]);

 

                // 添加多线段
                var polyline= document.createElementNS(svgns, 'polyline');
                polyline.setAttribute("points",points);
                polyline.setAttribute("font-size", "14");
                polyline.setAttribute('style', 'fill:none;stroke:red;stroke-width:1;pointer-events:visiblePainted;');
                polyline.setAttribute('marker-end', 'url(#markerArrow)');
                svger.appendChild(polyline);
                $(".dot").remove();
                $("line").remove();
                alert(points);
                points=""
                mark=0;
            }
            // else{
            //     mark=0
            // }
        }
       
        QA9
        0.
        
        var defs=document.createElementNS(svgns,"defs");
        defs.innerHTML=`<marker id="markerArrow" markerWidth="12" markerHeight="12" refX="6" refY="6" viewBox="0 0 12 12" orient="auto" style="fill: red;"><path id="SvgjsPath1008" d="M2,2 L2,11 L10,6 L2,2" style="fill: red;"></path></marker>`;
        svger.appendChild(defs);

 

        var text=document.createElementNS(svgns,"text");
        text.setAttribute("x","151");
        text.setAttribute("y","436");
        text.setAttribute("fill","red");
        text.setAttribute("sitekey","P00001");
        //text.setAttribute("onclick","click('P00001')");
        //text.html("sdfsdfsdff");
        text.addEventListener("click", function() {
            firstSk=$(this).attr("sitekey");
            arrsk.push($(this).attr("sitekey"));
        });
        // text.addEventListener("mouseover", function() {
        //  alert($(this).attr("sitekey"));
        // });
        text.innerHTML = "fsdfsdf";
        svger.appendChild(text);




        // 添加文本
        var t = document.createElementNS(svgns, 'text');
        t.setAttribute("x",400);
        t.setAttribute("y", 300);
        t.setAttribute("font-size", "14");
        t.setAttribute('fill', 'blue');
        t.setAttribute('sitekey', 'P00002');
        t.setAttribute('style',"pointer-events:visiblePainted;");
        t.addEventListener("click", function() {
            endSk=$(this).attr("sitekey");
            arrsk.push($(this).attr("sitekey"));
        });
        // t.addEventListener("mouseover", function() {
        //  alert($(this).attr("sitekey"));
        // });
        t.innerHTML = "fsfsdfsfdsdfffffffffff";
        svger.appendChild(t);

 

        // 添加多边形
        var polygon = document.createElementNS(svgns, 'polygon');
        polygon.setAttribute("points","380,238 520,251 600,312 320,365");
        polygon.setAttribute('sitekey', 'P00003');
        polygon.setAttribute('style',"fill:transparent;stroke:purple;stroke-width:1;pointer-events:visiblePainted;");
        polygon.addEventListener("click", function() {
            endSk=$(this).attr("sitekey");
            arrsk.push($(this).attr("sitekey"));
        });
        svger.appendChild(polygon);

 

        // 添加多线段
        var polyline= document.createElementNS(svgns, 'polyline');
        polyline.setAttribute("points","241,138 575,151 736,212 671,365 622,448 358,451 356,315");
        polyline.setAttribute("font-size", "14");
        polyline.setAttribute('style', 'fill:none;stroke:red;stroke-width:1;pointer-events:visiblePainted;');
        polyline.setAttribute('marker-end', 'url(#markerArrow)');
        svger.appendChild(polyline);




    //     $(function() {
    //         $("text").click(function(){
    //             alert("sfdsfdsf");
    //         });
    // });
    // function click(param){
    //     alert(param);
    // }

 

//     window.addEventListener('mouseup', (e) => {
//   // Let's pick a random color between #000000 and #FFFFFF
//   const color = Math.round(Math.random() * 0xFFFFFF)

 

//   // Let's format the color to fit CSS requirements
//   const fill = '#' + color.toString(16).padStart(6,'0')

 

//   // Let's apply our color in the
//   // element we actually clicked on
//   e.target.style.fill = fill
// })

 

        //  var draw = SVG('container');
        //  var arrow = draw.marker(12, 12, function (add) {
        //         add.path();
        //         // add.circle(10).fill('#f06')
        //         add.style({
        //             fill: 'red'
        //         });
        //     });

 

        // var line2 = draw.polyline('241,138 575,151 736,212 671,365 622,448 358,451 356,315');
        // line2.fill('none').style({
        //     stroke: 'red',
        //     'stroke-width': 1
        // });
        // line2.marker('end', arrow)
        
        // $("path").attr("d","M2,2 L2,11 L10,6 L2,2");
        // $("path").attr("style","fill: red;");
</script>
posted @ 2021-07-06 16:06  时光1025  阅读(633)  评论(0编辑  收藏  举报