Sample SVG with drag element

<html>
<script type="text/ecmascript">
	var selectedElement = 0;
	var currentX = 0;
	var currentY = 0;
	var currentMatrix = 0;

	function selectElement(evt) {
		selectedElement = evt.target;
		currentX = evt.clientX;
		currentY = evt.clientY;
		currentMatrix = selectedElement.getAttributeNS(null, "transform").slice(7, -1).split(' ');

		for (var i = 0; i < currentMatrix.length; i++) {
			currentMatrix[i] = parseFloat(currentMatrix[i]);
		}
		selectedElement.setAttributeNS(null, "onmousemove", "moveElement(evt)");
		selectedElement.setAttributeNS(null, "onmouseup", "deselectElement(evt)");
		selectedElement.style.cursor='move';
	}

	function moveElement(evt) {
		dx = evt.clientX - currentX;
		dy = evt.clientY - currentY;
		currentMatrix[4] += dx;
		currentMatrix[5] += dy;
		newMatrix = "matrix(" + currentMatrix.join(' ') + ")";

		selectedElement.setAttributeNS(null, "transform", newMatrix);
		currentX = evt.clientX;
		currentY = evt.clientY;
	}

	function deselectElement(evt) {
		if (selectedElement != 0) {
			selectedElement.style.cursor='';
			console.log(selectedElement.style.cursor);
			selectedElement.removeAttributeNS(null, "onmousemove");
			selectedElement.removeAttributeNS(null, "onmouseout");
			selectedElement.removeAttributeNS(null, "onmouseup");
			selectedElement = 0;
		}
	}
</script>

<body>
	<svg xmlns="http://www.w3.org/2000/svg" version="1.1" width="1000" height="1000">
		<ellipse cx="150" cy="150" rx="100" ry="100" transform="matrix(1 0 0 1 0 0)" onmousedown="selectElement(evt)" style="fill:yellow;stroke:purple;stroke-width:2" />
	</svg>
</body>
</html>

Leave a Reply

Your email address will not be published. Required fields are marked *