canvas – 色
図形の色について試します。
パスの内側を塗りつぶす
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>テストHTML</title>
</head>
<body>
<canvas id="canvas"></canvas>
<script>
// canvasのDOMを取得
const canvas = document.getElementById('canvas');
// getContextメソッドでコンテキストを取得
// ここでは2次元の平面的な図形を扱うので、引数に「2d」を指定
const ctx = canvas.getContext('2d');
// コンテキストのstyleを定義
// パスの開始
ctx.beginPath();
// 長方形
ctx.moveTo(10, 10);
ctx.rect(30, 30, 100, 60);
// 色を指定する
ctx.fillStyle = "#339999";
// パスを色と線を描画する
ctx.fill();
</script>
</body>
</html>
画面にアクセスすると長方形のパスにそって内側に色が描画されます。
パスを塗りつぶす
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>テストHTML</title>
</head>
<body>
<canvas id="canvas"></canvas>
<script>
// canvasのDOMを取得
const canvas = document.getElementById('canvas');
// getContextメソッドでコンテキストを取得
// ここでは2次元の平面的な図形を扱うので、引数に「2d」を指定
const ctx = canvas.getContext('2d');
// コンテキストのstyleを定義
// パスの開始
ctx.beginPath();
// 長方形
ctx.moveTo(10, 10);
ctx.rect(30, 30, 100, 60);
// 色を指定する
ctx.strokeStyle = "#000000";
// パスを色と線を描画する
ctx.stroke();
</script>
</body>
</html>
画面にアクセスすると長方形のパスに色が描画されます。
パスとパスの内側を塗りつぶす
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>テストHTML</title>
</head>
<body>
<canvas id="canvas"></canvas>
<script>
// canvasのDOMを取得
const canvas = document.getElementById('canvas');
// getContextメソッドでコンテキストを取得
// ここでは2次元の平面的な図形を扱うので、引数に「2d」を指定
const ctx = canvas.getContext('2d');
// コンテキストのstyleを定義
// パスの開始
ctx.beginPath();
// 長方形
ctx.moveTo(10, 10);
ctx.rect(30, 30, 100, 60);
// 色を指定する
ctx.fillStyle = "#339999";
ctx.strokeStyle = "#000000";
// パスを色と線を描画する
ctx.fill();
ctx.stroke();
</script>
</body>
</html>
画面にアクセスすると長方形のパスの内側とパスそのものに色が描画されます。
パスとパスの内側を塗りつぶす(透明度の設定)
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>テストHTML</title>
</head>
<body>
<canvas id="canvas"></canvas>
<script>
// canvasのDOMを取得
const canvas = document.getElementById('canvas');
// getContextメソッドでコンテキストを取得
// ここでは2次元の平面的な図形を扱うので、引数に「2d」を指定
const ctx = canvas.getContext('2d');
// コンテキストのstyleを定義
// パスの開始
ctx.beginPath();
// 長方形
ctx.moveTo(10, 10);
ctx.rect(30, 30, 100, 60);
// 色を指定する
ctx.fillStyle = 'rgba(255, 0, 0, 0.3)';
ctx.strokeStyle = 'rgba(0 , 0, 255, 0.3)';
// パスを色と線を描画する
ctx.fill();
ctx.stroke();
</script>
</body>
</html>
画面にアクセスすると長方形のパスの内側とパスそのものに色が描画されます。
透明度の指定は、RGBと透明度の組み合わせで指定しています。
rgba(R, G, B, A)
サンプルの場合は、パスもパスの内側も0.2の透明度なので、描画された図形は薄く見えます。