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

214
Vistas
Canvas drawImage layering

Using a canvas to render a collection of images layered that a user can download the compiled image afterwards. However, when using image.onload it layers the order of images in terms of which loads the fastest from the CDN.

I am trying to achieve so that they are layered in terms of code line progression. Is there anyway to achieve this? I have tried async functions but haven't really been able to achieve anything. Below is the current code I have:

import React, { useRef, useEffect } from 'react';

interface CanvasProps {
    width: number;
    height: number;
    base: string;
    eyes: string;
    hat: string;
    backpack: string;
    clothes: string;
    selected: number;
}

const Canvas = ({ width, height, base, eyes, hat, backpack, clothes, selected }: CanvasProps) => {
    const canvasRef = useRef<HTMLCanvasElement>(null);

    const renderImages = async (context) => {
        var bg_image = new Image();
        var base_image = new Image();
        var eyes_image = new Image();
        var hats_image = new Image();
        var backpacks_image = new Image();
        var clothes_image = new Image();

        bg_image.crossOrigin="*";
        base_image.crossOrigin="*";
        eyes_image.crossOrigin="*";
        hats_image.crossOrigin="*";
        clothes_image.crossOrigin="*";
        backpacks_image.crossOrigin="*";

        base_image.src = base;
        eyes_image.src = eyes;
        hats_image.src = hat;
        clothes_image.src = backpack;
        backpacks_image.src = clothes;

        base_image.onload = function(){ context.drawImage(base_image, 0, 0, 650, 650) }
        eyes_image.onload = function(){ context.drawImage(eyes_image, 0, 0, 650, 650) }
        hats_image.onload = function(){ context.drawImage(hats_image, 0, 0, 650, 650) }
        clothes_image.onload = function(){ context.drawImage(clothes_image, 0, 0, 650, 650) }
        backpacks_image.onload = function(){ context.drawImage(backpacks_image, 0, 0, 650, 650) }
    }

    useEffect(() => {
        if (canvasRef.current) {
            const canvas = canvasRef.current;
            if (canvasRef.current) {
                const context = canvas.getContext('2d');
                if (context) {
                    context.clearRect(0, 0, 650, 650);
                    renderImages(context);
                }
            }
        }       
    },[selected]);

    return <canvas id="canvas" ref={canvasRef} height={height} width={width} />;
};

Canvas.defaultProps = {
    width: window.innerWidth,
    height: window.innerHeight
};

export default Canvas;
about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

You can wrap your image creation in a Promise that resolves once the image is done loading and wait for each of the image loadings to finish, to achieve the synchronous flow you want.

const getImg = (url: string) => {
  const img = new Image();
  img.crossOrigin="*";
  img.src = url;

  return new Promise((res, rej) =>  {
        img.onload = () => res(img);
        img.onerror = (err) => rej(err);
  });
}

const renderImages = async (context) => {
  const baseImg = await getImg(base);
  context.drawImage(baseImg, 0, 0, 650, 650);

  const eyesImg = await getImg(eyes);
  context.drawImage(eyesImg, 0, 0, 650, 650);

  const hatImg = await getImg(hat);
  context.drawImage(hatImg, 0, 0, 650, 650);

  const backpackImg = await getImg(backpack);
  context.drawImage(backpackImg, 0, 0, 650, 650);

  const clothesImg = await getImg(clothes);
  context.drawImage(clothesImg, 0, 0, 650, 650);
}

about 4 years ago · Juan Pablo Isaza Denunciar

0

I would use one array image_sources instead of a the many variables you are using
(base, eyes, hat, backpack, clothes), benefits of this approach:

  • This would significantly reduce the size of your render function code.
  • We can recursively call renderImages to sequentially draw all images.
  • Your code is ready to handle as many image layers as the users needs.

Here is my rough prototype:

const renderImages = (context, index) => {
  if (index < image_sources.length) {
    let image = new Image();
    image.crossOrigin = "*";
    image.src = image_sources[index];
    image.onload = function() {
      context.drawImage(image, 0, 0, 650, 650)
      renderImages(context, index + 1)
    }
  }
}

useEffect(() => {
  if (canvasRef.current) {
    const canvas = canvasRef.current;
    if (canvasRef.current) {
      const context = canvas.getContext('2d');
      if (context) {
        context.clearRect(0, 0, 650, 650);
        renderImages(context, 0);
      }
    }
  }
}, [selected]);
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