Cómo mostrar una imagen en un lienzo HTML5

Bien, aquí hay una pregunta: "¿Por qué necesitamos un artículo para esto, Nash?"

Bueno, toma asiento.

¡No, espera! Primero, eche un vistazo a esto.

Exactamente. ¿Qué fue eso?

drawImagees el método utilizado para mostrar o "dibujar" una imagen canvas. Es posible que ya sepa o no que no es tan simple como simplemente pasarle el URI de la imagen. drawImageacepta un máximo de 9 parámetros. Van algo como esto, ¿listo? Contenga la respiración…

(image, sx, sy, sWidth, sHeight, dx, dy, dWidth, dHeight)

Exhalar.

Encontré la documentación drawImageun poco confusa y dura. Solo la documentación, sí. El concepto y cómo funciona la API es excelente para todas las necesidades que se supone que debe satisfacer.

Repasaremos los parámetros mencionados anteriormente uno por uno, de una manera que tenga mucho sentido para usted. Si en algún momento del artículo te encuentras diciendo “Solo quería dibujar una imagen en mi lienzo, querido Nash. ¿Por qué poner mi mente en el timbre? ”, Será una frustración comprensible.

La forma en que drawImagefunciona parece compleja hasta cierto punto, pero esta complejidad hace que sea drawImageinmensamente poderosa y útil, como veremos a través de ejemplos al final. Además, la complejidad está solo en la superficie: una vez que comprendes el panorama completo, es un paseo en bicicleta cuesta abajo en una carretera rural en algún lugar de Europa.

Al final de este artículo, podrá visualizar cómo drawImagese dibujará una imagen determinada con canvassolo mirar los valores de los 9 parámetros. ¿Suena como un superpoder que quizás quieras tener? Bien, entonces, ¡sumergámonos!

Cargando una imagen en lienzo

Comencemos de manera simple con una imagen y un HTML5 canvas.

Así es como se ve nuestro directorio

Dentro de nuestro index.htmlarchivo, hemos creado un nuevo elemento de lienzo como ese.

Nuestro objetivo es tomar la cat.jpgimagen y ponerla en el lienzo ( #my-canvas). Y como ya dije, ¡no es tan fácil, Betty! De lo contrario, no estaría escribiendo este artículo, ¿me entiendes? Bueno.

Para empezar, apuntemos al canvaselemento usando JavaScript y obtengamos su contexto.

const myCanvas = document.getElementById('my-canvas'); const myContext = myCanvas.getContext('2d');

Necesitamos myContextinteractuar con el canvaselemento. Es como si fuera canvasuna hoja de papel en blanco, el contexto del lienzo es el lápiz. Intuitivamente, le dirás a tu bolígrafo que dibuje algo en una hoja de papel en blanco, y no solo gritarle al papel que dibuje algo sobre sí mismo, ¿verdad?

Hay varias cosas con las que puede hacer context. Puede dibujar un rectángulo, una elipse, una línea o una ... imagen . Además, observe que el contexto myContextestá implícitamente vinculado a myCanvas. Puede tener varios canvases y llamar getContext()a cada uno de ellos para obtener un nuevo contexto / lápiz para cada uno. En nuestro caso, estamos tratando con un solo lienzo ( myCanvas) y solo un contexto ( myContext).

Muy bien, con eso fuera del camino, finalmente podemos empezar a mojarnos los pies drawImage.

Para un repaso, aquí están los 9 parámetros que drawImageacepta.

(image, sx, sy, sWidth, sHeight, dx, dy, dWidth, dHeight)

Vamos a empezar con el primer parámetro, image. Primero escribamos algo que no funcione.

context.drawImage('./cat.jpg', 0, 0);

¿Ves los dos ceros al final? Bueno. Esta no es la parte del artículo donde se supone que debes entender para qué están ahí. Ignóralos por ahora, solo recuerda que Nash escribió 2 ceros y no los explicó. No me importa

Ahora observe ...('./cat.jpg',..en la línea de código de arriba. Parece ser un URI perfectamente correcto, ¿no? Y es ... pero, si enciende index.htmlun navegador, verá un mensaje de error largo idéntico al que se muestra a continuación.

ERROR: The provided value is not of type '(CSSImageValue or HTMLImageElement or SVGImageElement or HTMLVideoElement or HTMLCanvasElement or ImageBitmap or OffscreenCanvas)

*trago*

El error nos dice que necesita un elemento de imagen y no solo un URI para la imagen. Para evitar eso, esto es lo que podemos hacer.

const canvas = document.getElementById('canvas'); const context = canvas.getContext('2d'); const img = new Image(); img.src = './cat.jpg'; img.onload = () => { context.drawImage(img, 0, 0); };

Eso es algo que no esperabas, ¿verdad? Canvas necesita una imagen precargada para poder dibujarla / mostrarla en sí misma. Por cierto, no hay necesidad de mostrar ningún desprecio hacia el lienzo. Tiene su razón, es como el resto de nosotros. Eventualmente veremos cuáles son esas razones y tal vez entonces puedas simpatizar.

Recordar:

drawImagesolicita 9 parámetros, el primero de los cuales es image. Miramos y entendimos que se canvasrequiere una imagen precargada para dibujar y no solo un URI para la imagen. ¿Por qué necesita eso? Se aclarará a medida que lea.

Ahora es el momento de los 8 parámetros restantes. ¡Pop tus cuellos! ¡Primero voy a aprender algo de edición de gráficos!

Cómo recortar una imagen

Cada programa de edición de gráficos, incluso el más básico, viene con la función de recorte. Es bastante simple: abra una imagen> seleccione el área que desea ver> recorte. Y así, el vientre de cerveza desnudo de ese anciano de olor desagradable está fuera. ¡Maricón!

¡Tecnología! Guardar los Instagram de las personas desde que existió Instagram.

Demos un paso atrás y paremos ahora mismo.

Señalemos algunos puntos.

"¡Espera un segundo! sx, sy, sWidthY sHeight? ¡Los he visto antes! "

¡Sí, hace aproximadamente un minuto! Lo que nos lleva a la parte más carnosa del artículo.

Visualización de una imagen en lienzo, Paso 1: Selección

The first task drawImage performs (behind the scenes) is it selects a portion of the image based on the four s parameters (sx, sy, sWidth, sHeight). You can say that s in all the s parameters stands for “select”.

Here’s how it goes. sx and sy mark the point on the image from where the selection is to begin, or in other words the coordinates of the top left corner of the selection rectangle. sWidth and sHeight then, are the width and height of the selection rectangle respectively. You can scroll right up to the last image to get a clearer picture of what I am trying to explain.

“But why the selection Nash? Can’t it just display the entire image?” We’re getting closer to all your answers, patience.

Just know that the first step drawImage performs after receiving a proper image is it selects a portion/area of the image based on the s parameters (sx, sy, sWidth, sHeight) you provide.

Remember that you don’t always have to select a small portion of the image, you can select the entire image if you want to. In that case sx and sy will have values 0 and 0 respectively and sWidth, sHeight will be the same as the image’s width and height.

Also, negative values are welcome for sx and sy. The values of sx and sy are relative to the origin of the image on the top left.

Once drawImage has selected the area of image you asked it to – and we’ll see soon why selecting an area of the image helps – the next step is to draw the selected portion of the image on the canvas.

“Originally” s and d in the official documentation stand for ‘source’ and ‘destination’. But, just between us, let’s call it ‘select’ and ‘draw’. It makes much more sense this way, doesn’t it?

Again. selection is done, the next step is to draw.

Displaying an image on canvas, Step 2: Drawing

To draw the selected portion of the image, we again need four parameters.

  1. x Coordinate of where to start drawing on the canvas. ( dx )
  2. y Coordinate of where to start drawing on the canvas. ( dy )
  3. How wide to draw the image. ( dWidth )
  4. How high/tall to draw the image. ( dHeight )

The values of dx and dy will be relative to the origin of the canvas.

There’s a very important but subtle detail to notice here. dWidth and dHeight are in no way tied to sWidth and sHeight. They are independent values. Why do you need to know that? Well, because if you don’t choose values of the width and height of ‘draw’ carefully you will end up with a stretched or squashed image, like this.

So if that’s something you’re not looking for (which I hope you’re not), make sure to maintain the aspect ratio. Or so to say sWidth divided by sHeight should be equal to dWidth divided by dHeight. That was a small little disclaimer, you’re the ruler of your own world and free to choose whatever values you like.

The whole process of displaying/drawing an image on canvas can thus be summarised in just two steps: Selection and Drawing.

Awesome! Not so complicated after all is it?

Now at this point, we’re done with all the theory. In rest of the article that follows we’ll bake the batter of knowledge spread around your head with a fun and practical example and you’ll be good to go. But, before we do that, let’s talk about one last important thing concerning drawImage.

The default values

Remember my lecture on “hey keep the aspect ratio and be careful don’t take chocolates from strangers…”? Well, as it turns out, you can omit certain values and not worry about the aspect ratio at all. As far as taking chocolates from strangers go, again — you’re the ruler of your own world.

Here’s one way to use the method.

drawImage(image, dx, dy)

That is all! In this case, you’re telling drawImage only the location on canvas where to start the drawing. The rest, sx, sy, sWidth, sHeight, dWidth and dHeight are taken care of automagically. The method selects the entire image (sx = 0, sy = 0, sWidth = image's width, sHeight = images' height) and starts drawing on canvas at (dx, dy) with dWidth and dHeight same as sWidth(image’s width), sHeight(image’s height) .

Remember the two zeroes that I didn’t explain? That is where the two zeroes came from.

Yet another way to use the method is,

drawImage(image, dx, dy, dWidth, dHeight)

In this form sx, sy, sWidth and sHeight are taken care of, and the method automatically selects the entire image and leaves it up to you to choose where and how large of an image to draw.

Pretty cool! isn’t it?

If I can have your attention for another two minutes I’d like to tell you why selection and drawing are two separate operations. And how it is helpful.

Do I have your attention? Great!

So here.

Heard of sprites before? You see, sprites are a computer graphics concept where a graphic may be moved on-screen and otherwise manipulated as a single entity.

…?

I copied this definition from Google to sound suave.

Alright alright. Remember Mario?

Good.

Let’s do something fun.

Animating Mario with drawImage

You see, when Mario moves forward/backward or in any other direction, it appears as if he is walking. His position changes but also there is an accompanying animation of his legs and hands moving.

How do they do that? Do they show different images of Mario in succession, like a flipbook and it appears as if he’s moving?

Well, 50% yes. Imagine how resource intensive storing and loading a huge set of images describing every frame of animation in our program (or game) would be. Instead, there’s a single image and all the positions are laid out in a grid. Like the one shown below.

To execute an animation, instead of loading a new image every millisecond, a portion of the same image is shown through a viewport just at different positions. Clever isn’t it?

So yes, it’s sorta like a flipbook, a clever flipbook actually.

Now if you could just stretch a little and pop your knuckles I would like us to recreate Mario’s walking animation. We’ll use the sprite shown above and everything we have learnt about drawImage so far.

Ready? Here we go!

Let’s take another look at our sprite and try to figure the grid dimensions that it has been laid out on.

All that we have done here is imagined a grid over the sprite. Notice that the entire grid is made up of cells of equal dimensions (32 x 39). But it’s still just one image, remember that.

Great! Now let’s get to writing some code. We’ll start in the usual way by first creating a canvas element, grabbing it and its context in JavaScript, and then loading our Mario spritesheet.

// index.js const canvas = document.getElementById('canvas'); const ctx = canvas.getContext('2d'); const img = new Image(); img.src = './mario.png'; img.onload = () => { ctx.drawImage(img, 0, 0); }; 
// style.css canvas { /*Add a border around canvas for legibility*/ border: 1px solid grey; }

The above code will result in the following.

Woah-kay! We’ve got the image showing! What’s happening really?

Here, we’re using the form of drawImagedrawImage(image, sx, sy)–where the whole image is selected and drawn on the canvas as it is.

What we want to do, first of all, is select just one cell of the grid and draw just that single cell. Let’s start out by first making tweaks to our code that selects the first cell in the third row, the one in which Mario is standing facing east. We’ll figure how to animate once we have that done. Sounds good? Lovely!

Let’s make the necessary changes to our code.

const canvas = document.getElementById('canvas'); const ctx = canvas.getContext('2d'); 
// Mario variables const MARIO_WIDTH = 32; const MARIO_HEIGHT = 39; 
const mario = new Image(); mario.src = './mario.png'; mario.onload = () => { ctx.drawImage( // Image mario, // ---- Selection ---- 0, // sx MARIO_HEIGHT * 2, // sy MARIO_WIDTH, // sWidth MARIO_HEIGHT, // sHeight // ---- Drawing ---- 0, // dx 0, // dy MARIO_WIDTH, // dWidth MARIO_HEIGHT // dHeight ); };

First off, notice the two variables MARIO_WIDTH and MARIO_HEIGHT. They are the dimensions of the grid cell, that’s all they are. We defined them to make it easier for us to traverse the grid using just multiples of each of those constants. Makes sense?

Good.

Next, in the // Selection block we defined the area of the image we want to select, in the // Drawing section we defined the width and height and the position from where to start drawing on the canvas… aaand just like that we managed to draw just one cell of the entire imaginary grid.

Pretty simple, just selection and drawing. Now at this point I’d like to digress into an older topic about aspect ratio. “Nash! again? ugghh” I know I know. But it’s cool! Look!

If I change the values of dWidth or dHeight or both of them, look at how the image stretches and squashes.

... ctx.drawImage( // Image mario, // ---- Selection ---- 0, // sx MARIO_HEIGHT * 2, // sy MARIO_WIDTH, // sWidth MARIO_HEIGHT, // sHeight // ---- Drawing ---- 0, // dx 0, // dy MARIO_WIDTH * 2, // dWidth MARIO_HEIGHT * 1.5 // dHeight ); ...

Hah! See! That’s why I was advising you to maintain the aspect ratio and that the values of selection and drawing have no real interconnection.

Okay, back to what we were doing.

So now we have Mario in the canvas, small and little. We need to animate it, or in other words show different frames at the same location in succession and make the illusion of movement happen. Was I too specific? Heck yeah!

We can do that by selecting the grid cells we want to draw in succession. We just need to change the value of sx by the multiples of MARIO_WIDTH.

Now doing this will require the use of requestAnimationFrame and I have been explaining that in a streak in this article and this article.

As a small challenge why don’t you go ahead and try accomplishing this on your own? In any case, you can check out this Codepen where I have Mario running like this. The pen has enough comments to help you understand the tiny bit of high school math that’s being used to make the animation happen.

Cute little thing!

Y con eso, hemos terminado con una explicación muy completa de drawImage. Espero que hayas disfrutado.

Si ha llegado hasta aquí, ¿qué tal si me envía algunos comentarios o #goodvibes en Twitter?

Este artículo se publicó originalmente en www.nashvail.me.

¿Te hablé de mi nuevo sitio web? ¿Y te dije que también tiene Newsletter? Me encantaría si se suscribiera para poder notificarle cada vez que publique algo nuevo o ponga algo nuevo a la venta en mi tienda. Continuaré publicando artículos en Medium, pero habrá un intervalo de dos semanas entre el momento en que aparece por primera vez en mi sitio y el momento en que aparece aquí.

Muchas gracias por leer y muchas gracias por su apoyo. ¡Tener una buena! :)