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
263 views
in Technique[技术] by (71.8m points)

javascript - How to fill the whole canvas with specific color?

How to fill the whole HTML5 <canvas> with one color.

I saw some solutions such as this to change the background color using CSS but this is not a good solution since the canvas remains transparent, the only thing that changes is the color of the space it occupies.

Another one is by creating something with the color inside the canvas, for example, a rectangle(see here) but it still does not fill the whole canvas with the color (in case the canvas is bigger than the shape we created).

Is there a solution to fill the whole canvas with a specific color?

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

Yes, fill in a Rectangle with a solid color across the canvas, use the height and width of the canvas itself:

var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
ctx.fillStyle = "blue";
ctx.fillRect(0, 0, canvas.width, canvas.height);
canvas{ border: 1px solid black; }
<canvas width=300 height=150 id="canvas">

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

...