Thursday, February 14, 2019

drawing x1,y1,x2,y2 lines (any angle) with divs

When I was playing with different technologies for my timelines project Timelines project one advantage P5 had over straight DOM-stuff was being able to draw arbitrary lines (I was already using a lot of X/Y coordinate absolute positioning, rather than letting things flow)

Not surprisingly it's pretty easy to do similar in DOM and CSS, using transform rotations and just a bit of geometry.

The core CSS could be
.line {
    height:1px;
    background-color: #000;
    position: absolute;
    transform-origin: top left;  
}
(the container div should be be styled position:relative or similar)

and then the JS something like

function addLine(id,x1,y1,x2,y2) {
  const canvas = document.getElementById(id);
  const newLine = document.createElement("div");
  newLine.classList.add("line");

  const length = Math.sqrt(Math.pow(x1-x2,2)+Math.pow(y1-y2,2));
  const ang = Math.atan2(y2 - y1, x2 - x1) * 180 / Math.PI;

  newLine.style.top = `${x1}px`;
  newLine.style.left = `${y1}px`;
  newLine.style.width = `${length}px`;
  newLine.style.transform = `rotate(${ang}deg)`;
  canvas.appendChild(newLine);
}

I created a codepen proof of concept but didn't make it do anything interesting.

Of course, this doesn't hold a candle to stuff like Diana Adrianne's pure-CSS oilpaintings but it's a start :-D (For that matter, arguably I'm just reinventing svg, badly...)

No comments:

Post a Comment