js 画图实现
使用 Canvas API 绘制图形
Canvas API 是 HTML5 提供的原生绘图工具,通过 JavaScript 操作画布元素实现绘图。基本步骤如下:
-
在 HTML 中创建
<canvas>元素:<canvas id="myCanvas" width="500" height="500"></canvas> -
获取画布上下文并绘制图形:
const canvas = document.getElementById('myCanvas'); const ctx = canvas.getContext('2d');
// 绘制矩形 ctx.fillStyle = 'blue'; ctx.fillRect(50, 50, 100, 100);
// 绘制圆形 ctx.beginPath(); ctx.arc(200, 200, 50, 0, Math.PI * 2); ctx.fillStyle = 'red'; ctx.fill();
### 使用 SVG 绘图
SVG 是矢量图形标记语言,可通过 JavaScript 动态创建和修改:
1. HTML 中直接嵌入 SVG:
```html
<svg id="mySvg" width="500" height="500"></svg>
- 使用 JavaScript 添加图形元素:
const svg = document.getElementById('mySvg');
// 创建圆形 const circle = document.createElementNS('http://www.w3.org/2000/svg', 'circle'); circle.setAttribute('cx', '100'); circle.setAttribute('cy', '100'); circle.setAttribute('r', '50'); circle.setAttribute('fill', 'green'); svg.appendChild(circle);

### 使用第三方库(Chart.js)
对于数据可视化,Chart.js 提供简单易用的图表绘制功能:
1. 引入库文件:
```html
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<canvas id="myChart"></canvas>
- 创建图表:
const ctx = document.getElementById('myChart'); new Chart(ctx, { type: 'bar', data: { labels: ['Red', 'Blue', 'Yellow'], datasets: [{ label: 'Color Values', data: [12, 19, 3], backgroundColor: [ 'rgba(255, 99, 132, 0.2)', 'rgba(54, 162, 235, 0.2)', 'rgba(255, 206, 86, 0.2)' ] }] } });
使用 D3.js 进行高级可视化
D3.js 适合复杂的数据可视化需求:
-
引入 D3.js:
<script src="https://d3js.org/d3.v7.min.js"></script> <div id="visualization"></div> -
创建力导向图示例:
const width = 600, height = 400; const svg = d3.select("#visualization") .append("svg") .attr("width", width) .attr("height", height);
// 模拟数据 const nodes = [{id: 1}, {id: 2}, {id: 3}]; const links = [{source: 1, target: 2}, {source: 2, target: 3}];

// 创建力导向布局 const simulation = d3.forceSimulation(nodes) .force("link", d3.forceLink(links).id(d => d.id)) .force("charge", d3.forceManyBody()) .force("center", d3.forceCenter(width / 2, height / 2));
### WebGL 三维绘图
对于高性能 3D 图形,可使用 Three.js:
1. 引入 Three.js:
```html
<script src="https://cdn.jsdelivr.net/npm/three@0.132.2/build/three.min.js"></script>
<div id="3d-container"></div>
- 创建简单 3D 场景:
const scene = new THREE.Scene(); const camera = new THREE.PerspectiveCamera(75, window.innerWidth/window.innerHeight, 0.1, 1000); const renderer = new THREE.WebGLRenderer(); renderer.setSize(800, 600); document.getElementById('3d-container').appendChild(renderer.domElement);
const geometry = new THREE.BoxGeometry(); const material = new THREE.MeshBasicMaterial({color: 0x00ff00}); const cube = new THREE.Mesh(geometry, material); scene.add(cube);
camera.position.z = 5;
function animate() { requestAnimationFrame(animate); cube.rotation.x += 0.01; cube.rotation.y += 0.01; renderer.render(scene, camera); } animate();






