How Can I Make Background Color Of Canvas White With Javascript?
What I want to do I want to know how to make background color white. I built a drawing app with canvas. You can download the canvas image you have drawn by clicking the Download
Solution 1:
You can use the following code to set background color of canvas.
var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");
context.fillStyle = "green";
context.fillRect(0, 0, canvas.width, canvas.height);
canvas{ border: 1px solid black; }
<canvaswidth=300height=150id="canvas">
Solution 2:
On a canvas you can use getAttribute()
to retrieve the dimension. Look at my snippet:
let canvas = document.getElementById('canvas');
let cheight = parseInt(canvas.getAttribute("height"));
let cwidth = parseInt(canvas.getAttribute("width"));
let context = canvas.getContext('2d');
context.fillStyle = "green";
context.fillRect(0,0,cwidth,cheight);
<canvaswidth="200"height="200"id="canvas">
Solution 3:
In your draw()
function you need to add specifically the background like this:
const canvas = document.querySelector('#draw');
const ctx = canvas.getContext('2d');
ctx.strokeStyle = '#BADA55';
ctx.fillStyle = "#ffffff"; //HERE, use HEX format in 6 digits
ctx.fillRect(0, 0, canvas.width, canvas.height); //HERE
...
functiondraw(e) {
...
}
Why?
You need to draw the background before everything, otherwise drawing the background over and over, or also above everything would result in the white rectangle overlapping everything on your canvas.
Here is a LIVE DEMO.
Post a Comment for "How Can I Make Background Color Of Canvas White With Javascript?"