How can I scale / stretch / skew a sprite from a sprite sheet using javascript?

Some prerequisites: I do a raycaster, well ... did. But I decided to change it a little. I started creating the beam maker and decided that it would be much easier to display the icon and stretch / skew, rather than just moving a bunch of pixels.

My question is: How can I scale / stretch / skew a sprite from a sprite sheet using javascript?

Basically I want to get a 16px by 16px image from a sprite image and put it, scale it, rotate it and skew it using javascript. How can I do it?

If this helps, I thought of connecting three versions of this image to give the impression of a three-dimensional block moving in three-dimensional space, without using 3D.

+6
source share
3 answers

You can do this with CSS3 transform . Or use a hidden canvas element, apply transformation , and then draw it on the main canvas.

+2
source

Most likely, the easiest way is to use the background-size css property. Since most modern browsers (IE 9+, FF4 +, Safari4 +, Chrome3 +) support it, you can do the following:

HTML:

 <div id="mySprite"> </div> 

CSS

 #mySprite{ height: 80px; /* 64px * 1.25 */ width: 80px; /* 64px * 1.25 */ background-image:url(my.png); background-position: -0px -560px; /* pick specific one at -448px * 1.25 */ background-size:640px 640px; /* scale image to 512px * 1.25 */ } 

The spritesheet has 64x64px sprites and scales to 80x80px. See a real-time example: http://jsfiddle.net/Zgr5w/1/

As @Prusse said: you can use transform: scale() as well, but it has some disadvantages: browser support, additional position transformation, alignment with other elements may be broken:

 #mySprite{ height: 64px; width: 64px; background-image:url(my.png); background-position: -0px -448px; transform:scale(1.25); /* additional to compensate the position shift */ position:relative; top:10px; left:10px; } 

see a live example of the above two approaches here: http://jsfiddle.net/Zgr5w/1/

+7
source

You can accomplish this using the drawImage function on the canvas. The following example scales a 40x100 sprite to double the size of 80x200.

 <html> <body> <canvas id="canvas" width=80 height=200> <script language="JavaScript"> function draw() { var ctx = document.getElementById('canvas').getContext('2d'); var img = new Image(); img.src = 'http://gamemedia.wcgame.ru/data/2011-07-17/game-sprite-sheet.jpg'; img.onload = function() { // (image, sx, sy, sw, sh, dx, dy, dw, dh) ctx.drawImage(img,0,0,40,100,0,0,80,200); } } draw(); </script> </body> </html> 
+2
source

Source: https://habr.com/ru/post/903467/


All Articles