Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

194
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda