Help us understand the problem. What is going on with this article?

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

More than 1 year has passed since last update.

問題

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

ダウンロード.png

解答例

answer.js
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の左右に隙間ができますよね。
その隙間を計算します。

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away