<svg width="500" height="500" viewBox="0 0 1000 1000">
<rect x="0" y="0" width="1000" height="1000" fill="white" stroke="black" stroke-width="2" />
<g id="draggableElement" transform="translate(500 500)">
<circle cx="0" cy="0" r="75" fill="black" />
</g>
</svg>
circle {
fill: lightgray;
stroke: #212121;
stroke-width: 5;
transition-property: fill, stroke-width;
transition-duration: 200ms;
transition-timing-function: ease-in-out
}
circle:hover {
fill: white;
stroke-width: 20;
}
text {
fill: #eaeaea;
font-size: 80px;
font-weight: 900;
}
const svg = document.querySelector("svg");
const draggableElement = document.querySelector("#draggableElement");
let dragging = false;
function init() {
draggableElement.addEventListener("mousedown", startDrag);
svg.addEventListener("mousemove", drawDrag);
svg.addEventListener("mouseup", stopDrag);
svg.addEventListener("mouseout", stopDrag);
}
function startDrag() {
dragging = true;
}
function stopDrag() {
dragging = false;
}
function drawDrag(mouseEvent) {
if (!dragging) return;
const svgPoint = toSVGPoint(mouseEvent.clientX, mouseEvent.clientY, svg);
draggableElement.setAttribute("transform", `translate(${svgPoint.x} ${svgPoint.y})`);
}
function toSVGPoint(x, y, theSVG) {
let p = new DOMPoint(x, y);
return p.matrixTransform(theSVG.getScreenCTM().inverse());
}
init();
This Pen doesn't use any external JavaScript resources.