1

The code at the bottom should draw a cropped part of an image, keeping aspect ratio.

However, on iOS 6 and iOS 7 (only tried it on iPad mini and iPad retina), it squeezes the image vertically.

I know this is a known iOS6 bug when dealing with large images, but this seems to occur even on small images, the image in question is only 669 x 500, and on iOS7...

At first sight I can workaround this by not cropping the image, but setting a clipping rectangle on the canvas, then drawing the full image with scaling and rotation, counter translating the image, but I have no idea if that always works...

Also, I noticed the problem does not occur when the scaling factors are above 0.5, so this indeed indicates that it is again Apple's subsampling algoritm that is causing this scaling problems. Note that the image size if very important, it fails for 669x500, but amazingly it works for 670x500! It seems that any odd width fails, an even widths work fine.

Anyone has a solution for this? We could use the megapix-image js library, but since we need draw many small images, this would be rather slow.

Thanks, Peter

<html>
<body>
    Left and right image should be the same, but on iOS, the left image is vertically squeezed
    <br/>
    <canvas id="canvas" width="980" height="709"></canvas>
</body>
<script>
    var img = document.createElement('img');
    img.onload = function () {
        var canvas = document.getElementById('canvas');
        var context = canvas.getContext('2d');

        // The scaling problem does not occur when scale is larger than 0.5
        var scale = 0.4;

        // Cropping it this way does not work on iOS, but works on all other browsers
        context.drawImage(img, 0, 0, 500, 500, 0, 0, 500 * scale, 500 * scale);

        // Cropping the image using a clipping rect seems to do the job on iOS, but might be slower.
        context.beginPath();
        context.rect(400, 0, 500 * scale, 500 * scale);
        context.clip();
        context.drawImage(img, 0, 0, img.width, img.height, 400, 0, img.width * scale, img.height * scale);
    };
    // The problem occurs for 669x500, it works for 670x500!
    img.src = "http://lorempixel.com/669/500/";
</script>
</html>
4

0 回答 0