Kuidas kuvada pilti HTML5 lõuendil

Ok, nii et siin on küsimus: "Miks me vajame selleks artiklit, Nash?"

Haara koht.

Ei oota! Kõigepealt vaadake seda.

Täpselt nii. Mis see oli?

drawImageon meetod, mida kasutatakse pildi kuvamiseks või joonistamiseks canvas. Võib-olla juba teate, et see pole nii lihtne kui lihtsalt pildi URI edastamine sellele. drawImageaktsepteerib maksimaalselt 9 parameetrit. Nad lähevad midagi sellist, valmis? Hoidke hinge…

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

Hinga, välja.

Leidsin, et dokumentatsioon drawImageon veidi segane ja raske. Lihtsalt dokumentatsioon, jah. Kontseptsioon ja API toimimine sobivad suurepäraselt kõigi nende vajaduste rahuldamiseks.

Tutvume ükshaaval ülalnimetatud parameetritega viisil, mis on teie jaoks täiesti mõistlik. Kui leiate ühel hetkel artiklis, et lähete „Ma tahtsin lihtsalt joonistada oma lõuendile pilti, kallis Nash. Miks peaksin oma mõtteid helisema panema? ”, See on arusaadav pettumus.

Toimiv viis drawImagenäib teatud määral keeruline, kuid see keerukus muudab drawImagetohutult võimsa ja kasuliku - nagu näeme lõpus toodud näidete kaudu. Pealegi on keerukus lihtsalt pinnal: kui tervikpildist aru saate, on see allamäge jalgrattasõit riigimaanteel kuskil Euroopas.

Selle artikli lõpuks saate 9 parameetri väärtusi vaadates visualiseerida, kuidas drawImagekonkreetne pilt joonistatakse canvas. Kõlab nagu suurriik, mida võiksite soovida? Olgu siis, sukeldume otse sisse!

Pildi laadimine lõuendisse

Alustame lihtsaks pildi ja HTML5-ga canvas.

Meie kataloog näeb välja selline

Meie index.htmlfaili sees oleme loonud uue lõuendi elemendi.

Meie eesmärk on teha cat.jpgpilt ja panna see lõuendile ( #my-canvas). Ja nagu ma juba ütlesin, pole see nii lihtne betty! Muidu ma ei kirjutaks seda artiklit, kas tunnete mind? Hea.

Alustuseks suuname canvaselemendi JavaScripti abil ja saame selle konteksti.

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

Peame elemendiga myContextsuhtlema canvas. See on nagu, kui canvastühi paberileht on lõuendi kontekst sulepea. Intuitiivselt ütlete oma pastakale, et joonistage midagi tühjale paberilehele, ja mitte lihtsalt ei karju paberi peale, et midagi endale joonistada?

Saate teha mitmeid asju context. Võite joonistada ristküliku, ellipsi, joone või… pildi . Pange tähele, et kontekst myContexton kaudselt seotud myCanvas. Teil võib olla mitu canvases ja helistada getContext()neile kõigile, et saada igaühele uus kontekst / pliiats. Meie puhul on tegemist ainult ühe lõuendiga ( myCanvas) ja ainult ühe kontekstiga ( myContext).

Hästi, kui see on mujalt väljas, saame lõpuks jalgu märjaks teha drawImage.

Värskenduseks on siin 9 parameetrit, mis drawImageaktsepteerivad.

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

Alustame esimese parameetriga image. Kirjutame kõigepealt midagi, mis ei tööta.

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

Kas näete lõpus kahte nulli? Hea. See pole artikli osa, kus peaksite aru saama, mille jaoks nad seal on. Eirake neid praegu, hoidke lihtsalt kuklas, et Nash kirjutas 2 nulli ja ei selgitanud neid. Mul pole selle vastu midagi.

Nüüd märkage ...('./cat.jpg',..ülaltoodud koodireal. Tundub täiesti õige URI, kas pole? Ja see on ... buuuut, kui index.htmlkäivitate brauseri, näete pikka pikka veateadet, mis on identne allpool näidatuga .

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

* lonks *

Viga ütleb meile, et see vajab pildi elementi ja mitte ainult pildi URI-d. Sellest pääsemiseks saame seda teha.

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

See on midagi, mida te ei oodanud? Lõuend vajab eelnevalt laaditud pilti, et seda ise joonistada / kuvada. Muide, pole vaja lõuendi suhtes põlgust näidata. Sellel on oma põhjus, see on täpselt nagu meil kõigil teistel. Lõpuks näeme, mis need põhjused on, ja võib-olla siis saate kaastunnet tunda.

Kokkuvõtteks:

drawImageküsib 9 parameetrit, millest esimene on image. Vaatasime ja saime aru, et canvasselle joonistamiseks on vaja eelnevalt laaditud pilti ja mitte ainult pildi URI-d. Miks ta seda vajab? See selgub lugedes.

Nüüd on aeg üle minna 8 parameetrile. Pop oma kraed! Ma õpin teile kõigepealt graafika redigeerimise!

Kuidas pilti kärpida

Igal graafika redigeerimisprogrammil, isegi kõige elementaarsemal, on kärpimise funktsioon. See on üsna lihtne: avage pilt> valige ala, mida soovite näha> vajutage kärpimist. Ja just nii on selle ebameeldiva lõhnaga vanamehe paljas õllekõht väljas. Puhh!

Tehnoloogia! Inimeste instagrammide salvestamine alates Instagrami olemasolust.

Võtame sammu tagasi ja lõpetame riiight siin.

Märgistame sellel mõned punktid.

"Oota sekund! sx, sy, sWidthJa sHeight? Olen neid varem näinud! ”

Jah, umbes minut tagasi! Mis viib meid artikli kõige värskema osa juurde.

Pildi kuvamine lõuendil, 1. samm: valik

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!

Ja sellega oleme lõpetanud väga põhjaliku selgituse drawImage. Loodetavasti teile meeldis.

Kui olete nii kaugele jõudnud, siis kuidas oleksite mulle Twitteris tagasisidet või #heavibes?

See artikkel avaldati algselt veebisaidil www.nashvail.me.

Kas ma rääkisin teile oma uuest veebisaidist? Ja kas ma ütlesin teile, et ka sellel on uudiskiri? Mulle meeldiks, kui telliksite, et saaksin teid teavitada iga kord, kui avaldan midagi uut või panen oma poes midagi uut müüki. Jätkan artiklite avaldamist Mediumis, kuid selle vahel, millal see minu saidil esimest korda üles tõuseb ja millal siin ilmub, jääb kahe nädala vahe.

Suur aitäh lugemast ja aitäh toetuse eest. Head! :)