var base_image = new Image(); base_image.src = 'https://......jpg'; var can = document.getElementById("pai"); var ctx = can.getContext('2d'); base_image.onload = function() { can.style.width = base_image.width; can.style.height = base_image.height; var imgWidth= base_image.width; var imgHeight=base_image.height; ctx.canvas.width= imgWidth; ctx.canvas.height= imgHeight; ctx.drawImage(base_image,0,0,imgWidth,imgHeight);manga como me reencarné como un cirujano legendario
Estoy usando el código anterior para dibujar una imagen en el lienzo. ¿Hay alguna forma de poder dibujar 2 o más imágenes verticalmente? Gracias.
Entonces, en general, si desea dibujar un montón de imágenes en un orden garantizado, puede intentar usar una pila/matriz para almacenar las imágenes y luego dibujarlas en un bucle.
El orden de dibujo determinará el orden en que se muestran.
Así es como te recomiendo que configures tu código para que cargues todas las imágenes que necesitas primero antes de comenzar a dibujar:
// Counter to keep track of how many images have loaded so far. let imagesReady = 0; // Array of image urls/srcs that you can easily update. const imageSrcs = ['https://acnhcdn.com/latest/FtrIcon/FtrMarioRoundB.png', 'https://acnhcdn.com/latest/FtrIcon/FtrMarioSquareA.png']; // Construct a new array with image objects const images = imageSrcs.map((src) => { const image = new Image(); image.src = src; // Increment our `imagesReady` counter once this image loads. image.onload = () => { imagesReady++; if (imagesReady >= imageSrcs.length) { // Trigger the image draw drawImages(); } } return image; }); const can = document.getElementById("pai"); const ctx = can.getContext('2d'); function drawImages() { // Set the canvas height to the sum of all image heights can.height = images.reduce((previousValue, image) => previousValue + image.height, 0); let lastImage = null; let lastImageY = 0; // We store the last image data above so that // we know what is the next Y to start drawing at. for (const image of images) { lastImageY = lastImage ? lastImageY + lastImage.height : 0; lastImage = image; ctx.save(); ctx.drawImage(image, 0, lastImageY, image.width, image.height); ctx.restore(); } } Nota: por lo general, cuando tiene un lienzo, puede tender a envolverlo en un bucle setInterval o requestAnimationFrame para seguir actualizando el lienzo, por ejemplo, a 30 o 60 cuadros por segundo (por ejemplo, si está creando un cuadro interactivo). pantalla de lienzo donde cambian posiciones/dibujos o estás haciendo un juego).
En ese escenario, la técnica anterior es una forma muy simple/básica de configurar una barra de carga para que pueda cargar todos sus activos primero (hasta imagesReady === imageSrcs.length )
Puede mostrar una barra de carga o un mensaje de carga para una mejor experiencia de usuario.