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()">
2.1m questions
2.1m answers
60 comments
57.0k users