如何用特定的颜色填充整个画布

时间:2015-01-02 01:09:33

标签: javascript html5 canvas

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

我看到了this等一些解决方案来改变背景颜色,但这不是一个好的解决方案,因为画布保持透明,唯一改变的是它占据的空间的颜色。

另一个是通过在画布中创建具有颜色的东西,例如矩形(see here),但它仍然没有用颜色填充整个画布(如果画布大于形状我们创建)。

是否有解决方案用特定颜色填充整个画布?

5 个答案:

答案 0 :(得分:94)

是的,只需在画布上填充一个纯色的矩形,使用画布本身的heightwidth

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

答案 1 :(得分:3)

let canvas = document.getElementById('canvas');
canvas.setAttribute('width', window.innerWidth);
canvas.setAttribute('height', window.innerHeight);
let ctx = canvas.getContext('2d');

//Draw Canvas Fill mode
ctx.fillStyle = 'blue';
ctx.fillRect(0,0,canvas.width, canvas.height);
* { margin: 0; padding: 0; box-sizing: border-box; }
body { overflow: hidden; }
<canvas id='canvas'></canvas>

答案 2 :(得分:0)

您知道吗,有一个完整的画布图形库。它叫做p5.js 您可以在head元素中仅添加一行并添加一个sketch.js文件。 首先对您的html和body标签进行

<html style="margin:0 ; padding:0">
<body style="margin:0 ; padding:0">

将此添加到您的头部:

<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.6.1/p5.js"></script>
<script type="text/javascript" src="sketch.js"></script>

sketch.js文件

function setup() {
  createCanvas(windowWidth, windowHeight);
background(r, g, b);
  }

答案 3 :(得分:0)

如果要明确显示背景,则必须确保在画布上的当前元素后面绘制

var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
// Add behind elements.
ctx.globalCompositeOperation = 'destination-over'
// Now draw!
ctx.fillStyle = "blue";
ctx.fillRect(0, 0, canvas.width, canvas.height);

答案 4 :(得分:0)

我们不需要访问画布上下文。

在纯JS中实施hednek会得到cutLongest [xs, ys] $ zipWith (++) (map pure xs ++ repeat []) (map pure ys ++ repeat []) 。但是我的首选方法需要将 kabab-case 转换为 camelCase

pkg-config opencv --libs

相关问题