js 实现画线
使用 Canvas API 画线
Canvas API 是 HTML5 提供的绘图工具,可以通过 JavaScript 直接操作画布元素绘制线条。
// 获取 Canvas 元素和上下文
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');
// 设置线条样式
ctx.strokeStyle = 'blue'; // 线条颜色
ctx.lineWidth = 5; // 线条宽度
// 开始绘制路径
ctx.beginPath();
ctx.moveTo(50, 50); // 起点坐标
ctx.lineTo(250, 150); // 终点坐标
ctx.stroke(); // 绘制线条
使用 SVG 画线
SVG 是矢量图形标准,可以通过 DOM 操作创建线条元素。
// 创建 SVG 元素
const svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
svg.setAttribute('width', '300');
svg.setAttribute('height', '200');
document.body.appendChild(svg);
// 创建线条元素
const line = document.createElementNS("http://www.w3.org/2000/svg", "line");
line.setAttribute('x1', '50');
line.setAttribute('y1', '50');
line.setAttribute('x2', '250');
line.setAttribute('y2', '150');
line.setAttribute('stroke', 'red');
line.setAttribute('stroke-width', '5');
svg.appendChild(line);
使用 CSS 画线
通过 CSS 的伪元素和 transform 属性可以创建简单的线条效果。
// 创建 div 元素
const div = document.createElement('div');
div.className = 'line';
document.body.appendChild(div);
// 添加 CSS 样式
const style = document.createElement('style');
style.textContent = `
.line {
position: relative;
width: 200px;
height: 5px;
background-color: green;
transform: rotate(20deg);
transform-origin: left center;
}
`;
document.head.appendChild(style);
使用 WebGL 画线
WebGL 提供更强大的 3D 绘图能力,适合复杂图形需求。
// 获取 WebGL 上下文
const canvas = document.getElementById('glCanvas');
const gl = canvas.getContext('webgl');
// 顶点着色器
const vsSource = `
attribute vec2 position;
void main() {
gl_Position = vec4(position, 0.0, 1.0);
}
`;
// 片段着色器
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: {
position: gl.getAttribLocation(shaderProgram, 'position'),
},
};
// 定义线条顶点
const vertices = new Float32Array([
0.0, 0.5,
0.5, -0.5
]);
// 创建缓冲区
const vertexBuffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer);
gl.bufferData(gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW);
// 绘制线条
gl.drawArrays(gl.LINES, 0, 2);
使用第三方库画线
许多图形库如 D3.js、Three.js 等提供了更高级的绘图功能。
// 使用 D3.js 画线
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', 'purple')
.attr('stroke-width', 5);
// 使用 Three.js 画线
const scene = new THREE.Scene();
const renderer = new THREE.WebGLRenderer();
renderer.setSize(300, 200);
document.body.appendChild(renderer.domElement);
const geometry = new THREE.BufferGeometry();
const material = new THREE.LineBasicMaterial({ color: 0x00ff00 });
const points = [
new THREE.Vector3(0, 0, 0),
new THREE.Vector3(1, 1, 0)
];
geometry.setFromPoints(points);
const line = new THREE.Line(geometry, material);
scene.add(line);
renderer.render(scene, camera);






