1

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?

OR

I have a HTML5 / JavaScript web application. There is an item catalogue, in which when I add a new item, I add an image of the item using HTML5 canvas:

<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. 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. Now, I need to draw this same image into one more canvas of size 400 * 400 without distortion. How do I do this?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
dany
  • 1,801
  • 7
  • 27
  • 40

1 Answers1

0

Try this:

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

drawImage accepts up to 9 parameters, the first 5 being:

  1. The image,
  2. x position,
  3. y position,
  4. width,
  5. height.

So: 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. (Take a look here for some more information)

Community
  • 1
  • 1
Cerbrus
  • 70,800
  • 18
  • 132
  • 147