Explain Codes LogoExplain Codes Logo

How to fill the whole canvas with specific color?

javascript
canvas
javascript-style-properties
web-development
Nikita BarsukovbyNikita Barsukov·Aug 29, 2024
TLDR

Apply color to your canvas like Van Gogh with his sunflowers by using fillStyle for the color and fillRect() to cover the entire area:

let ctx = canvas.getContext('2d'); ctx.fillStyle = 'red'; // Van Gogh loved this color ctx.fillRect(0, 0, canvas.width, canvas.height); // Just paint all over!

This makes Picasso worry as you are setting the canvas color and make the whole thing just sparkle with it.

Canvas configuration

Before going all out Bob Ross and starting the actual happy painting, give your <canvas> element some dimensions in HTML:

<canvas id="myCanvas" width="500" height="500"></canvas>

Get your brushes ready in JavaScript and then fill the canvas:

let canvas = document.getElementById('myCanvas'); // Brushes (named 'myCanvas') at the ready! let ctx = canvas.getContext('2d'); ctx.fillStyle = '#00FFFF'; // Let the cyan party start! ctx.fillRect(0, 0, canvas.width, canvas.height); // Paint like there's no tomorrow!

Without the annoying scrollbars, your new masterpiece will take center stage:

body, html { height: 100%; margin: 0; overflow: hidden; // No distractions, please! } canvas { display: block; // It's showtime! }

Dynamic canvas

The canvas can be as flexible as a yoga master. Just resize it to fit the window:

window.addEventListener('resize', resizeCanvas, false); // Mindfulness! function resizeCanvas() { canvas.width = window.innerWidth; canvas.height = window.innerHeight; fillCanvas('#123456'); // Yoga time with a new color! }

And if padding or borders are in play, bring them under control with:

box-sizing: border-box; // 'Cause size matters!

Overpainting and layers

Playing with existing canvases? Use the globalCompositeOperation property and challenge your inner Michelangelo:

ctx.globalCompositeOperation = 'destination-over'; // Behind the scenes action ctx.fillStyle = 'green'; // And the color is... ctx.fillRect(0, 0, canvas.width, canvas.height); // Ta-dah!

You're not just painting here. You're creating layered masterpieces.

The CSS way

For a change, do the paint job without JavaScript. Simple, yet effective:

canvas { background-color: #FFD700; // The Midas touch! }

For dynamically changing the canvas color, switch back to JavaScript:

canvas.style.backgroundColor = 'lightblue'; // Hmm, soothing...

Remember, JavaScript style properties love the camel! (read camelCase)