js实现绘图
使用Canvas API绘图
Canvas是HTML5提供的绘图API,适合动态图形和游戏开发。通过获取Canvas元素的上下文(getContext('2d'))调用绘图方法:
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');
ctx.fillStyle = 'red';
ctx.fillRect(10, 10, 100, 100); // 绘制红色矩形
ctx.beginPath();
ctx.arc(150, 75, 50, 0, Math.PI * 2); // 绘制圆形
ctx.stroke();
使用SVG绘图
SVG(可缩放矢量图形)通过XML描述图形,适合静态矢量图。可直接嵌入HTML或通过JavaScript动态创建:
const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
svg.setAttribute('width', '200');
svg.setAttribute('height', '200');
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', 'blue');
svg.appendChild(circle);
document.body.appendChild(svg);
使用第三方库(如Chart.js)
Chart.js简化了图表绘制,适合数据可视化:
import Chart from 'chart.js/auto';
const ctx = document.getElementById('chart').getContext('2d');
new Chart(ctx, {
type: 'bar',
data: {
labels: ['A', 'B', 'C'],
datasets: [{
label: '数据',
data: [10, 20, 30],
backgroundColor: ['#ff0000', '#00ff00', '#0000ff']
}]
}
});
使用WebGL(Three.js)
Three.js封装WebGL,适合3D图形渲染:
import * as THREE from 'three';
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(window.innerWidth, window.innerHeight);
document.body.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();
使用HTML/CSS绘图
简单的图形可通过CSS实现,例如纯CSS绘制三角形:

<div class="triangle"></div>
<style>
.triangle {
width: 0;
height: 0;
border-left: 50px solid transparent;
border-right: 50px solid transparent;
border-bottom: 100px solid yellow;
}
</style>






