使用drawImage()在画布上输出固定大小的图像? [英] Using drawImage() to output fixed size images on a canvas?

查看:391
本文介绍了使用drawImage()在画布上输出固定大小的图像?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用 drawImage() 300px X 380px 画布上输出完整尺寸的图像,无论源图像大小?

How do I use drawImage() to output full size images on a 300px X 380px canvas regardless of the source image size?

示例:

1)。如果图像< c $ c> 75px X 95px 我希望能够绘制它以适合 300px X 380px 画布。

1). If there is a image of 75px X 95px I want to be able to draw it to fit a 300px X 380px canvas.

2)。如果有图像 1500px X 1900px 能够绘制它以适合 300px X 380px 画布。

2). If there is a image of 1500px X 1900px I want to be able to draw it to fit a 300px X 380px canvas.

var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
var img=document.getElementById("myPic");
ctx.drawImage(img,10,10);

有哪些选项可以防止质量损失?

What options are available to prevent any quality loss?

推荐答案

要缩放图像以使其适合并不难,只需使用简单的宽高比和大小即可:

To scale the image to fit is not so hard, just use simple aspect ratio with the sizes:

var ratioX = canvas.width / image.naturalWidth;
var ratioY = canvas.height / image.naturalHeight;
var ratio = Math.min(ratioX, ratioY);

ctx.drawImage(image, 0, 0, image.naturalWidth * ratio, image.naturalHeight * ratio);

保持质量; 300x380的画布在打印时会显得很小,或者非常模糊。

To maintain quality; a canvas of 300x380 will either appear very tiny on print, or very blurry.

重要的是,将其中的数据保持为 target 分辨率。为此,请使用目标DPI(或更确切地说是PPI)来计算大小。您还需要提前知道300x380区域的尺寸(例如,英寸,厘米,毫米等)。

It's important to keep the data from it in the target resolution. To do this, calculate the size using the target DPI (or rather, PPI). You will also need to know in advance what size the 300x380 area represents (e.g. in either inches, centimeters, millimeters etc.).

例如:

如果目标PDF的PPI为300,并且画布表示3 x 3.8厘米(为简单起见),则宽度和高度像素为:

If the target PDF will have a PPI of 300, and the canvas represents 3 x 3.8 cm (just to keep it simple), then the width and height in pixel will be:

var w = (3 / 2.54) * 300;   // cm -> inch x PPI
var h = (3.8 / 2.54) * 300;

在画布的位图上使用此大小,然后使用CSS:

Use this size on canvas' bitmap, then scale down the element using CSS:

canvas.width = w|0;             // actual bitmap size, |0 cuts fractions
canvas.height = h|0;
canvas.style.width = "300px";   // size in pixel for screen use
canvas.style.height = "380px";

现在,您可以将画布直接用作PDF的图像源,同时保持PDF的打印质量(不过请记住,在任何情况下上传的小图像在任何情况下都无法提供高质量的打印效果。)

You can now use the canvas directly as an image source for the PDF while keeping print quality for the PDF (have in mind though, small images uploaded will not provide high print quality in any case).

当然,请先设置画布大小,然后使用以下代码顶部以绘制图像。

And of course, set the canvas size first, then use the code at top to draw in the image.

这篇关于使用drawImage()在画布上输出固定大小的图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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