Animation is the rapid display of a sequence of images in order to create an illusion of movement.
There are few methods to achieve that effect in JS, and I will discuss four of them in here.
1. Canvas animation
I used canvas animation in my Javascript game tutorial, but let's describe it once again. As an example, I will animate jump frames from my very favorite game days ago, Prince of Persia, you can find it on the right side of the post.
Before stating any animation related stuff it's necessarily to define few variables common for all four methods. Let's do this:
var width = 100, height = 86, frames = 10, //our PoP jumping animation has 11 frames, but we count from 0 actualFrame = 0, posX = 100, posY = 100, //X & Y position of the element canvas = document.createElement('canvas'), //'canvas' variable will be always main element of an animation, not alwaysTo animate our character we need just to display next frames of the jump on the canvas. It's not necessarily to clear whole surface each time in this particular case, because it has the same size as single frame. The draw function will looks like that:
var draw = function(){ ctx.drawImage(image, 0, height * actualFrame, width, height, 0, 0, width, height); //the attributes are: image to draw, X coord of the source image, Y coord of the source image, width & height of the cut piece (frame size), X & Y destination coords (our canvas) and destination frame size (not always the same as the source one, eg in case of scaling the frame) if (actualFrame == frames) { actualFrame = 0; } else { actualFrame++; } //looping the frames, it is also the common part of all draw() function in this post }So that is the first method of JavaScript animation.
Pros:
- it uses canvas (the future of HTML5 games)
- it's possible to scale, rotate, flip, etc. the frames in browsers that support canvas but no CSS3
- probably much more
Cons:
- need to clear whole canvas to draw another frame
- not supported in old browsers
- quite complex math for display single frame
Life example: [1. Canvas Animation]
2. Background looping
I think it was one of the firstmethods of sprite's animation in web browsers. It is the simplest way ever. Just create div element with background, and change backgroundPosition on each frame. Piece of cake. Try:
var canvas = document.createElement('div'), //div element is now our 'canvas' canvasStyle = canvas.style; canvasStyle.backgroundImage = "url(sprite.jpg)"; //and our image is just it's background canvasStyle.position = "absolute"; canvasStyle.top = posX; canvasStyle.left = posY; canvasStyle.width = width; canvasStyle.height = height; //width & height are now assigned to the 'style', not directly to the element document.body.appendChild(canvas); var draw = function(){ canvasStyle.backgroundPosition = "0 -"+height * actualFrame; //each frame background image moves up, that's why there is minus sign before the value, you can multiply (height * actualFrame) by negative one, it gives the same effect (...) //here goes frame changing logic from the 1st example }Pros:
- simplicity
- works everywhere
Cons:
- not possible to scale, rotate, etc. without CSS3
Example: [2. Background looping animation]
3. Clip-rect method
Hmm, but what when we wan't our game to run on full screen, or on different devices with various resolutions? Changing size of the div from second example gives nothing, just looks ugly. So this is where I introduce clip:rec(), Css attribute of img element. Quoting W3schools:
The clip property lets you specify the dimensions of an absolutely positioned element that should be visible, and the element is clipped into this shape.
Let's try:
var canvas = document.createElement('img'), //image is not the canvas canvasStyle = canvas.style; canvas.src = 'sprite.jpg'; (...)//rest of the attributes var draw = function(){ var frameTop = height * actualFrame, frameLeft = 0, frameRight = width, frameBottom = frameTop + height; //a little math here for each frame canvasStyle.clip = "rect(" +frameTop +"px " //top +frameRight +"px " //right +frameBottom +"px " //bottom +frameLeft +"px )"; //left canvasStyle.top = posY - height * actualFrame; //IMPORTANT: even if we crop piece of source image, it's top & left attrs dont change - it's necessarily to move it to the fixed position. That's what I made above.Pros:
- only one element needed (just img)
- possibility of scaling without CSS3
- crossbrowser
Cons:
- not possible to rotate, flip, etc
- very lot of math needed on each move/frame changing.
Example: [3. Clip-rect method]
4. Div with overflow:hidden
The last way of animation I want to present is simplest than 3rd one, better than 2nd, and doesn't use canvas. The whole philosophy is to create one div element with image inside, display only part visible in div, and move the image in proper way. Like this:
var canvas = document.createElement('div'), canvasStyle = canvas.style, image = document.createElement('img'), imageStyle = image.style; image.src = 'sprite.jpg'; //div is the 'canvas' now, but it has an image inside canvasStyle.position = imageStyle.position = "absolute"; canvasStyle.top = posX; canvasStyle.left = posY; canvasStyle.overflow = "hidden"; //that is very important canvasStyle.width = width; canvasStyle.height = height; imageStyle.top = 0; imageStyle.left = 0; canvas.appendChild(image); document.body.appendChild(canvas); //put image in the canvas/div and add it all to the body of the document. var draw = function(){ imageStyle.top = -1*height * actualFrame; //as in the 3rd example - direction of the move must be negative. Otherwise animation will be played backwards if (actualFrame == frames) { actualFrame = 0; } else { actualFrame++; } }Pros:
- possibility of scaling without CSS3
- crossbrowser
- much simpler than clip:rect()
Cons:
- not possible to rotate, flip, etc
- two elements needed (img & div)
Example: [4. Div with overflow:hidden]
Changing size of animated elements is very important in gamedev. So as simplicity. That's why in my new JS game engine I will implement both, canvas and overflow:hidden methods. You can find all the sources on my GitHub account: [Javascript animation]
nice one. Write this damn book :)
ReplyDeletegreat great, thank you for sharing, I was looking for this post, and I've found. very helpful in completing my job
ReplyDeleteThanks for making the above tutorials. Good tutorials like what you posted above are very very very very hard to find over the internet. I've been through hell and back looking for good and CLEAR examples on how to do the above animations. Most tutorials about Animations I found only tells a person how to move a stinking box and who the heck wants to do boring animations like that?? I wouldn't even call that animation. So thus, thanks. I can get back to the business of making my game and website. I have only one suggestion. Could a very simple HTML parts be included in what is above so that a person could just come to this site, copy the code, paste it into their text editor (such as notepad,etc), download the frame image file above, save them all into one folder and just run the code that way? Thanks again!
ReplyDeleteGood Information...you have mentioned very rare points on java script animation. Best software Training institute in Bangalore
ReplyDeleteThanks for your great and helpful presentation I like your good service. I always appreciate your post. That is very interesting I love reading and I am always searching for informative information like this. Well written article
ReplyDeleteMachine Learning With TensorFlow Training and Course in Muscat
| CPHQ Online Training in Singapore. Get Certified Online
learn ceh certification and become a certified hacker
ReplyDeleteNice Post...
ReplyDeletebitwise aptitude questions
how to hack flipkart legally
zenq interview questions
count ways to n'th stair(order does not matter)
zeus learning subjective test
ajax success redirect to another page with data
l&t type 2 coordination chart
html rollover image
hack android phone using cmd
how to hack internet speed upto 100mbps
Wonderful post and I learn a lot of informations from your great post. Thank you...!
ReplyDeleteSpark Training in Chennai
Apache Spark Training
Pega Training in Chennai
Advanced Excel Training in Chennai
Power BI Training in Chennai
Corporate Training in Chennai
Unix Training in Chennai
Job Openings in Chennai
Tableau Training in Chennai
Spark Training in Anna Nagar
Together with loving just what exactly looks very similar to a good day spa day time, your cousins within The japanese dedicate their particular times languishing within sizzling hot rises, despite the fact that thrilled sightseers take on his or her's pictures. http://0r96qvf3fp.dip.jp http://1p97u9mhpn.dip.jp https://imgur.com/a/2Z6N6zZ https://imgur.com/a/9zdI7Xh https://imgur.com/a/wG7OzCi http://yqzv7a0xna.dip.jp https://imgur.com/a/KAUU3VD
ReplyDeletevery nice post and useful information........
ReplyDeleter programming training in chennai
internship in bangalore for ece students
inplant training for mechanical engineering students
summer internships in hyderabad for cse students 2019
final year project ideas for information technology
bba internship certificate
internship in bangalore for ece
internship for cse students in hyderabad
summer training for ece students after second year
robotics courses in chennai
nice....
ReplyDeletecategory/advocate-resume
category/agriculture-forestry-fishing
category/android-developer-resume
category/assistant-professor-resume
category/chartered-accountant-resume
category/database-resume
category/design-engineer-resume
category/developer-resume
category/engineer-resume
category/entrepreneur-and-financial-services-resume
useful information..nice..
ReplyDeletedevops-engineer-resume-samples
digital-marketing-resume-samples
digital-marketing-resume-samples
electronics-engineer-resume-sample
engineering-lab-technician-resume-samples
english-teacher-cv-sample
english-teacher-resume-example
english-teacher-resume-sample
excel-expert-resume-sample
executive-secretary-resume-samples
Your Guidance Helps me solve all my query...I enjoyed your blog Thanks for sharing such an informative post.
ReplyDeleteJava training in chennai | Java training in annanagar | Java training in omr | Java training in porur | Java training in tambaram | Java training in velachery
Interesting information and attractive.This blog is really rocking... Yes, the post is very interesting and I really like it.I never seen articles like this. I meant it's so knowledgeable, informative, and good looking site. I appreciate your hard work. Good job.
ReplyDeleteSalesforce Training in Chennai | Certification | Online Course | Salesforce Training in Bangalore | Certification | Online Course | Salesforce Training in Hyderabad | Certification | Online Course | Salesforce Training in Pune | Certification | Online Course | Salesforce Online Training | Salesforce Training
Can you make animation for tiktok? I would use this method, because my video people like very seldom and I have to get tiktok likes from this page https://soclikes.com/buy-tiktok-likes
ReplyDeleteThis is my first time visit to your blog and I am very interested in the articles that you serve. Provide enough knowledge for me. Thank you for sharing useful and don't forget, keep sharing useful info:
ReplyDeleteJava Training in Gurgaon
Read trending & Latest news from India & World. Daily news on Indian politics, elections, environment, government, business, technology and Bollywood & Hollywood.
ReplyDeleteanilinkz
ReplyDelete13377x
9xmovies
1337x
123moviesonline
Managed Dispatch services
ReplyDeleteWe provide the resources you need to make sure that you’re devoting all the time necessary to your own specialities rather than firefighting IT issues.
Thankyou so much for sharing this info
ReplyDeletewedding Photographer in Ahmedabad
wedding Photographer in Bhopal
Dooh in India
4Movierulz is the center of pirate movies and TV shows. When it comes to releasing the latest movies, no other free streaming site can match it. As the name suggests, this website is the owner of pirated movies. No streaming sites like 4Movierulz or Movierulz4 have gained popularity.
ReplyDeletefloating paper airplane | fatty | slick slider | Easy paper airplane | rocker | reconn | Span | traveller
ReplyDeletevirtual edge. Could this solution be a win-win for both corporate registrants and event planners? Conference organizers often have to book large room blocks. How to Create an Original Name for a Company and 9 Steps to Organize a Digital Event
ReplyDeleteThanks for sharing great info … Hiring a limousine are excellent option to make your special occasion more delightful. Limo Hire Melbourne – Limo Hire Melbourne Prices .
ReplyDeletethank you for posting this Bike Rental Dehradun
ReplyDeleteAuthentic and Classical Yoga, Online Yoga, Bali Private Yoga, and Meditation Classes, At convenient timings for you, taught by professional and experienced yoga teachers at a unique center set amidst ancient trees and nature, free from pollution, in the heart of Bali – Canggu. Join our center and practice Yoga from the best yoga center in Bali, Yoga Baliby Billy Beate & Cultural Centre, for a lifestyle holistic and enriching experience. Make us part of your yoga journey! Join the best yoga school in Bali and the best yoga Bootcamp in Bali, Billy Yoga & Yoga Bali Centre, for a happy and healthy life.
ReplyDeleteYour post is extremely useful and the data is dependable. I'm happy with your post. Much thanks for sharing this great post.
ReplyDeleteThis comment has been removed by the author.
ReplyDeleteJobs in MNC’s
ReplyDeleteOnly MNC & established companies are using DFP(doubleclick for publishers) at this point. so learn doubleclick for publishers to get hired in these companies.
Very awesome post! I like that and very interesting content.
ReplyDeletepega testing
pega testing training
Good Article, very interesting post
ReplyDeletePega Training Hyderabad
Pega Online Training
Thanks for the post. It was very interesting and meaningful. I want share about Aaraa couture
ReplyDeleteVery Nice information
ReplyDeleteWorkday Training Online
Workday Course
Sigmatest understands the significance of purity of water for human consumption and industrial works. This water testing lab offers competitive facilities for testing of drinking water and waste. They own an exceptionally equipped laboratory that possesses the most advanced and contemporary tools and instruments required for carrying out a complete analysis for all sorts of water samples.
ReplyDeleteMore info:
Major Types of Non Destructive Testing Methods
water testing lab near me
In the case of so-called permanent laser hair removal, the laser acts directly on melanin, which is responsible for hair and skin color. The area to be shaved must be shaved before applying the laser.
ReplyDeletetypes of laser hair removal
Your blog posts provided me with excellent information
ReplyDeleteReact JS Training in Hyderabad
ReplyDeleteSunny
ReplyDeleteKiran
ReplyDeleteAwesome blog post.
ReplyDeleteInformative post
ReplyDeleteThank you for this blog.
ReplyDeletePython Training in Chennai
Python Online Course
Python Training in Bangalore
kralbet
ReplyDeletebetpark
tipobet
slot siteleri
kibris bahis siteleri
poker siteleri
bonus veren siteler
mobil ödeme bahis
betmatik
JTP
nice post. Data Science Training In Amravati
ReplyDeleteThis information is really amazing, thanks for sharing. Looking for more post from you.
ReplyDeleteI love the depth of research in your writing. Every post is a learning experience.Visit this site click speed test for more informative content.The CPS test really helped me improve my butterfly clicking technique. Now I’m faster in Minecraft PVP.
ReplyDeleteشركة تركيب طارد الحمام بخميس مشيط xHdbLLnjbY
ReplyDelete