Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

195
Views
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?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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";

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!