当在iOS Safari中缩放和绘制图像到画布时,宽度是正确的,但高度被压扁 [英] When scaling and drawing an image to canvas in iOS Safari, width is correct but height is squished

查看:1682
本文介绍了当在iOS Safari中缩放和绘制图像到画布时,宽度是正确的,但高度被压扁的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在加载图像,然后将该图像绘制到画布上。我也缩放图像下来适合画布。当我这样做,图像绘制在画布上适当的宽度,但高度大约是画布的实际高度的1/4。

I am loading an image and then drawing that image to a canvas. I am also scaling the image down to fit the canvas. When I do this, the image draws onto the canvas at the proper width but the height is about 1/4 of what the canvas' actual height is.

//Calculate height from canvas-to-image width ratio
var width = canvas.width;
var height = ( width / img.width ) * img.height;

//Draw scale image (This results in a squished height, despite "height" being correct)
context.drawImage( image, 0, 0, img.width, img.height, 0, 0, width, height );

即使 height 控制台),图像以更小的高度绘制到画布。

Even though height is correct (checked in console), the image draws to the canvas at a much smaller height.

此外,当我检查 canvas.width / canvas.height vs img.width / img.height 我得到: .707234 vs .707818

Also, when I check the ratio of the canvas.width / canvas.height vs img.width / img.height I get: .707234 vs .707818. That's so close it could not account for the huge height problem.

为什么会发生这种情况?如何解决此问题?

Why does this happen? How do I fix this?

编辑:在Chrome上,此确切代码显示正确。

On Chrome, this exact code shows correctly.

推荐答案

这是iOS Safari中的一个错误。说明如下: Mobile Safari呈现< ; img src =data:image / jpeg; base64 ...>

This is a bug in iOS Safari. It's described here: Mobile Safari renders <img src="data:image/jpeg;base64..."> scaled on Canvas?

解决方案在这里: https://github.com/stomita/ios-imagefile-megapixel

问题

如果你有一个非常高的分辨率(大于1024x1024)的图像,它将被子采样(减少16x像素的数量)。执行此操作时,Safari会引发一个错误,导致垂直高度过小。

If you have an image with very high resolution (greater than 1024x1024) it will be subsampled (reduces the number of pixels by 16x). When doing this, Safari introduces an error that results in a too-small vertical height.

解决方案

要解决这个问题,你需要小块的图像(就像从一个文件读取一个缓冲区块),调整垂直高度差,绘制一个临时画布,然后绘制临时画布像素到目标画布。

To solve, this, you take small chunks of the image (like reading from a file into a buffer in chunks), adjust for the vertical height differential, draw just those to a temporary canvas, and then draw that temporary canvas' pixels to the destination canvas.

这篇关于当在iOS Safari中缩放和绘制图像到画布时,宽度是正确的,但高度被压扁的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆