缩放图像以适合画布 [英] Scaling an image to fit on canvas

查看:29
本文介绍了缩放图像以适合画布的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个允许用户上传图片的表单.

I have a form that allows a user to upload an image.

加载图像后,我们会对其进行一些缩放,以在将其传回服务器之前减小其文件大小.

Once the image is loaded, we perform some scaling on it in order to reduce its filesize before we pass it back to the server.

为此,我们将它放在画布上并在那里操作.

To do this, we place it on the canvas and manipulate it there.

此代码将在画布上呈现缩放后的图像,画布大小为 320 x 240 像素:

This code will render the scaled image on the canvas, with the canvas of size 320 x 240px:

ctx.drawImage(img, 0, 0, canvas.width, canvas.height)

... 其中 canvas.width 和 canvas.height 是图像的高度和宽度 x 基于原始图像大小的缩放因子.

... where canvas.width and canvas.height is the image height and width x a scaling factor based on the size of the original image.

但是当我去使用代码时:

But when I go to use the code:

ctx.drawImage(img, 0, 0, canvas.width, canvas.height, 0, 0, canvas.width, canvas.height

... 我只得到画布上图像的一部分,在这种情况下是左上角.尽管实际图像尺寸大于 320x240 画布尺寸,但我需要缩放"整个图像以适合画布.

... I only get part of the image on the canvas, in this case the top left corner. I need the whole image 'scaled' to fit on the canvas, despite the actual image size being larger than the 320x240 canvas size.

所以对于上面的代码,宽度和高度都是 1142x856,因为这是最终的图像尺寸.我需要保持这个大小,以便在提交表单时传递给服务器,但只希望它的较小视图出现在用户的画布中.

So for the code above, the width and heights are 1142x856, as that is the final image size. I need to maintain that size to pass beck to the server when the form is submitted, but only want a smaller view of it to appear in the canvas for the user.

我在这里错过了什么?任何人都可以指出我正确的方向吗?

What am I missing here? Can anyone point me in the right direction please?

非常感谢.

推荐答案

提供源图片(img)大小作为第一个矩形:

Provide the source image (img) size as the first rectangle:

ctx.drawImage(img, 0, 0, img.width,    img.height,     // source rectangle
                   0, 0, canvas.width, canvas.height); // destination rectangle

第二个矩形将是目标大小(源矩形将被缩放到的大小).

The second rectangle will be the destination size (what source rectangle will be scaled to).

2016/6 更新:有关纵横比和定位(ala CSS 的cover"方法),请查看:
模拟背景尺寸:画布封面

Update 2016/6: For aspect ratio and positioning (ala CSS' "cover" method), check out:
Simulation background-size: cover in canvas

这篇关于缩放图像以适合画布的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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