Reputation: 87
I have a project: on mouse clicks and move and next click and so on; by every click's position I want to make an svg polygon but I don't have any idea as to how.
When the mouse moves, at the same time the polygon's last point is appearing at the mouse pointer and when I click and move, the clicked position get a vertices point and so on.
Upvotes: 2
Views: 2362
Reputation: 36564
here is a code example you want. Polygon needs to be closed you should use polyline
<svg id="svg" height="500px" width="500px" style="border: 1px dashed #dbd2d2;">
<polyline id="polyline" style="fill:white;stroke:black;stroke-width:1"/>
</svg>
<script>
const polyline = document.querySelector('#polyline');
const svg = document.querySelector('#svg');
svg.addEventListener('click',(e) =>{
let pts = polyline.getAttribute('points') || '';
const newPoint = `${e.clientX},${e.clientY} `;
pts += newPoint;
polyline.setAttribute('points',pts);
})
</script>
Update: For mousemove functionality add this code
<svg id="svg" height="50%" width="50%" style="border: 1px dashed #dbd2d2;">
<polyline id="polyline" style="fill:white;stroke:black;stroke-width:1"/>
<line id="templine" style="fill:white;stroke:black;stroke-width:1" />
</svg>
<script>
let lastPt;
const polyline = document.querySelector('#polyline');
const svg = document.querySelector('#svg');
const templine = document.querySelector('#templine');
svg.addEventListener('click',(e) =>{
let pts = polyline.getAttribute('points') || '';
const newPoint = `${e.clientX},${e.clientY} `;
pts += newPoint;
polyline.setAttribute('points',pts);
lastPt = [e.clientX,e.clientY]
})
svg.addEventListener('mousemove',(e) =>{
templine.setAttribute('x1',lastPt[0]);
templine.setAttribute('y1',lastPt[1]);
templine.setAttribute('x2',e.clientX);
templine.setAttribute('y2',e.clientY);
})
</script>
Upvotes: 1