js实现线条
使用 Canvas 绘制线条
Canvas 是 HTML5 提供的绘图 API,可以通过 JavaScript 动态绘制线条。
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');
// 设置线条样式
ctx.strokeStyle = 'blue';
ctx.lineWidth = 5;
// 开始绘制路径
ctx.beginPath();
ctx.moveTo(50, 50); // 起点坐标
ctx.lineTo(200, 100); // 终点坐标
ctx.stroke(); // 绘制线条
使用 SVG 创建线条
SVG 是矢量图形标准,可以直接在 HTML 中嵌入线条元素。

<svg width="300" height="200">
<line x1="50" y1="50" x2="200" y2="100"
stroke="red" stroke-width="3" />
</svg>
使用 CSS 绘制线条
通过 CSS 的边框属性可以创建简单的线条效果。

<div class="horizontal-line"></div>
<div class="vertical-line"></div>
<style>
.horizontal-line {
width: 200px;
border-top: 2px solid green;
margin: 20px 0;
}
.vertical-line {
height: 100px;
border-left: 2px solid purple;
margin: 0 20px;
}
</style>
使用 WebGL 绘制 3D 线条
对于需要 3D 效果的线条,可以使用 WebGL 技术。
// 初始化 WebGL 上下文
const canvas = document.getElementById('glCanvas');
const gl = canvas.getContext('webgl');
// 顶点着色器
const vsSource = `
attribute vec4 aVertexPosition;
void main() {
gl_Position = aVertexPosition;
}
`;
// 片段着色器
const fsSource = `
void main() {
gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0);
}
`;
// 初始化着色器程序
const shaderProgram = initShaderProgram(gl, vsSource, fsSource);
const programInfo = {
program: shaderProgram,
attribLocations: {
vertexPosition: gl.getAttribLocation(shaderProgram, 'aVertexPosition')
}
};
// 定义线条顶点数据
const positions = [
-0.5, -0.5, 0.0,
0.5, 0.5, 0.0
];
// 创建缓冲区并绑定数据
const positionBuffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer);
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(positions), gl.STATIC_DRAW);
// 绘制线条
gl.drawArrays(gl.LINES, 0, 2);
使用第三方库绘制高级线条
D3.js 和 Three.js 等库提供了更高级的线条绘制功能。
// 使用 D3.js 绘制 SVG 线条
d3.select("body").append("svg")
.attr("width", 300)
.attr("height", 200)
.append("line")
.attr("x1", 50)
.attr("y1", 50)
.attr("x2", 250)
.attr("y2", 150)
.attr("stroke", "orange")
.attr("stroke-width", 4);
// 使用 Three.js 绘制 3D 线条
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(75, window.innerWidth/window.innerHeight, 0.1, 1000);
const renderer = new THREE.WebGLRenderer();
const material = new THREE.LineBasicMaterial({ color: 0x00ff00 });
const geometry = new THREE.BufferGeometry();
const vertices = new Float32Array([-1, -1, 0, 1, 1, 0]);
geometry.setAttribute('position', new THREE.BufferAttribute(vertices, 3));
const line = new THREE.Line(geometry, material);
scene.add(line);






