SVGとcanvasのレスポンシブ対応

以前にSVGのレスポンシブ対応の記事を投稿したことがありますが、その時の方法より簡単に対応できそうかつcanvasでもレスポンシブ対応できそうだったので、対応方法をメモ。

サンプルコード

まずはSVGの場合です。
今回は1600×900(16:9)のサイズのSVGを作成します。

<svg class="svg" width="1600" height="900" viewBox="0 0 1600 900">
  <rect width="1600" height="900" x="0" y="0" fill="black"></rect>
  <rect width="1500" height="800" x="50" y="50" fill="darkgray"></rect>
  <rect width="1400" height="700" x="100" y="100" fill="gray"></rect>
  <rect width="1300" height="600" x="150" y="150" fill="lightgray"></rect>
  <text x="800" y="450" text-anchor="middle" font-size="72">テキスト</text>
</svg>

レスポンシブ対応として、aspect-ratioでSVGと同じ比率を指定すればOKです。

.svg {
  display: block;
  width: 100%;
  height: auto;
  aspect-ratio: 16 / 9;
}

これで画面幅に合わせてSVGが拡大・縮小されるようになりました。
SVGのレスポンシブ対応のデモページ

次にcanvasの場合を試してみます。
SVGの時と同じ1600×900のサイズです。

<canvas id="canvas" width="1600" height="900"></canvas>

SVGと同じような見た目になるように描画します。

var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');

ctx.fillStyle = 'black';
ctx.fillRect(0, 0, 1600, 900);
ctx.fillStyle = 'darkgray';
ctx.fillRect(50, 50, 1500, 800);
ctx.fillStyle = 'gray';
ctx.fillRect(100, 100, 1400, 700);
ctx.fillStyle = 'lightgray';
ctx.fillRect(150, 150, 1300, 600);

ctx.font = '72px serif';
ctx.fillStyle = 'black';
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
ctx.fillText('テキスト', 800, 450);

最後にCSSです。
SVGの時と同じく、aspect-ratioでcanvasの比率を指定します。

#canvas {
  display: block;
  width: 100%;
  height: auto;
  aspect-ratio: 16 / 9;
}

これでcanvasでもレスポンシブ対応ができました。
canvasのレスポンシブ対応のデモページ

このエントリーをはてなブックマークに追加

関連記事

コメントを残す

メールアドレスが公開されることはありません。
* が付いている欄は必須項目です

CAPTCHA


コメントが承認されるまで時間がかかります。

2024年7月
 123456
78910111213
14151617181920
21222324252627
28293031