Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

193
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda