gpt4 book ai didi

javascript - 更改 Canvas 的背景颜色

转载 作者:行者123 更新时间:2023-12-04 08:17:23 26 4
gpt4 key购买 nike

在 Canvas 上,我有一个默认颜色为白色的矩形,我想通过使用将颜色存储在文本框中的颜色选择器来更改其颜色。如果用户输入颜色名称、值或输入颜色选择器,它应该改变。
我不明白为什么我的代码根本不起作用。你可以帮帮我吗?

const canvas = document.getElementById("canvas");
canvas.width = window.innerWidth - 60;
canvas.height = 400;

let context = canvas.getContext("2d");

let start_background_color = "white";

context.clearRect(0, 0, window.innerWidth, window.innerHeight);
context.fillStyle = start_background_color;
context.fillRect(0, 0, window.innerWidth, window.innerHeight);

function change_background_color() {
let color = document.getElementById('colorInputColor').value;
//document.body.style.backgroundColor = color;
context.fillStyle = color;
context.fillRect(0, 0, window.innerWidth, window.innerHeight);
document.getElementById('colorInputText').value = color;
}
<input type="text" id="colorInputText">
<input type="color" class="color-picker" id="colorInputColor">
<input type="button" id="colorButton" value="Click to Change Color" onclick="change_background_color">
<canvas id="canvas"></canvas>

最佳答案

调用函数 change_background_color 时,您也必须像这样使用括号

<input type="button" id="colorButton" value="Click to Change Color" onclick="change_background_color()">

关于javascript - 更改 Canvas 的背景颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65651547/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com