You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

p5.js从文本输入框获取颜色名控制tint滤镜失效问题求助

错误原因

  • 你在setup()中仅执行了一次输入框值的读取,后续用户输入内容后colorss变量不会同步更新,导致非随机模式下tint()拿到的始终是初始空值
  • 未绑定触发submit()函数的交互入口,你现在写的submit()函数没有任何触发时机,代码不会自动执行
  • tint()的着色逻辑如果没有放在draw()中,页面重绘时效果会丢失,p5.js的draw()函数每秒执行60次刷新画布,所有需要持续生效的渲染配置都要放在这里

修复方案

首先给HTML补充提交触发入口,可选择加按钮或者绑定回车事件:

<input placeholder="Type color name OR type 'Random' for a random tint!" style="width: 340px; border-radius: 5px; border: 3px rgb(0, 0, 0) solid; background-color: rgb(197, 197, 197);" id="colors">
<button onclick="submit()" style="margin-left: 8px; padding: 3px 12px;">应用颜色</button>

修改后的JS代码:

let currentTint = ""; // 存储当前要应用的着色值

function preload() {

}

function setup() {
    const canvas = createCanvas(400, 400);
    canvas.position(480, 300);
    const video = createCapture(VIDEO);
    video.hide();

    // 如果需要按回车触发提交,可添加下面这段代码
    // document.getElementById('colors').addEventListener('keydown', e => {
    //     if(e.key === 'Enter') submit()
    // })
}

function draw() {
    image(video, 0, 0, 400, 400);
    // 着色逻辑放在draw中保证每帧渲染都生效
    currentTint ? tint(currentTint) : noTint();
}

function submit() {
    const inputVal = document.getElementById('colors').value.trim();
    if (inputVal === "Random") {
        const r = random(255);
        const g = random(255);
        const b = random(255);
        currentTint = color(r, g, b);
    } else if (inputVal) {
        // p5.js的color方法支持所有合法CSS颜色名
        currentTint = color(inputVal);
    }
}

内容的提问来源于stack exchange,提问作者Rameen Humayun

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 10:42:01