使用纯CSS从一个点到另一个点绘制一条线(路径)。

9
我在下面的路径中有一个正在动画的图像,并希望路径可见。
CSS:
div {
    width:10px;
    height:10px;
    background:red;
    position:relative;
    -webkit-animation-name:Player1;
    -webkit-animation-duration:100s;
    -webkit-animation-timing-function:cubic-bezier(0.1,0.1,0.1,0.1);
    -webkit-animation-delay:2s;
    -webkit-animation-iteration-count:5;
    -webkit-animation-direction:normal;
    -webkit-animation-play-state:running
}

@-webkit-keyframes Player1 {
0% {
    background:red;
    left:20px;
    top:20px
}

25% {
    background:#ff0;
    left:800px;
    top:200px
}

50% {
    background:blue;
    left:950px;
    top:500px
}

75% {
    background:green;
    left:0;
    top:800px
}

100% {
    background:red;
    left:0;
    top:0
}
}

HTML:

<div></div>

这里有一个小提琴。

是否可能只使用CSS代码来连接它们?如果不行的话,你能帮我写一下代码吗?


你能在jsfiddle上展示一下吗? - misterManSam
你可以通过设置旋转div的宽度和变换原点来实现其动画效果。 - Alex
@misterManSam 抱歉,我不知道 jsfiddle 怎么用,但我已经更新了我的代码,并附上了整个源代码,希望能有所帮助? - evin
你可以使用SVG元素来绘制那条线。 - LorDex
@LorDex,我能否将我的left:800px; top:200px更改为x和y轴?这样代码看起来像75% {background:green; y=0; x=8吗?因为SVG使用x和y坐标。 - evin
3个回答

11

2
谢谢您,先生,您是我的英雄。 - evin

2
您可以使用svg中的“stroke-dashoffset”动画化线的起始点(也可以反向),就像这个codepen示例一样。
@keyframes dash {
  0% {
    stroke-dashoffset: 500;
  }
  100% {
    stroke-dashoffset: 0;
  }
}

https://codepen.io/Yudo/full/OaEWXK


1
你可以计算点之间的角度和距离,并使用CSS变换将线推到所需位置。这里有一个jsfiddle。它有点粗糙,但我认为你会明白的。
var startPoint=[200,200], 
    endPoint=[300,300],
    rise=endPoint[1]-startPoint[1],
    run=endPoint[0]-startPoint[0],
    slope=rise/run,
    DEGREES=57.2957795,
    width=Math.sqrt((rise*rise)+(run*run));
var line=document.getElementById('line');
line.style.top=startPoint[0]+'px';
line.style.left=startPoint[1]+'px';
line.style.width=width+"px";
line.style.transform= "rotate("+(Math.atan(slope)*DEGREES)+"deg)";
line.style.transformOrigin= "0 0";

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接