svg 折线鼠标绘制

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        #div1{ 780px;height: 370px;background: white; background: url(./bakground.jpeg) no-repeat;margin:20px auto; overflow: hidden;}
        body{background: gray;}
    </style>
</head>
<body>
    <div id="div1"> 
        <svg id = "svg1" xmlns="http://www.w3.org/2000/svg" width="100%" height="100%" >
            <!-- 折线 -->
           <!--  <polyline points = "50,50,200,300,230,300,250,200" fill = "none" stroke = "black" stroke-width="5"></polyline>  -->
            <!-- 闭合 -->
            <!-- <polygon points = "50,50,200,300,230,300,250,200" fill = "none" stroke = "black" stroke-width="5"></polygon>   -->
        </svg> 
        
    </div>
</body>
</html>
<script>
    window.onload = function()
    {
        var svgNS = 'http://www.w3.org/2000/svg';
        var oParent = document.getElementById('div1');
        var oSvg = document.getElementById("svg1");
        var oPolyLine = null;
        var pointsNum = "";

     /* 封装一个创建标签的函数 */
      function createTag(tag,objAttr)
     {
       var oTag = document.createElementNS(svgNS,tag);
    
       for(var attr in objAttr)
       {
           oTag.setAttribute(attr,objAttr[attr]);
       }
       return oTag;
     }

     oSvg.onmousedown = function(ev)
       {
           var ev = ev||window.event;
           if(!oPolyLine)
           {
            oPolyLine = createTag('polyline',{'fill':'none','stroke':'red','stroke-width':'2'})
            oSvg.appendChild(oPolyLine);
           }
           oPolyLine = createTag('polyline',{'fill':'none','stroke':'red','stroke-width':'2'})
           oSvg.appendChild(oPolyLine);

           var x = ev.clientX-oParent.offsetLeft;
           var y = ev.clientY-oParent.offsetTop;

           if(pointsNum == "")
           {
            pointsNum = x + ',' + y;
           }
           else{
            pointsNum += ','+x+','+y;  
           }

           oPolyLine.setAttribute('points',pointsNum);
           var oCircle = createTag('circle',{'cx':x,'cy':y,'r':'5','fill':'white','stroke':'red','stroke-width':'3'});
           oSvg.append(oCircle)
       }

       oSvg.onmousemove = function(ev)
       {
           var ev = ev ||window.event;
           if(oPolyLine)
           {
            var x = ev.clientX-oParent.offsetLeft;
            var y = ev.clientY-oParent.offsetTop;
            oPolyLine.setAttribute('points',pointsNum+','+x+','+y);

           }
       }

       oSvg.oncontextmenu = function()
       {
           oSvg.onmousemove = null;
           return false;
       }

    }

    


</script>
原文地址:https://www.cnblogs.com/Aaron-Lee/p/13855706.html