简体   繁体   中英

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>

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()">

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM