Results 1 to 9 of 9
Thread: HTML5 Canvas Animation
Threaded View
-
09-16-2011, 05:07 PM #1Junior Guru Wannabe
- Join Date
- Sep 2011
- Posts
- 74
HTML5 Canvas Animation
Since I'm relatively new to the board, I'd thought I'd give a little demonstration on the ease of animations on an HTML5 canvas element. Other tutorials show how to draw, I thought I'd touch base on how easy it is to animate.
What is Canvas :
Canvas is a (semi-)new feature of modern browsers that allows Javascript to draw and create graphics inside an element.
What could it be used for :
Just like Java and Flash, it could be used to make some cool games. Also, someday it could be used to eliminate the need for some unneeded images, therefore reducing bandwidth.
Learning Curve :
Easy, if you know a bit of Math and Javascript, you are good to go. Flash game designers should find it a walk in the park.
#1. The canvas element
Use this :
Code:<canvas id="canvas" height="300px" width="500px"></canvas>
Code:<canvas id="canvas" style="height:300px; width:500px"></canvas>
#2. Get the canvas element
Code:canvas = document.getElementById("canvas"); ctx = canvas.getContext("2d");
#3. Let's Draw!
Code:ctx.beginPath(); ctx.fillRect(10,10,30,30); ctx.closePath();
#4. Let's make it move
To make it move we have to use a timer and erase the canvas every time (or we will get a smudge mark). For fun, we will create a player object, with an X and Y.
Code:player = new Object(); player.x = 10; player.y = 10; setInterval(draw,100); function draw(){ canvas.width = canvas.width; ctx.beginPath(); ctx.fillRect(player.x,player.y,30,30); ctx.closePath(); player.x++; }
At the end, you see that the player.x value gets an increment of 1.
That is it! I haven't tested the code but it should work. Copy and paste what is below into a HTML file and give it a go.
Code:<!DOCTYPE HTML> <head></head> <body> <canvas id="canvas" height="300px" width="400px" style="border:1px solid #000"></canvas> <script> player = new Object(); player.x = 5; player.y = 5; canvas = document.getElementById("canvas"); ctx = canvas.getContext("2d"); setInterval(draw,100); function draw(){ canvas.width = canvas.width; ctx.beginPath(); ctx.fillRect(player.x,player.y,30,30); ctx.closePath(); player.x++; } </script> </body> </html>
Although a bit basic, you should have the jist of it. With what you have here, your next step could be to add keyboard controls, or maybe have it follow your mouse.
Good luck in the future to other programmers!
Similar Threads
-
Javascript/Canvas gallery
By Mike Taylor in forum Employment / Job OffersReplies: 2Last Post: 04-20-2011, 07:20 PM -
Canvas Systems emailed me...
By HOD-Jardin in forum Web Hosting LoungeReplies: 6Last Post: 02-09-2010, 06:43 PM -
Animator vs Animation - For people dealing with animation
By unity100 in forum Web Hosting LoungeReplies: 0Last Post: 04-07-2008, 08:56 AM -
Deneba's CANVAS 7 Plug-ins (Free)
By Cosmos75 in forum Web Design and ContentReplies: 0Last Post: 07-13-2004, 10:59 AM