JSFiddle - React, Tailwind, and code Playground
by melvinT
HTML
<!DOCTYPE html>
<html>
<head>
<title>drag triangle</title>
</head>
<body>
<svg id="figure1" width="500" height="500">
<style>
#figure1 {
border: 1px solid blue;
}
</style>
<script type="text/javascript">
<![CDATA[
var svg = document.getElementById('figure1');
svg.addEventListener('mousemove', onMouseMove);
svg.addEventListener('mouseup', onMouseUp);
function onMouseMove(ev) {
var p;
if (!dragElem) {
return;
}
p = getClientPointInSVG(ev);
dragElem.setAttribute('cx', p.x - mouseOffsetX);
dragElem.setAttribute('cy', p.y - mouseOffsetY);
controlPath.setAttribute('d',
'M' + p1.getAttribute('cx') + ' ' + p1.getAttribute('cy') +
' ' + p2.getAttribute('cx') + ' ' + p2.getAttribute('cy') +
' ' + p3.getAttribute('cx') + ' ' + p3.getAttribute('cy') +
' ' + 'z' );
}
function onMouseDown(ev) {
var p;
dragElem = ev.target;
p = getClientPointInSVG(ev);
mouseOffsetX = p.x - dragElem.getAttribute('cx');
mouseOffsetY = p.y - dragElem.getAttribute('cy');
}
function getClientPointInSVG(ev) {
var p, m;
p = svg.createSVGPoint();
p.x = ev.clientX;
p.y = ev.clientY;
m = dragElem.getScreenCTM();
return p.matrixTransform(m.inverse());
}
function onMouseUp(ev) {
dragElem = null;
}
var mouseOffsetX, mouseOffsetY;
</script>
<path d="M170 150 20 110 250 60 z" stroke="pink" fill="none" id="controlPath"/>
<circle cx="170" cy="150" r="8" id="p1" fill="red" style="cursor: move;"/>
<circle cx="20" cy="110" r="8" id="p2" fill="black" style="cursor: move;"/>
<circle cx="250" cy="60" r="8" id="p3" fill="lightgrey" style="cursor: move;"/>
var controlPath = document.getElementById('controlPath');
var dragElem = null;
var p1 = document.getElementById('p1');
var p2 = document.getElementById('p2');
var p3 = document.getElementById('p3');
</svg>
<script>
var elements = [p1, p2, p3,];
for (i = 0; i < elements.length; i++) {
elements[i].addEventListener('mousedown',...