Skip to content

Instantly share code, notes, and snippets.

@ahvonenj
Last active August 29, 2015 14:23
Show Gist options
  • Save ahvonenj/d18afbaf3a16550d3438 to your computer and use it in GitHub Desktop.
Save ahvonenj/d18afbaf3a16550d3438 to your computer and use it in GitHub Desktop.
Drawing lines without canvas, using the HR-tag
function Line(from, to, color, thickness)
{
this.from = from || { x: 0, y: 0 };
this.to = to || { x: 100, y: 100 };
// Aliases for from and to
this.p1 = this.from;
this.p2 = this.to;
this.color = color || 'black';
this.thickness = thickness || 2;
// Create hr element
this.line = document.createElement('hr');
// Cache hr element for jQuery
this.$line = $(this.line);
this.draw();
return this;
}
Line.prototype.draw = function()
{
// Distance and angle calculations for CSS3 transforms
var d = Math.sqrt((this.from.x - this.to.x) * (this.from.x - this.to.x) + (this.from.y - this.to.y) * (this.from.y - this.to.y));
var angleRad = Math.atan2(this.p2.y - this.p1.y, this.p2.x - this.p1.x);
var angleDeg = Math.atan2(this.p2.y - this.p1.y, this.p2.x - this.p1.x) * 180 / Math.PI;
// Apply million rules of CSS
this.$line.css(
{
'position': 'absolute',
'color': this.color,
'background-color': this.color,
'border': 'none',
'height': this.thickness + 'px',
'width': d + 'px',
'padding': 0,
'margin': 0,
'left': this.from.x + 'px',
'top': this.from.y + 'px',
'transform-origin': 'left',
'transform': 'rotate(' + angleDeg + 'deg)'
});
// Append the created and styled line to body
this.$line.appendTo('#matrix');
}
Line.prototype.update = function(newfrom, newto, newcolor, newthickness)
{
this.from = newfrom || this.from;
this.to = newto || this.to;
this.p1 = this.from;
this.p2 = this.to;
this.color = newcolor || this.color;
this.thickness = newthickness || this.thickness;
this.draw();
return this;
}
@ahvonenj
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment