2026-07-31 03:41:03
使用JavaScript Canvas绘制可配置的水壶图形,可通过封装drawJug函数实现模块化与位置无关性,结合路径管理和配置选项提升灵活性与复用性。
一、Canvas路径绘制基础Canvas的2D绘图能力依赖路径(Path)构建复杂图形,核心方法包括:
将水壶绘制逻辑封装为独立函数,接受ctx(渲染上下文)、起始坐标(x, y)及配置对象(如颜色、尺寸)作为参数,实现位置无关性与可配置性。
1. 基础版drawJug函数以下代码展示如何通过相对坐标绘制水壶,并使用beginPath()确保路径独立:
const drawJug = (ctx, x, y) => { ctx.beginPath(); // 壶口上沿(二次贝塞尔曲线) ctx.moveTo(x, y); ctx.quadraticCurveTo(x + 30, y - 20, x + 60, y); // 壶身右侧(直线) ctx.lineTo(x + 60, y + 80); // 壶底(圆弧) ctx.arc(x + 30, y + 100, 30, 0, Math.PI, true); // 壶身左侧(直线) ctx.lineTo(x, y + 20); // 壶口下沿(二次贝塞尔曲线) ctx.quadraticCurveTo(x + 10, y, x, y); ctx.stroke(); // 绘制轮廓};关键点:
通过配置对象自定义水壶颜色、尺寸等属性,提升灵活性:
const drawJug = (ctx, x, y, config = {}) => { const { width = 60, height = 100, color = '#fff', lineWidth = 2 } = config; ctx.beginPath(); ctx.strokeStyle = color; ctx.lineWidth = lineWidth; // 壶口上沿(缩放后的二次贝塞尔曲线) ctx.moveTo(x, y); ctx.quadraticCurveTo( x + width * 0.5, y - height * 0.2, x + width, y ); // 壶身右侧(直线) ctx.lineTo(x + width, y + height * 0.8); // 壶底(圆弧) ctx.arc( x + width * 0.5, y + height, width * 0.5, 0, Math.PI, true ); // 壶身左侧(直线) ctx.lineTo(x, y + height * 0.2); // 壶口下沿(二次贝塞尔曲线) ctx.quadraticCurveTo( x + width * 0.167, y, x, y ); ctx.stroke();};配置项说明:
以下代码展示如何在HTML中调用drawJug函数,绘制不同颜色和尺寸的水壶:
<!DOCTYPE html><html lang="zh-CN"><head> <meta charset="UTF-8"> <title>Canvas 可配置水壶</title> <style> body { margin: 0; display: flex; justify-content: center; align-items: center; height: 100vh; background: #222; } canvas { border: 1px solid #fff; } </style></head><body> <canvas id="view" width="500" height="200"></canvas> <script> const ctx = document.getElementById('view').getContext('2d'); const main = () => { ctx.translate(0.5, 0.5); // 像素对齐 ctx.fillStyle = '#000'; ctx.fillRect(0, 0, ctx.canvas.width, ctx.canvas.height); // 绘制不同配置的水壶 drawJug(ctx, 50, 40, { color: 'hsl(0, 100%, 75%)', width: 50 }); drawJug(ctx, 200, 40, { color: 'hsl(120, 100%, 75%)', height: 80 }); drawJug(ctx, 350, 40, { color: 'hsl(180, 100%, 75%)', width: 70, lineWidth: 3 }); }; const drawJug = (ctx, x, y, config = {}) => { const { width = 60, height = 100, color = '#fff', lineWidth = 2 } = config; ctx.beginPath(); ctx.strokeStyle = color; ctx.lineWidth = lineWidth; // 路径绘制逻辑(同增强版代码) // ...(省略重复部分,见上文增强版代码) ctx.stroke(); }; main(); </script></body></html>效果说明:
通过以上方法,可高效构建灵活、可维护的Canvas图形系统,适用于数据可视化、游戏开发等场景。