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

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

问题描述

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



图片加载完成后,我们会对其进行缩放,以减少文件大小我们将它传回给服务器。



要做到这一点,我们把它放在画布上并在那里操作。



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

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

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



但是当我使用代码:

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

...我只能得到画布上的图像的一部分, 。我需要整个图像缩放以适合在画布上,尽管实际图像大小大于320x240的画布大小。



所以对于上面的代码,宽度和高度为1142x856,因为这是最终的图像大小。我需要保持该大小,以便在提交表单时将beck传递给服务器,但只需要一个较小的视图显示在用户的画布中。



我在这里缺少什么?

解决方案



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

  ctx.drawImage(img, 0,img.width,img.height,// source rectangle 
0,0,canvas.width,canvas.height); //目标矩形

第二个矩形将是目标大小



更新2016/6 :对于宽高比和定位(ala CSScover方法),请查看:

模拟背景大小:在canvas中覆盖 a>


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.

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)

... 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

... 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.

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?

Many thanks in advance.

解决方案

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).

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

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

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