Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
109 views
in Technique[技术] by (71.8m points)

javascript - Changing background color of canvas

On canvas, I have a rectangle that has white as default color and I want to change its color by using a color picker that stores the color in a textbox. If user types in a color name, value or the input color picker it should change.

I don't understand why my code doesn't work at all. Could you help me?

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>
question from:https://stackoverflow.com/questions/65651547/changing-background-color-of-canvas

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

when calling the function change_background_color you have to use parentheseis too like this

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...