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

Canvasで画像を縮小したいのだけど、MobileSafariでは大きな画像に関して取得される高さが小さくなっているらしい時

More than 5 years have passed since last update.

大きな画像を選んでCanvasで縮小すると、下の方が真っ黒になってあれあれ?となってしまうと思う。

※コメント戴いた内容から、下記の話題へ続く。
http://qiita.com/ms2sato/items/d1e6a58b23af41e0090a

iOS6からのバグの様子。下記を参考にすべし。
http://stackoverflow.com/questions/11929099/html5-canvas-drawimage-ratio-bug-ios

コード保全のため一応転載。

/**
 * Detecting vertical squash in loaded image.
 * Fixes a bug which squash image vertically while drawing into canvas for some images.
 * This is a bug in iOS6 devices. This function from https://github.com/stomita/ios-imagefile-megapixel
 * 
 */
function detectVerticalSquash(img) {
    var iw = img.naturalWidth, ih = img.naturalHeight;
    var canvas = document.createElement('canvas');
    canvas.width = 1;
    canvas.height = ih;
    var ctx = canvas.getContext('2d');
    ctx.drawImage(img, 0, 0);
    var data = ctx.getImageData(0, 0, 1, ih).data;
    // search image edge pixel position in case it is squashed vertically.
    var sy = 0;
    var ey = ih;
    var py = ih;
    while (py > sy) {
        var alpha = data[(py - 1) * 4 + 3];
        if (alpha === 0) {
            ey = py;
        } else {
            sy = py;
        }
        py = (ey + sy) >> 1;
    }
    var ratio = (py / ih);
    return (ratio===0)?1:ratio;
}

/**
 * A replacement for context.drawImage
 * (args are for source and destination).
 */
function drawImageIOSFix(ctx, img, sx, sy, sw, sh, dx, dy, dw, dh) {
    var vertSquashRatio = detectVerticalSquash(img);
    ctx.drawImage(img, sx, sy, sw, sh, dx, dy, dw, dh / vertSquashRatio);
}

上記をどこかに定義しておいて下記のように変更してみると良い。

    //context.drawImage(img, 0, 0, canvaswidth, canvasheight); //これはダメだった
    drawImageIOSFix(context, img, 0, 0, width, height, 0, 0, canvaswidth, canvasheight);
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