在两点之间画一条假想的路径并沿着该路径打印图像? [英] draw imaginary path between two points and print image along that path?

查看:118
本文介绍了在两点之间画一条假想的路径并沿着该路径打印图像?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用Javascript(或jQuery)是否可以在坐标之间绘制线(不一定显示这些线),然后沿着这些路径"重复图像或字母? 我在这里说的是直线,没有贝塞尔曲线或其他任何东西. 我认为这似乎没什么大不了的,并且会尝试一下,但是我想在此方面征询其他人的意见... 类似于(虚构代码):

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')

我疯了吗? 谢谢

推荐答案

tl; dr

这是一个jsFiddle,它可以满足我的要求:单击.

实际上这很容易,因为您可以通过知道x坐标和该直线经过的两个点来计算直线上的任何点:

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

一旦有了斜率,就可以通过简单地将其x坐标乘以斜率来计算直线上的任何"y":

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 ↓
}

有了这些,剩下的只是复制图像(或其他DOM对象)并将其定位在以下坐标上的事情:

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"
})

-imageWidth/2部分在此处使图像居中.否则,图像的左上角将定位在该位置.此外,此方法还依赖于您指定相对于其父容器偏移量的坐标的事实,该偏移量必须具有position: relative属性.然后,如@Eru的注释所建议的那样,使用此技术定位的每个元素都必须有一个position: absolute.

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.

这篇关于在两点之间画一条假想的路径并沿着该路径打印图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆