文本重复 | p5.js

问题描述 投票: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);
}

Output p5.js 草图

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

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

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

在您的情况下,您使用的是

screen.availWidth
,它会在图像加载后发生变化。您还在
setup
中加载图像,它不会在开始
draw()
循环之前等待图像显示,因此您在两个不同的地方获得 100 欧姆。

相反,使用

preload
并禁用动画循环或使用
background()
clear()
擦除陈旧的图纸。

let img;

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

function setup() {
  createCanvas(screen.availWidth, screen.availHeight);
  textOutput();
}

function draw() {
  noLoop();
  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.