LoginSignup
15
11

More than 5 years have passed since last update.

canvasで画像をトリミングする

Last updated at Posted at 2016-05-04

デモ:http://mo49.tokyo/qiita/20160504/trim.html

imgは読み込んだ後でないとwidth, heightがとれないので、img.onloadの中で描画する。
もしくはdomとしてあらかじめ用意。display:none;で消しておく。

trim.js
// トリミングしてcanvas要素に描画して返す関数
function trimImage (imgSrc) {

    var TRIM_SIZE = 300;
    var canvas = document.createElement('canvas');
    var ctx = canvas.getContext('2d');

    canvas.width = canvas.height = TRIM_SIZE;
    canvas.id = 'canvas-photo';

    var img = new Image();
    img.src = imgSrc + '?' + (new Date).getHours(); // IE対策

    // imgは読み込んだ後でないとwidth,heightが0
    img.onload = function() {
        // 横長か縦長かで場合分けして描画位置を調整
        var width, height, xOffset, yOffset;
        if (img.width > img.height) {
            height = TRIM_SIZE;
            width = img.width * (TRIM_SIZE / img.height);
            xOffset = -(width - TRIM_SIZE) / 2;
            yOffset = 0;
        } else {
            width = TRIM_SIZE;
            height = img.height * (TRIM_SIZE / img.width);
            yOffset = -(height - TRIM_SIZE) / 2;
            xOffset = 0;
        }
        ctx.drawImage(img, xOffset, yOffset, width, height);
    };

    return canvas;
}

// トリミングしたcanvasを追加
var imgSrc = './img/test.jpg';
$('body').append( trimImage(imgSrc) );

正方形に切り抜くのではなく、画像の比率を保ったまま縮小させる場合は以下のようにやる。

resize.js
img.onload = function() {
    //縦横の縮小率を求める    
    var ratioWidth = canvas.width / img.width;
    var ratioHeight = canvas.height / img.width;
    //縮小率の小さい方を使う
    if (ratioWidth <= ratioHeight) {
        var ratio = ratioWidth;
    } else {
        var ratio = ratioHeight;
    }

    //リサイズ後のピクセル数を計算(縦横に同じ比率をかける) 
    var sizeWidth = Math.round(img.width * ratio);
    var sizeHeight = Math.round(img.height * ratio);        
    //中央値を求める
    var drawX = Math.round((canvas.width - sizeWidth) / 2);
    var drawY = Math.round((canvas.height - sizeHeight) / 2);

    //写真をcanvasに表示する
    ctx.drawImage(img,drawX,drawY,sizeWidth,sizeHeight);
}

参考
drawImage() メソッド
canvasに画像を描画しよう(トリミングやクリッピングも)

15
11
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
15
11