简体   繁体   English

如何在HTML5 canvas,canvas.toDataURL()中保存大小为a * a的图像,并稍后以不同的大小a * a / 2a * 2a绘制它?

[英]How to save an image of size a*a in HTML5 canvas, canvas.toDataURL() and later draw it in different sizes, a*a / 2a*2a?

How to save a single image of size a * a using HTML5 canvas, canvas.toDataURL() and later draw it in different sizes, a * a / 2a * 2a without distortion? 如何使用HTML5 canvas, canvas.toDataURL()保存大小a * a的单个图像,并稍后以不同大小绘制它, a * a / 2a * 2a而不会变形?

OR 要么

I have a HTML5 / JavaScript web application. 我有一个HTML5 / JavaScript网络应用程序。 There is an item catalogue, in which when I add a new item, I add an image of the item using HTML5 canvas: 有一个商品目录,在其中添加新商品时,会使用HTML5画布添加该商品的图片:

<canvas id="canvasnew" height="100" style="border:1px dotted" width="100"></canvas>

This 100 * 100 image is converted to $('#canvasnew')[0].toDataURL() and saved in my database. 这幅100 * 100图像被转换为$('#canvasnew')[0].toDataURL()并保存在我的数据库中。 And the image is later drawn into another canvas like this: 然后将图像绘制到另一个画布中,如下所示:

var ctx = $(this.el).find('#canvas')[0].getContext('2d');
var img = new Image;
img.onload = function () {
    ctx.drawImage(img, 0, 0);
};
img.src = this.model.toJSON().ImageUrl;`

this.model.toJSON().ImageUrl gets the image (size 100 * 100 )saved in dataUrl form. this.model.toJSON().ImageUrl获取以dataUrl格式保存的图像(大小为100 * 100 )。 Now, I need to draw this same image into one more canvas of size 400 * 400 without distortion. 现在,我需要将该同一图像绘制到另一个尺寸为400 * 400画布中而不会变形。 How do I do this? 我该怎么做呢?

Try this: 尝试这个:

ctx.drawImage(img, 0, 0, 400, 400);

drawImage accepts up to 9 parameters, the first 5 being : drawImage最多接受9个参数, 前五个是

  1. The image, 图片,
  2. x position, x位置,
  3. y position, y位置,
  4. width, 宽度,
  5. height. 高度。

So: drawImage(img, x, y, width, height); 所以: drawImage(img, x, y, width, height);

Stretching a image like that will, however, always result in some sort of distortion, due to "new" pixels having to be calculated / interpolated. 但是,由于必须计算/插值“新”像素,因此拉伸图像始终会导致某种形式的失真。 Some interpolation algorithms are more efficient, or result in better images than others, but so far the canvas has limited support for different algorithms. 一些插值算法比其他插值算法更有效,或产生更好的图像,但是到目前为止, canvas对不同算法的支持有限。 ( Take a look here for some more information ) 在这里查看更多信息

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM