js + css 在两点之间绘制直线
时间: 2024-01-24 18:01:54 浏览: 31
你可以使用 HTML5 的 Canvas 元素,结合 JavaScript 和 CSS 来画直线。下面是一个简单的示例代码:
HTML 代码:
```html
<!DOCTYPE html>
<html>
<head>
<title>画直线</title>
<style>
#myCanvas {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
z-index: -1;
}
</style>
</head>
<body>
<canvas id="myCanvas"></canvas>
<script src="script.js"></script>
</body>
</html>
```
CSS 代码:
```css
html,
body {
height: 100%;
margin: 0;
padding: 0;
}
```
JavaScript 代码:
```javascript
const canvas = document.getElementById("myCanvas");
const ctx = canvas.getContext("2d");
// 设置画布尺寸为屏幕宽高
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
// 设置起点和终点坐标
const startX = 100;
const startY = 100;
const endX = window.innerWidth - 100;
const endY = window.innerHeight - 100;
// 绘制直线
ctx.beginPath();
ctx.moveTo(startX, startY);
ctx.lineTo(endX, endY);
ctx.strokeStyle = "#000000";
ctx.lineWidth = 2;
ctx.stroke();
```
在这个示例中,我们首先在 HTML 中创建一个 Canvas 元素,并为其定义一个 ID。然后在 CSS 中设置了页面和 Canvas 的尺寸。接着在 JavaScript 中获取这个元素,并获取其 2D 渲染上下文。然后,我们设置起点和终点坐标,并使用 `moveTo()` 方法移动画笔到起点位置,再使用 `lineTo()` 方法画出一条从起点到终点的直线,并使用 `stroke()` 方法进行绘制。最后,我们设置了线条的颜色和宽度。