HTML5全体を埋める方法 <canvas>を1つの色で。
私はこのようないくつかの解決策を見ましたCSSを使用して背景色を変更するが、キャンバスが透明なままであるため、これは適切な解決策ではありません。変更されるのは、占有するスペースの色だけです。
もう1つは、キャンバス内の色で何かを作成することです。たとえば、長方形(ここを参照)ですが、それでもキャンバス全体が色で塗りつぶされません(キャンバスが作成した形状よりも大きい場合)。
キャンバス全体を特定の色で塗りつぶす解決策はありますか?
回答:
はい、キャンバス全体に無地の長方形を塗りつぶし、キャンバス自体のheightとwidthを使用します。
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">
背景を明示的に作成する場合は、キャンバス上の現在の要素の背後に描画することを確認する必要があります。
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);
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>
キャンバスグラフィックス用のライブラリ全体があります。これはp5.jsと呼ばれます。head要素に1行だけ追加し、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);
}
p5.jsされ340kBminiziedとgzipで圧縮されました!このページにはもう少し軽量なオプションが含まれていると思います。