2
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

HTML canvasをCSS Flex, Grid Layoutに組み込む方法

Posted at

#基本形

index.html
<div class="wrapper">
    <canvas class="canvas"></canvas>
</div>
style.css
.wrapper {
    position: relative;
    width: 100%;
    height: 100%;
}

.canvas {
    position: absolute;
    width: 100%;
    height: 100%;
}

#例) フルスクリーンの場合

See the Pen by hu (@hushad903) on CodePen.

#例) フレックスレイアウトに組み込む場合

See the Pen canvas-flex by hu (@hushad903) on CodePen.

#例) グリッドレイアウトに組み込む場合

See the Pen canvas-grid by hu (@hushad903) on CodePen.

#残りの話

canvas本来のサイズとレイアウトされた結果のサイズは当然異なるので、そこのところの処理をobject-fitで適当に指定する必要がある。

もしくは以下のようにcanvasのサイズを変更してしまう。

index.js
const canvas = // canvas取得
canvas.width = canvas.clientWidth;
canvas.height = canvas.clientHeight;

window.onresize = () => {
    canvas.width = canvas.clientWidth;
    canvas.height = canvas.clientHeight;
    // canvas再描画
}

ちなみに基本形のCSSを用いずにcanvasのサイズを変更するのみだとリサイズ後にレイアウトが崩れてうまく行かない(と思う)。

2
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?