p5.js画布文本重复显示问题排查求助
问题原因排查
1. draw() 循环执行导致重复绘制
p5.js 的 draw() 函数默认以约60帧/秒的频率持续循环调用。你的代码在每次循环中都会重复绘制文本,即使位置固定,多次叠加也会造成视觉上的重影、模糊等"重复显示"效果。
2. 异步图像加载的时序问题
loadImage() 是异步操作,setup() 执行后 draw() 会立即启动,此时图像尚未加载完成,img.width 和 img.height 为0,导致文本绘制位置计算错误;同时 image() 不会渲染任何内容,文本直接画在空白画布上。等图像加载完成后,新绘制的文本和之前错误位置的文本叠加,进一步加重重复问题。
3. 缺少画布清屏操作
每次 draw() 循环没有清除画布旧内容,之前绘制的文本(包括图像加载前的错误位置文本)会持续保留,和新内容叠加显示。
解决建议
方案1:添加清屏操作(通用场景)
在 draw() 开头添加 background() 或 clear(),确保每次循环从干净的画布开始,同时判断图像加载状态避免错误绘制:
let img; function setup() { createCanvas(screen.availWidth, screen.availHeight); img = loadImage('https://mediumpurpleperfumeddegrees.boyuan12.repl.co/circuit1.webp'); } function draw() { background(255); // 用白色清空画布,可按需调整颜色 if (img.loaded) { // 确保图像加载完成后再绘制 image(img, screen.availWidth / 2 - img.width, 0, img.width * 1.25, img.height * 1.25); textSize(20); text('5V', screen.availWidth / 2 - img.width - 20, img.height / 2 + 30); text('50Ω', screen.availWidth / 2 - img.width + 100, img.height / 2 - 45); text('100Ω', screen.availWidth / 2 - img.width + 220, img.height / 2 + 50); } }
方案2:仅绘制一次(静态场景适用)
如果内容是静态的,不需要循环更新,可在图像加载完成后一次性绘制并停止循环:
let img; function setup() { createCanvas(screen.availWidth, screen.availHeight); img = loadImage('https://mediumpurpleperfumeddegrees.boyuan12.repl.co/circuit1.webp', () => { // 图像加载完成后执行绘制 image(img, screen.availWidth / 2 - img.width, 0, img.width * 1.25, img.height * 1.25); textSize(20); text('5V', screen.availWidth / 2 - img.width - 20, img.height / 2 + 30); text('50Ω', screen.availWidth / 2 - img.width + 100, img.height / 2 - 45); text('100Ω', screen.availWidth / 2 - img.width + 220, img.height / 2 + 50); }); } function draw() { noLoop(); // 停止循环,仅执行一次 }
方案3:用标志位控制绘制时机
设置标志位,仅在图像加载完成后执行绘制逻辑:
let img; let isImgLoaded = false; function setup() { createCanvas(screen.availWidth, screen.availHeight); img = loadImage('https://mediumpurpleperfumeddegrees.boyuan12.repl.co/circuit1.webp', () => { isImgLoaded = true; }); } function draw() { if (!isImgLoaded) return; // 图像未加载时直接返回 background(255); image(img, screen.availWidth / 2 - img.width, 0, img.width * 1.25, img.height * 1.25); textSize(20); text('5V', screen.availWidth / 2 - img.width - 20, img.height / 2 + 30); text('50Ω', screen.availWidth / 2 - img.width + 100, img.height / 2 - 45); text('100Ω', screen.availWidth / 2 - img.width + 220, img.height / 2 + 50); }
内容的提问来源于stack exchange,提问作者boyuan12
相关产品推荐
相关产品推荐

