Is there a way with Javascript (or jQuery) to draw lines between coordinates (not necessarily showing those lines) and then repeat an image or a letter along those "paths"?
I am talking straight lines here, no bezier curves or anything.
I would think it doesn't seem like a big deal and will give it a go, but I'd like to have others' opinion on this...
something like (imaginary code):
path = point1[x,y], point2[x,y], point3[x,y];
every20pixels-->renderimage('path/to/image') or letter('letter')
am I crazy?
Thanks
tl;dr
Here's a jsFiddle that does what I think you want: click.
Explanation
It is quite easy actually, given that you can calculate any point on a line by knowing it's x-coordinate and two of the points the line goes through:
// A line, defined by two coordinates
var s = {x: 0.0, y: 0.0}; // Start
var e = {x: 300.0, y: 100.0}; // End
var distance = (e.x - s.x)
var slope = (e.y - s.y) / distance
As soon as you have the slope, you can calculate any "y" on the line by simply multiypling it's x-coordinate with the slope:
var step = 32; // Calculate y-coordinate every 32 units
for(var x=0; x<distance; x+=step) {
var y = x * slope;
console.log(s.x + x, s.y + y);
// The next snippet goes here ↓
}
Having that, the rest is simply a matter copying an image (or other DOM object) and position it at these coordinates:
image.clone().appendTo(stage).css({
left: (s.x + x-imageWidth/2) + "px",
top: (s.y + y-imageHeight/2) + "px"
})
The -imageWidth/2
part is there to center the image on the line. Otherwise, the upper left corner of the image would be positioned there. Also, this method relies on the fact that you specify the coordinates relative to their parents containers offset, which must have the position: relative
attribute. Every element you position using this technique must then have a position: absolute
, as suggested by @Eru's comment.