Canvas
跳转到“Canvas”Canvas是可通过JavaScript绘图的HTML元素,可用于图表、动画等;它是像素画布,不会为每条路径自动生成DOM节点。HTML和JavaScript分别放在页面对应位置,脚本应在这些元素存在后执行,例如放在body末尾。
<canvas id="test-canvas" width="300" height="200">上下文示例</canvas><canvas id="test-webgl-canvas" width="300" height="200">WebGL示例</canvas><canvas id="test-shape-canvas" width="200" height="200">路径示例</canvas><canvas id="test-text-canvas" width="300" height="100">阴影文字示例</canvas>width/height属性设置绘图缓冲区大小;只改CSS尺寸可能拉伸像素。高DPI场景可按devicePixelRatio调整缓冲区与坐标变换,本例保持简单的1:1坐标。
const canvas = document.getElementById('test-canvas');const ctx = canvas.getContext('2d');if (!ctx) throw new Error('2D context unavailable');const webglCanvas = document.getElementById('test-webgl-canvas');const gl = webglCanvas.getContext('webgl');console.log(gl ? 'WebGL context available' : 'WebGL unavailable');同一画布成功取得一种上下文后不能再切换为另一种,故2D与WebGL使用不同元素。WebGL可能因浏览器、驱动或环境限制返回null;这里只展示取得上下文,不声称完成3D绘制。
图形块用独立块作用域,保留原Path2D的圆脸、嘴和眼睛路径。
{ const canvas = document.getElementById('test-shape-canvas'); const ctx = canvas.getContext('2d'); if (!ctx) throw new Error('2D context unavailable'); ctx.clearRect(0, 0, 200, 200); // 默认alpha上下文下清成透明 ctx.fillStyle = '#dddddd'; ctx.fillRect(10, 10, 130, 130); const path = new Path2D(); path.arc(75, 75, 50, 0, Math.PI * 2, true); path.moveTo(110, 75); path.arc(75, 75, 35, 0, Math.PI, false); path.moveTo(65, 65); path.arc(60, 65, 5, 0, Math.PI * 2, true); path.moveTo(95, 65); path.arc(90, 65, 5, 0, Math.PI * 2, true); ctx.strokeStyle = '#0000ff'; ctx.stroke(path);}{ const canvas = document.getElementById('test-text-canvas'); const ctx = canvas.getContext('2d'); if (!ctx) throw new Error('2D context unavailable'); ctx.fillStyle = '#fff'; ctx.fillRect(0, 0, 300, 100); ctx.shadowOffsetX = 2; ctx.shadowOffsetY = 2; ctx.shadowBlur = 2; ctx.shadowColor = '#ccc'; ctx.font = '28px Arial'; ctx.fillStyle = '#999'; ctx.fillText('带阴影的文字', 20, 40);}实际字体可能回退,像素结果不保证跨设备完全相同。参考:getContext与返回null条件。