Created
August 7, 2016 15:29
-
-
Save madox2/c79cab16dee72ed3f5e690c648bbff11 to your computer and use it in GitHub Desktop.
draw lines on html page using div elements
This file contains 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
/** | |
* Creates line element on given position, with given length and angle. | |
*/ | |
function createLineElement(x, y, length, angle) { | |
var line = document.createElement("div"); | |
var styles = 'border: 1px solid black; ' | |
+ 'width: ' + length + 'px; ' | |
+ 'height: 0px; ' | |
+ '-moz-transform: rotate(' + angle + 'rad); ' | |
+ '-webkit-transform: rotate(' + angle + 'rad); ' | |
+ '-o-transform: rotate(' + angle + 'rad); ' | |
+ '-ms-transform: rotate(' + angle + 'rad); ' | |
+ 'position: absolute; ' | |
+ 'top: ' + y + 'px; ' | |
+ 'left: ' + x + 'px; '; | |
line.setAttribute('style', styles); | |
return line; | |
} | |
/** | |
* Creates element which represents line from point [x1, y1] to [x2, y2]. | |
* It is html div element with minimal height and width corresponding to line length. | |
* It's position and rotation is calculated below. | |
*/ | |
function createLine(x1, y1, x2, y2) { | |
var a = x1 - x2, | |
b = y1 - y2, | |
c = Math.sqrt(a * a + b * b); | |
var sx = (x1 + x2) / 2, | |
sy = (y1 + y2) / 2; | |
var x = sx - c / 2, | |
y = sy; | |
var alpha = Math.PI - Math.atan2(-b, a); | |
return createLineElement(x, y, c, alpha); | |
} | |
// Draw some lines | |
document.body.appendChild(createLine(100, 100, 200, 200)); | |
document.body.appendChild(createLine(30, 40, 150, 300)); | |
document.body.appendChild(createLine(400, 300, 100, 100)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment