Kép megjelenítése HTML5 vásznon

Oké, szóval itt van egy kérdés: "Miért van szükségünk erre cikkre, Nash?"

Fogj helyet.

Nincs várakozás! Először nézze meg ezt.

Pontosan. Mi volt az?

drawImageaz a módszer, amelyet egy kép megjelenítésére vagy „rajzolására” használnak canvas. Lehet, hogy már nem tudod, hogy ez nem olyan egyszerű, mint csak átadni neki a kép URI-ját. drawImagemaximum 9 paramétert fogad el. Valami ilyesmit mennek, készen? Tartsa vissza a lélegzetét…

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

Kilélegez.

A dokumentációt drawImagekissé zavarosnak és keménynek találtam . Csak a dokumentáció, igen. A koncepció és az API működése minden igényt kielégít, amelyet kiszolgálnak.

Egyenként áttekintjük a fent említett paramétereket, olyan módon, hogy az neked teljes értelmet nyerjen. Ha a cikk bármelyik pontján azon kapja magát, hogy „Csak képet akartam rajzolni a vásznamon, kedves Nash. Miért adnám át az elmémet a csengőn? ”, Érthető csalódás lesz.

A drawImageműködési mód bizonyos mértékig bonyolultnak tűnik, de ez a bonyolultság drawImagerendkívül hatékonnyá és hasznosgá teszi - amint a végén példákkal láthatjuk. Sőt, a bonyolultság csak a felszínen van: ha megértette az összképet, lefelé tartó kerékpáros út vezet egy országúton valahol Európában.

A cikk végére csak a 9 paraméter értékeinek megnézésével láthatja, hogyan drawImagerajzolhatja ki az adott képet canvas. Úgy hangzik, mint egy szuperhatalom, amire esetleg vágysz? Oké, akkor merüljünk be rögtön!

Kép betöltése vászonra

Kezdjük egyszerûen egy képpel és egy HTML5-tel canvas.

Így néz ki a könyvtárunk

A index.htmlfájlunk belsejében létrehoztunk egy új vászon elemet.

Célunk, hogy a cat.jpgképet elkészítsük és a vászonra tegyük ( #my-canvas). És mint már mondtam, ez nem olyan egyszerű betty! Különben nem írnám ezt a cikket, érzed? Jó.

Először is célozzuk meg az canvaselemet a JavaScript használatával, és kapjuk meg annak összefüggéseit.

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

myContextKölcsönhatásba kell lépnünk az canvaselemmel. Olyan, mintha canvasüres papír lenne, akkor a vászon kontextusa a toll. Intuitív módon elmondja a tollának, hogy rajzoljon valamit egy üres papírlapra, és ne csak kiabáljon a papírral, hogy rajzoljon magára valamit, igaz?

Számos dolgot megtehetsz context. Rajzolhat téglalapot, ellipszist, vonalat vagy… képet . Figyelje meg azt is, hogy a kontextus myContextimplicit módon kapcsolódik myCanvas. Több canvases lehet, és getContext()mindegyiket felhívhatja, hogy mindegyikhez új kontextust / tollat ​​kapjon. Esetünkben csak egy vászonnal ( myCanvas) és csak egy kontextussal ( myContext) foglalkozunk.

Rendben, ezzel az útból végre elkezdhetjük nedvesíteni a lábunkat drawImage.

A frissítéshez íme a 9 paraméter, amelyet drawImageelfogad.

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

Kezdjük az első paraméter, image. Írjunk először olyat, ami nem működik.

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

Látod a végén a két nullát? Jó. Ez nem a cikknek az a része, ahol meg kellene értenie, hogy mire valók. Most figyelmen kívül hagyja őket, csak tartsa a fejét, hogy Nash 2 nullát írt, és nem magyarázta el őket. Nem bánom.

Most vegye észre ...('./cat.jpg',..a fenti kódsorban. Teljesen helyes URI-nak tűnik, nem? És ez… buuuut, ha index.htmlegy böngészőben elindul, hosszú, hosszú hibaüzenetet fog látni, amely megegyezik az alábbiakkal.

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

*korty*

A hiba azt mondja, hogy egy képelemre van szükség, és nem csak a kép URI-jára. Hogy ezt megkerüljük, ezt megtehetjük.

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); };

Erre nem számított? A Canvas-nak előretöltött képre van szüksége annak megrajzolásához / megjelenítéséhez. Egyébként nem kell semmiféle megvetést mutatni a vászon iránt. Ennek megvan az oka, pont olyan, mint mi többiek. Végül meglátjuk, melyek ezek az okok, és talán akkor képes lesz szimpatizálni.

Összefoglalva:

drawImage9 paramétert kér, amelyek közül az első az image. Megnéztük és megértettük, canvasamihez előre feltöltött kép szükséges, és nem csak URI-t kell használni a képhez. Miért van erre szükség? Ez olvasás közben kiderül.

Itt az ideje a megújuló 8 paraméternek. Pop a gallér! Először megtanulok neked néhány grafikai szerkesztést!

Kép kivágása

Minden egyes grafikai szerkesztő program, még a legalapvetőbb is, magában foglalja a kivágás funkcióját. Ez meglehetősen egyszerű: nyisson meg egy képet> válassza ki a látható területet> nyomja meg a vágást. És éppen úgy, kint van annak a kellemetlen szagú öregnek a meztelen sörhas. Hoppá!

Technológia! Az emberek instagramainak mentése az Instagram létezése óta.

Tegyünk egy lépést hátra, és állítsuk meg itt a riiightot.

Jelöljünk rajta néhány pontot.

"Várjunk csak! sx, sy, sWidthÉs sHeight? Már láttam őket!

Igen, körülbelül egy perccel ezelőtt! Ami a cikk legfrissebb részéhez vezet.

Kép megjelenítése vászonra, 1. lépés: Kiválasztás

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!

És ezzel elkészültünk egy nagyon átfogó magyarázattal drawImage. Remélem élvezted.

Ha eddig eljutottál, mit szólnál ahhoz, ha visszajeleznél vagy visszajeleznél a Twitterről?

Ezt a cikket eredetileg a www.nashvail.me oldalon tették közzé.

Mondtam neked az új weboldalamról? És mondtam, hogy van Hírlevele is? Örülnék, ha feliratkozna, így értesíteni tudok minden alkalommal, amikor valami újat teszek közzé, vagy eladok valami újat az üzletemben. Folytatom a cikkek közzétételét a Medium-on, de kéthetes különbség lesz, amikor először kerül fel a webhelyemre, és mikor jelenik meg itt.

Nagyon köszönöm, hogy elolvastad, és nagyon köszönöm a támogatást. Van egy jó! :)