如何用HTML/CSS/JS绘制自适应窗口的A(0vh|0vw)到B(50vh|50vw)连线?
几种实现自适应两点连线的方法
方法1:用CSS动态计算角度(现代浏览器首选)
不用手动算角度,直接靠CSS原生数学函数自动计算,窗口尺寸变化时能实时更新角度和长度。
核心逻辑:
- 把线条容器定位在起点A(0,0),以左上角作为旋转原点
- 用勾股定理计算线条的实际长度,刚好覆盖A到B的距离
- 用
atan2()函数算出两点间的夹角,转成角度后应用旋转
代码示例:
.line { position: absolute; top: 0; left: 0; width: calc(sqrt((50vw)² + (50vh)²)); height: 1px; background: #000; transform-origin: top left; transform: rotate(calc(atan2(50vh, 50vw) * 180 / 3.1415926535deg)); }
注:sqrt()和atan2()是CSS原生数学函数,Chrome、Firefox、Edge等现代浏览器均支持。
方法2:用SVG绘制(最简单省心)
SVG天生适配矢量图形场景,无需处理旋转和长度计算,直接定义两点坐标即可,窗口尺寸变化时线条会自动适配。
代码示例:
<!-- SVG铺满整个视口,保证坐标与页面视口对应 --> <svg style="position: fixed; top: 0; left: 0; width: 100vw; height: 100vh;"> <!-- x1/y1为起点A,x2/y2为终点B,stroke控制线条颜色,stroke-width控制粗细 --> <line x1="0vw" y1="0vh" x2="50vw" y2="50vh" stroke="#000" stroke-width="1" /> </svg>
该方法兼容性极强,老浏览器也能正常运行,代码极简,推荐优先使用。
方法3:JS动态计算(兼容旧浏览器)
如果需要支持IE等老旧浏览器,可通过JS实时计算角度和长度,并在窗口 resize 时重新更新样式。
代码示例:
<div class="line"></div> <script> function updateLine() { const line = document.querySelector('.line'); // 计算B点的实际像素坐标 const dx = window.innerWidth * 0.5; // 对应50vw const dy = window.innerHeight * 0.5; // 对应50vh // 勾股定理计算线条长度 const length = Math.sqrt(dx*dx + dy*dy); // 弧度转角度,计算旋转角度 const angle = Math.atan2(dy, dx) * 180 / Math.PI; line.style.width = `${length}px`; line.style.transform = `rotate(${angle}deg)`; } // 页面初始化时执行,窗口变化时重新计算 updateLine(); window.addEventListener('resize', updateLine); </script> <style> .line { position: absolute; top: 0; left: 0; height: 1px; background: #000; transform-origin: top left; } </style>
内容的提问来源于stack exchange,提问作者Dragomy
相关产品推荐
相关产品推荐

