<div class="div1"> <svg id="svg1" xmlns="http://www.w3.org/2000/svg" width="100%" height="500px"> </svg> </div> methods:{ svgLoad(){ var ming = 'http://www.w3.org/2000/svg'; var oSvg = document.getElementById('svg1'); var oPolyLine = null; var pointsNum = ''; var lineText = null; function createTag(tagName, tagAttr) { let tag = document.createElementNS(ming, tagName); for (var attr in tagAttr) { tag.setAttribute(attr, tagAttr[attr]); } return tag; } var obj = document.querySelectorAll('.div1')[0]; obj.appendChild(createTag('svg', { 'xmlns': ming })); oSvg.onmousedown = function(ev) { if (!oPolyLine) { oPolyLine = createTag('polyline', { 'fill': 'none', 'stroke': 'red', 'stroke-width': '2' }); oSvg.appendChild(oPolyLine); } var x = ev.clientX - obj.offsetLeft; var y = ev.clientY - obj.offsetTop; if (pointsNum == '') { pointsNum = x + ',' + y; } else { pointsNum += ',' + x + ',' + y; } var theText = createTag('text', {//绘制鼠标移动位置坐标 'fill': 'red' }); oSvg.appendChild(theText); oPolyLine.setAttribute('points', pointsNum); theText.setAttribute('x',x); theText.setAttribute('y',y-30); theText.innerHTML=x + ',' + y; var oCircle = createTag('circle', {//绘制线条起始点 'cx': x, 'cy': y, 'r': '5', 'fill': 'white', 'stroke': 'red', 'stroke-width': 3 }); oSvg.appendChild(oCircle); if (ev.button === 2) { oSvg.onmousemove = null; oSvg.oncontextmenu = function() { oSvg.onmousemove = null; return false; }; } else { oSvg.onmousemove = function(ev) {//鼠标移动事件 var ev = ev || window.event; if (!lineText) {//显示鼠标移动坐标 lineText = createTag('text', { 'fill': 'red', 'x': ev.clientX - obj.offsetLeft, 'y': ev.clientY - obj.offsetTop }); var x = ev.clientX - obj.offsetLeft; var y = ev.clientY - obj.offsetTop; lineText.innerHTML= x + ',' + y;; oSvg.appendChild(lineText); } else{ var x = ev.clientX - obj.offsetLeft; var y = ev.clientY - obj.offsetTop; lineText.setAttribute('x',x,'y',y); lineText.innerHTML= x + ',' + y;; } if (oPolyLine) { var x = ev.clientX - obj.offsetLeft; var y = ev.clientY - obj.offsetTop; oPolyLine.setAttribute('points', pointsNum + ',' + x + ',' + y); } }; } } }, }