LoginSignup
18
16

More than 3 years have passed since last update.

【問題】アスペクト比を維持して画像を表示【JavaScript,Canvas】

Last updated at Posted at 2017-06-09

問題

画像をアスペクト比を維持しながら引き延ばしてcanvasの中央に描画しなさい。
また、画像が表示されない箇所は黒く塗りつぶしなさい。
※画像はcanvasとはアスペクト比が異なるものを用意してください。

ダウンロード.png

解答例

function onLoadBody() {
    var ctx = document.getElementById('canvas').getContext('2d'),
        img = new Image();
    img.src = "img/test1.png";
    img.onload = function() {
        var canvasAspect = ctx.canvas.width / ctx.canvas.height, // canvasのアスペクト比
            imgAspect = img.width / img.height, // 画像のアスペクト比
            left, top, width, height;

        ctx.fillStyle = "black";
        ctx.fillRect(0, 0, ctx.canvas.width, ctx.canvas.height);

        if(imgAspect >= canvasAspect) {// 画像が横長
            left = 0;
            width = ctx.canvas.width;
            height = ctx.canvas.width / imgAspect;
            top = (ctx.canvas.height - height) / 2;
        } else {// 画像が縦長
            top = 0;
            height = ctx.canvas.height;
            width = ctx.canvas.height * imgAspect;
            left = (ctx.canvas.width - width) / 2;
        }
        ctx.drawImage(img, 0, 0, img.width, img.height, 
            left, top, width, height);
    };
}

解説

canvasのアスペクト比と画像のアスペクト比を求めます。
画像の方が横長の場合、canvasの上下に隙間ができますよね。
その隙間を計算します。
画像のほうが縦長の場合、canvasの左右に隙間ができますよね。
その隙間を計算します。

18
16
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
18
16