在 Canvas 中修改文本颜色需先清空画布再重绘,直接修改 fillStyle 不会自动刷新已绘制内容;本文详解如何通过 clearRect() 和封装绘图逻辑实现点击切换颜色。
在 Canvas 中修改文本颜色需先清空画布再重绘,直接修改 `fillStyle` 不会自动刷新已绘制内容;本文详解如何通过 `clearRect()` 和封装绘图逻辑实现点击切换颜色。
Canvas 是一个位图渲染环境,其绘制操作是“一次性”的——一旦调用 fillText() 将文字渲染到画布上,它就成为像素数据的一部分,不会响应后续对 fillStyle、font 等上下文属性的修改。因此,仅更改 context.fillStyle = 'blue' 并不能让已绘制的文字变色,必须主动清除旧内容并重新绘制。
核心步骤有三:
以下为优化后的完整实现:
<!doctype html><html><head><style>#my-canvas { border: 1px solid #ccc; }</style></head><body><canvas id="my-canvas" width="300" height="100"></canvas><br><button onclick="changeColor('blue')">变蓝</button><button onclick="changeColor('green')">变绿</button><button onclick="changeColor('orange')">变橙</button><script>const canvas = document.querySelector('#my-canvas');const ctx = canvas.getContext('2d');// 封装绘图逻辑,支持传入颜色参数function drawText(color) {ctx.clearRect(0, 0, canvas.width, canvas.height); // 关键:每次重绘前清空ctx.font = '48px "Segoe UI", sans-serif';ctx.fillStyle = color;ctx.textBaseline = 'middle'; // 垂直居中对齐更美观ctx.fillText('Example text', 20, canvas.height / 2);}// 初始化绘制(红色)drawText('red');// 切换颜色函数,可复用function changeColor(newColor) {drawText(newColor);}</script></body></html>
通过结构化封装与明确的“清除–设置–绘制”流程,即可稳定、可扩展地实现 Canvas 内容的动态样式控制。