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

351
Visualizações
How to crop images when placing them on an HTML5 canvas?

I want to add images to an HTML5 canvas in a grid pattern. The canvas is square but the images are of various sizes and aspect ratios. I want to crop all the images into squares.

I have the algorithm to place the images onto the canvas as squares but the images are stretched / squeezed.

grid

How to crop the landscape and or portrait images into squares.

Here is the algorithm:

const ctx = canvas.getContext("2d");
for (let xCell = 0; xCell < 5; xCell++) {
  for (let yCell = 0; yCell < 5; yCell++) {
    const x = xCell * 200;
    const y = yCell * 200;
    const img = new Image();
    img.onload = function() {
      // how to crop into squares?
      ctx.drawImage(img, x, y, 200, 200);
    };
    img.src = 'https://source.unsplash.com/random';
  }
}

How to crop the images: crop1 crop2

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

Your nested for loops execute img.onload and img.src = 'https://source.unsplash.com/random'; 25 times.

let ii = 0;
for (let xCell = 0; xCell < 5; xCell++) {
  for (let yCell = 0; yCell < 5; yCell++) {
    console.log(++ii + ": ", xCell, yCell);
  }
}


Here's one way to use four predetermined x,y coordinate groups:

[[0,0],[200,0],[0,200],[200,200]].forEach(function ([x,y]) {
    console.log(x,y);
});

To crop and place an image in an HTML Canvas element you need to use all available drawImage() parameters. First crop (and resize if necessary) the image you're loading, then place it on the canvas.

drawImage(image, 

    // source image crop and resize
    // sx, sy = upper left coordinates of crop location
    // sWidth, sHeight = dimensions of crop
    sx, sy, sWidth, sHeight, 

    // placement of image on canvas
    // dx, dy = upper left coordinates of placement
    // dWidth, dHeight = dimensions of placement on canvas
    dx, dy, dWidth, dHeight

)

For example:

const ctx = document.querySelector("canvas").getContext("2d");

// loop array of 4 [x,y] desired coordinates
[[0,0],[200,0],[0,200],[200,200]].forEach(function ([x,y]) {
  const img = new Image();
  img.src = 'https://images.unsplash.com/photo-1652957251843-dcc1a7cfc4be?w=1080';

  img.onload = function() {
    const [imgw, imgh] = [this.width, this.height];
    ctx.drawImage(img, 
    
        // crop (250, 350) and resize ((imgw / 2.5), (imgh / 2.5)) source image
        250, 350, (imgw / 2.5), (imgh / 2.5), 
      
        // place image on canvas
        x, y, 200, 200 
    );
  };
});
<canvas width="400" height="400"></canvas>

about 4 years ago · Juan Pablo Isaza Relatório

0

Take a look at this documentation
drawImage(image, sx, sy, sWidth, sHeight, dx, dy, dWidth, dHeight) example

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