FabricioG
FabricioG

Reputation: 3320

Resize a current canvas image after one has already been created

I'm trying to create a smaller thumbnail of an image on a canvas. The thumbnail size I'd like is 200 x 200 According to the documentation it should be as easy as drawImage(img, 0, 0, 200, 200) but I get the same results here is my code:

_canvas = document.createElement('canvas'),
ctx = _canvas.getContext("2d"),
img = new Image();

img.onload = function() {
ctx.drawImage(this, 0, 0, 1200, 600);
var dataURL = _canvas.toDataURL();

// The above creates the first image 
//Then while I'm still in the load method I attempt to save another size:

ctx.drawImage(this,0,0,300,300);
var dataThumbURL = _canvas.toDataURL();

}

I save both dataURL and dataThumbURL to the server and both images are the same size. My assumption is ctx.drawImage could be repeated with just a different size. Any idea how I can achieve this?

Upvotes: 0

Views: 35

Answers (1)

obscure
obscure

Reputation: 12891

The width and height parameters of the drawImage() method do not alter the dimensions of the canvas you draw onto. So if your source image is bigger than the canvas it will simply be cropped.

To have snapshots of different sizes, you need to change the dimensions of the canvas to the desired size prior calling drawImage().

Here's an example:

let image = new Image();
let _canvas = document.createElement('canvas');
let ctx = _canvas.getContext("2d");
image.crossOrigin = "";
image.onload = function() {
  let img, dataURL;
  _canvas.width = 200;
  _canvas.height = 150;
  ctx.drawImage(this, 0, 0, _canvas.width, _canvas.height);
  dataURL = _canvas.toDataURL();
  img = new Image();
  document.body.appendChild(img);
  img.src = dataURL;

  _canvas.width = 40;
  _canvas.height = 30;
  ctx.drawImage(this, 0, 0, _canvas.width, _canvas.height);
  dataURL = _canvas.toDataURL();
  img = new Image();
  document.body.appendChild(img);
  img.src = dataURL;
}

image.src = "https://api.codetabs.com/v1/proxy?quest=https://picsum.photos/id/237/200/300";

Upvotes: 1

Related Questions