本文介绍了如何用特定的颜色填充整个画布?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何用一种颜色填充整个HTML5 <canvas>.

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

我看到了一些解决方案,例如可以更改使用CSS设置背景颜色,但这不是一个好的解决方案,因为画布保持透明,唯一改变的是它所占用空间的颜色.

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?

推荐答案

是的,只需在画布上用纯色填充矩形,然后使用画布本身的heightwidth即可:

Yes, just 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">

这篇关于如何用特定的颜色填充整个画布?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 13:21
查看更多