文本显示两次

问题描述 投票:0回答:1

当我尝试向 p5.js 画布添加文本时,由于某种原因它显示了两次。下面附上代码:

let img;

function setup() {
    createCanvas(screen.availWidth, screen.availHeight);
    img = loadImage('https://mediumpurpleperfumeddegrees.boyuan12.repl.co/circuit1.webp');
    textOutput();
}

function draw() {
     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);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.6.0/p5.js"></script>

Output p5.js 草图

我试图查看文档,但发现没有太大帮助。

javascript processing p5.js
1个回答
0
投票

draw()
每秒运行多次,用于动画。通常,你想在重绘之前清除屏幕,否则你可能会得到重影。

您正在

setup
中加载图像,它不会在启动
draw()
循环之前等待图像显示。最初,
img.width
是 1 几帧,然后图像加载并且它变成任何图像的宽度,200 左右。
draw()
运行不清晰和异步图像加载的组合导致文本显示在两个地方。

相反,使用

preload
避免在图像准备好之前绘制任何东西,并使用
noLoop()
禁用动画循环或使用
background()
clear()
draw()
的顶部擦除陈旧的图纸。

let img;

function preload() { // fix 1
  img = loadImage(
    "https://mediumpurpleperfumeddegrees.boyuan12.repl.co/circuit1.webp"
  );
}

function setup() {
  createCanvas(screen.availWidth, screen.availHeight);
  textOutput();
  noLoop(); // fix 2
}

function draw() {
  // clear() // alternative to noLoop() if you want animation
  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);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.6.0/p5.js"></script>

© www.soinside.com 2019 - 2024. All rights reserved.