Created
April 30, 2019 17:51
-
-
Save IshanArya/c62d402681e1b19e010e98b91b8137f2 to your computer and use it in GitHub Desktop.
Create a draggable line on a webpage.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| let lineSvg = '<svg id="lineSvg" height="0" width="0" style="display: none; position: fixed; top: 0px; left: 0px;"><line x1="0" y1="0" x2="500" y2="500" style="stroke: rgb(255, 0, 0); stroke-width: 2;"></line></svg>' | |
| document.body.innerHTML = document.body.innerHTML + lineSvg; | |
| lineSvg = document.getElementById('lineSvg'); | |
| let line = document.querySelector('#lineSvg > line'); | |
| let mouseDownX; | |
| let mouseDownY; | |
| function turnOnTracerLine() { | |
| document.body.addEventListener('mousedown', tracerMouseDown); | |
| document.body.addEventListener('mouseup', tracerMouseUp); | |
| } | |
| function turnoffTracerLine() { | |
| document.body.removeEventListener('mousedown', tracerMouseDown); | |
| document.body.removeEventListener('mouseup', tracerMouseUp); | |
| } | |
| function tracerMouseDown(e) { | |
| mouseDownX = e.clientX; | |
| mouseDownY = e.clientY; | |
| lineSvg.style.top = e.clientY + "px"; | |
| lineSvg.style.left = e.clientX + "px"; | |
| lineSvg.style.display = "initial"; | |
| document.body.addEventListener('mousemove', tracerMouseMove); | |
| } | |
| function tracerMouseUp(e) { | |
| lineSvg.setAttribute('width', 0); | |
| lineSvg.setAttribute('height', 0); | |
| lineSvg.style.display = "none"; | |
| document.body.removeEventListener('mousemove', tracerMouseMove); | |
| } | |
| function tracerMouseMove(e) { | |
| e.preventDefault(); | |
| let thisWidth = tracerWidth(mouseDownX, e.clientX); | |
| lineSvg.setAttribute('width', thisWidth); | |
| let thisHeight = tracerHeight(mouseDownY, e.clientY); | |
| lineSvg.setAttribute('height', thisHeight); | |
| if (mouseDownX <= e.clientX) { | |
| lineSvg.style.left = mouseDownX + "px"; | |
| line.setAttribute('x1', 0); | |
| line.setAttribute('x2', thisWidth); | |
| } else { | |
| lineSvg.style.left = e.clientX + "px"; | |
| line.setAttribute('x1', thisWidth); | |
| line.setAttribute('x2', 0); | |
| } | |
| if (mouseDownY <= e.clientY) { | |
| lineSvg.style.top = mouseDownY + "px"; | |
| line.setAttribute('y1', 0); | |
| line.setAttribute('y2', thisHeight); | |
| } else { | |
| lineSvg.style.top = e.clientY + "px"; | |
| line.setAttribute('y1', thisHeight); | |
| line.setAttribute('y2', 0); | |
| } | |
| } | |
| function tracerHeight(y1, y2) { | |
| return Math.abs(y1 - y2); | |
| } | |
| function tracerWidth(x1, x2) { | |
| return Math.abs(x1 - x2); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment