vue中 使用SVG實現鼠標點擊繪圖 提示鼠標移動位置 顯示繪制坐標位置


<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);

}

};

}

}

},

}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM