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

190
Visualizações
How to scale small ImageData to large HTML canvas

I am trying to put image data 100x100 to canvas 1000x1000 , but cant able to do it ,

let width=1000;      //canvas width
let height=1000;    //canvas height
let img_w=100;      //image width
let img_h=100;      //image height
let img=new Image();
img.width=img_w
img.height=img_h
img.src="./flower.jpg"
var canvas = document.getElementById('mycanvas');
var context = canvas.getContext('2d');
canvas.width = width;
canvas.height = height;
let pixels,scannedimg;
img.onload=()=>{
context.drawImage(img, 0, 0,width,height );
scannedimg = context.getImageData(0, 0, img.width, img.height);
pixels=scannedimg.data
console.log(pixels)
redraw();
}

let row=4*img_w;
let col=img_h;

function redraw(){
    for(let i=0;i<row;i+=4){
        for(let j=0;j<col;j++){
            pixels[i+j*row]=0;
            pixels[i+j*row+1]=0;
            pixels[i+j*row+2]=0;
            //pixels[i+j*400+3]=0;
        }
    }
   scannedimg.data=pixels;
    console.log(scannedimg);
    context.putImageData(scannedimg,0,0,0,0,width,height);
}

i have converted the original array into a black image array (array of zeros) , but while putting on canvas , it is still 100x100 How to scale it to 1000x1000? i don't want to iterate through 1000x1000 and set it to zero , i need a computationally efficient answer

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

0

Unless you outsource the pixel calculations to a WebAssembly module a JavaScript-only approach would indeed be rather slow for a large image.

Honestly I'm not sure what you are actually doing in your code.

First your drawing an unknown-sized .jpg to a 1000x1000 canvas which - unless the .jpg is also 1000x1000 - will scale and eventually distort the source image.

let width=1000;
let height=1000; 
context.drawImage(img, 0, 0, width, height);

Secondly you're obtaining the pixel data of a 100x100 region from the top-left of your 1000x1000 canvas.

let img_w=100;
let img_h=100;
img.width=img_w;
img.height=img_h;
scannedimg = context.getImageData(0, 0, img.width, img.height);

Finally in your redraw() function you're rather randomly setting some of the pixels to black and draw it back to the canvas at 1000x1000 (which doesn't work that way but I will get into it later).

Let's do it a little different. Say we have a 300x200 image. First we need to draw it to a 100x100 canvas while maintaining it's aspect ratio to get the 100x100 imagedata. This can be done using a dynamically created off-screen <canvas> element as we don't need to see it.

Now the tricky part is the CanvasRenderingContext2D putImageData() method. I assume you were thinking that the last pair of parameters for the width & height would stretch existing pixel data to fill the region specifid by (x, y, width, height). Well that's not the case. Instead we need to - again - paint the 100x100 pixel data to a same-sized off-screen canvas (or for simlicity re-use the existing) and draw it to the final canvas using the drawImage() method.

Here's everything put together:

let pixelsWidth = 100;
let pixelsHeight = 100;
let finalWidth = 500;
let finalHeight = 500;
let tempCanvas = document.createElement('canvas');
let tempContext = tempCanvas.getContext('2d');
tempCanvas.width = pixelsWidth;
tempCanvas.height = pixelsHeight;
let pixelData;
let img = new Image();
img.crossOrigin = 'anonymous';
img.onload = (e) => {
  let scale = e.target.naturalWidth >= e.target.naturalHeight ? pixelsWidth / e.target.naturalWidth : pixelsHeight / e.target.naturalHeight;
  let tempWidth = e.target.naturalWidth * scale;
  let tempHeight = e.target.naturalHeight * scale;
  tempContext.drawImage(e.target, pixelsWidth / 2 - tempWidth / 2, pixelsHeight / 2 - tempHeight / 2, tempWidth, tempHeight);
  pixelData = tempContext.getImageData(0, 0, pixelsWidth, pixelsHeight);
  redraw();
}
img.src = 'https://picsum.photos/id/237/300/200';

function redraw() {
  let canvas = document.getElementById('canvas');
  let context = canvas.getContext('2d');
  canvas.width = finalWidth;
  canvas.height = finalHeight;
  tempContext.putImageData(pixelData, 0, 0);
  context.drawImage(tempCanvas, 0, 0, finalWidth, finalHeight);
}
canvas {
  background: #cccccc;
}
<canvas id="canvas"></canvas>

about 4 years ago · Juan Pablo Isaza Relatório

0

The best way™ to render an ImageData upscaled is to create an ImageBitmap from it.
All modern browsers finally do support it (and if you need support for older browsers, I got you covered).

This will use a faster path to render the ImageData's content to a bitmap readily available to be painted by drawImage, theoretically a lot faster than the second best option of putting the ImageData on a canvas and redraw that canvas.

(async () => {
  // here I'll just make some noise in my ImageData
  const imagedata = new ImageData(100, 100);
  const arr = new Uint32Array(imagedata.data.buffer);
  for( let i = 0; i < arr.length; i++ ) {
    arr[i] = Math.random() * 0xFFFFFF + 0xFF000000;
  }
  // now to render it bigger
  const bitmap = await createImageBitmap(imagedata);
  const canvas = document.querySelector("canvas");
  const ctx = canvas.getContext("2d");
  ctx.imageSmoothingEnabled = false; // keep pixel perfect
  ctx.drawImage(bitmap, 0, 0, canvas.width, canvas.height);
})();
<canvas width="1000" height="1000"></canvas>

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