画图js实现
使用Canvas API绘制图形
Canvas API是HTML5提供的原生绘图工具,通过JavaScript操作Canvas元素实现绘图功能。需要获取Canvas的上下文(context)后调用绘图方法。
// 获取Canvas元素和上下文
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');
// 绘制矩形
ctx.fillStyle = 'blue';
ctx.fillRect(10, 10, 100, 100);
// 绘制圆形
ctx.beginPath();
ctx.arc(200, 60, 50, 0, Math.PI * 2);
ctx.fillStyle = 'red';
ctx.fill();
使用SVG动态生成图形
SVG是基于XML的矢量图形格式,可以通过JavaScript动态创建和修改SVG元素。

// 创建SVG元素
const svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
svg.setAttribute("width", "300");
svg.setAttribute("height", "200");
// 添加矩形
const rect = document.createElementNS("http://www.w3.org/2000/svg", "rect");
rect.setAttribute("x", "10");
rect.setAttribute("y", "10");
rect.setAttribute("width", "100");
rect.setAttribute("height", "100");
rect.setAttribute("fill", "green");
svg.appendChild(rect);
// 添加到DOM
document.body.appendChild(svg);
使用第三方库绘制图表
Chart.js是流行的图表库,适用于快速创建各种统计图表。
// 引入Chart.js后使用
const ctx = document.getElementById('chartCanvas').getContext('2d');
const chart = new Chart(ctx, {
type: 'bar',
data: {
labels: ['Red', 'Blue', 'Yellow'],
datasets: [{
label: 'Dataset',
data: [12, 19, 3],
backgroundColor: ['red', 'blue', 'yellow']
}]
}
});
使用D3.js进行数据可视化
D3.js是专业级数据可视化库,适合创建复杂的交互式图表。

// 创建SVG容器
const svg = d3.select("body").append("svg")
.attr("width", 400)
.attr("height", 200);
// 绘制数据点
svg.selectAll("circle")
.data([10, 20, 30])
.enter().append("circle")
.attr("cx", (d, i) => i * 50 + 30)
.attr("cy", 50)
.attr("r", d => d)
.attr("fill", "purple");
使用WebGL进行3D绘图
Three.js是基于WebGL的3D图形库,适合创建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(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可以创建基本的几何图形,适合简单的UI元素。
<style>
.circle {
width: 100px;
height: 100px;
border-radius: 50%;
background-color: orange;
}
.triangle {
width: 0;
height: 0;
border-left: 50px solid transparent;
border-right: 50px solid transparent;
border-bottom: 100px solid teal;
}
</style>
<div class="circle"></div>
<div class="triangle"></div>






