- GUI
- Windows API tutorial
- Introduction to Windows API
- Windows API main functions
- System functions in Windows API
- Strings in Windows API
- Date & time in Windows API
- A window in Windows API
- First steps in UI
- Windows API menus
- Windows API dialogs
- Windows API controls I
- Windows API controls II
- Windows API controls III
- Advanced controls in Windows API
- Custom controls in Windows API
- The GDI in Windows API
- PyQt4 tutorial
- PyQt5 tutorial
- Qt4 tutorial
- Introduction to Qt4 toolkit
- Qt4 utility classes
- Strings in Qt4
- Date and time in Qt4
- Working with files and directories in Qt4
- First programs in Qt4
- Menus and toolbars in Qt4
- Layout management in Qt4
- Events and signals in Qt4
- Qt4 Widgets
- Qt4 Widgets II
- Painting in Qt4
- Custom widget in Qt4
- The Breakout game in Qt4
- Qt5 tutorial
- Introduction to Qt5 toolkit
- Strings in Qt5
- Date and time in Qt5
- Containers in Qt5
- Working with files and directories in Qt5
- First programs in Qt5
- Menus and toolbars in Qt5
- Layout management in Qt5
- Events and signals in Qt5
- Qt5 Widgets
- Qt5 Widgets II
- Painting in Qt5
- Custom widget in Qt5
- Snake in Qt5
- The Breakout game in Qt5
- PySide tutorial
- Tkinter tutorial
- Tcl/Tk tutorial
- Qt Quick tutorial
- Java Swing tutorial
- JavaFX tutorial
- Java SWT tutorial
- wxWidgets tutorial
- Introduction to wxWidgets
- wxWidgets helper classes
- First programs in wxWidgets
- Menus and toolbars in wxWidgets
- Layout management in wxWidgets
- Events in wxWidgets
- Dialogs in wxWidgets
- wxWidgets widgets
- wxWidgets widgets II
- Drag and Drop in wxWidgets
- Device Contexts in wxWidgets
- Custom widgets in wxWidgets
- The Tetris game in wxWidgets
- wxPython tutorial
- Introduction to wxPython
- First Steps
- Menus and toolbars
- Layout management in wxPython
- Events in wxPython
- wxPython dialogs
- Widgets
- Advanced widgets in wxPython
- Drag and drop in wxPython
- Internationalisation
- Application skeletons in wxPython
- The GDI
- Mapping modes
- Creating custom widgets
- Tips and Tricks
- wxPython Gripts
- The Tetris game in wxPython
- C# Winforms Mono tutorial
- Java Gnome tutorial
- Introduction to Java Gnome
- First steps in Java Gnome
- Layout management in Java Gnome
- Layout management II in Java Gnome
- Menus in Java Gnome
- Toolbars in Java Gnome
- Events in Java Gnome
- Widgets in Java Gnome
- Widgets II in Java Gnome
- Advanced widgets in Java Gnome
- Dialogs in Java Gnome
- Pango in Java Gnome
- Drawing with Cairo in Java Gnome
- Drawing with Cairo II
- Nibbles in Java Gnome
- QtJambi tutorial
- GTK+ tutorial
- Ruby GTK tutorial
- GTK# tutorial
- Visual Basic GTK# tutorial
- PyGTK tutorial
- Introduction to PyGTK
- First steps in PyGTK
- Layout management in PyGTK
- Menus in PyGTK
- Toolbars in PyGTK
- Signals & events in PyGTK
- Widgets in PyGTK
- Widgets II in PyGTK
- Advanced widgets in PyGTK
- Dialogs in PyGTK
- Pango
- Pango II
- Drawing with Cairo in PyGTK
- Drawing with Cairo II
- Snake game in PyGTK
- Custom widget in PyGTK
- PHP GTK tutorial
- C# Qyoto tutorial
- Ruby Qt tutorial
- Visual Basic Qyoto tutorial
- Mono IronPython Winforms tutorial
- Introduction
- First steps in IronPython Mono Winforms
- Layout management
- Menus and toolbars
- Basic Controls in Mono Winforms
- Basic Controls II in Mono Winforms
- Advanced Controls in Mono Winforms
- Dialogs
- Drag & drop in Mono Winforms
- Painting
- Painting II in IronPython Mono Winforms
- Snake in IronPython Mono Winforms
- The Tetris game in IronPython Mono Winforms
- FreeBASIC GTK tutorial
- Jython Swing tutorial
- JRuby Swing tutorial
- Visual Basic Winforms tutorial
- JavaScript GTK tutorial
- Ruby HTTPClient tutorial
- Ruby Faraday tutorial
- Ruby Net::HTTP tutorial
- Java 2D games tutorial
- Java 2D tutorial
- Cairo graphics tutorial
- PyCairo tutorial
- HTML5 canvas tutorial
- Python tutorial
- Python language
- Interactive Python
- Python lexical structure
- Python data types
- Strings in Python
- Python lists
- Python dictionaries
- Python operators
- Keywords in Python
- Functions in Python
- Files in Python
- Object-oriented programming in Python
- Modules
- Packages in Python
- Exceptions in Python
- Iterators and Generators
- Introspection in Python
- Ruby tutorial
- PHP tutorial
- Visual Basic tutorial
- Visual Basic
- Visual Basic lexical structure
- Basics
- Visual Basic data types
- Strings in Visual Basic
- Operators
- Flow control
- Visual Basic arrays
- Procedures & functions in Visual Basic
- Organizing code in Visual Basic
- Object-oriented programming
- Object-oriented programming II in Visual Basic
- Collections in Visual Basic
- Input & output
- Tcl tutorial
- C# tutorial
- Java tutorial
- AWK tutorial
- Jetty tutorial
- Tomcat Derby tutorial
- Jtwig tutorial
- Android tutorial
- Introduction to Android development
- First Android application
- Android Button widgets
- Android Intents
- Layout management in Android
- Android Spinner widget
- SeekBar widget
- Android ProgressBar widget
- Android ListView widget
- Android Pickers
- Android menus
- Dialogs
- Drawing in Android
- Java EE 5 tutorials
- Introduction
- Installing Java
- Installing NetBeans 6
- Java Application Servers
- Resin CGIServlet
- JavaServer Pages, (JSPs)
- Implicit objects in JSPs
- Shopping cart
- JSP & MySQL Database
- Java Servlets
- Sending email in a Servlet
- Creating a captcha in a Servlet
- DataSource & DriverManager
- Java Beans
- Custom JSP tags
- Object relational mapping with iBATIS
- Jsoup tutorial
- MySQL tutorial
- MySQL quick tutorial
- MySQL storage engines
- MySQL data types
- Creating, altering and dropping tables in MySQL
- MySQL expressions
- Inserting, updating, and deleting data in MySQL
- The SELECT statement in MySQL
- MySQL subqueries
- MySQL constraints
- Exporting and importing data in MySQL
- Joining tables in MySQL
- MySQL functions
- Views in MySQL
- Transactions in MySQL
- MySQL stored routines
- MySQL Python tutorial
- MySQL Perl tutorial
- MySQL C API programming tutorial
- MySQL Visual Basic tutorial
- MySQL PHP tutorial
- MySQL Java tutorial
- MySQL Ruby tutorial
- MySQL C# tutorial
- SQLite tutorial
- SQLite C tutorial
- SQLite PHP tutorial
- SQLite Python tutorial
- SQLite Perl tutorial
- SQLite Ruby tutorial
- SQLite C# tutorial
- SQLite Visual Basic tutorial
- PostgreSQL C tutorial
- PostgreSQL Python tutorial
- PostgreSQL Ruby tutorial
- PostgreSQL PHP tutorial
- PostgreSQL Java tutorial
- Apache Derby tutorial
- SQLAlchemy tutorial
- MongoDB PHP tutorial
- MongoDB Java tutorial
- MongoDB JavaScript tutorial
- MongoDB Ruby tutorial
- Spring JdbcTemplate tutorial
- JDBI tutorial
Animation in HTML5 canvas
In this chapter, we create animation in HTML5 canvas.
Animation is a rapid succession of images which make an illusion of movement. Animation is not restricted to movement, however. Changing the background of a object over time is considered an animation too.
There are three functions to create animation in HTML5 canvas:
- setInterval(function, delay)
- setTimeut(function, delay)
- requestAnimationFrame(callback)
The setInterval()
function repeatedly executes the passed function every delay milliseconds. The setTimeout()
executes the specified function in delay milliseconds. In order to create animation, the setTimeout()
is called from within the executed function. The requestAnimationFrame()
function lets the browser call a specified function to update an animation before the next repaint. The browser does some optimisations.
Move along curve
In the first animation, an object is moved along a curve.
move_along_curve.html
<!DOCTYPE html> <html> <head> <title>HTML5 canvas move along curve</title> <style> canvas { border: 1px solid #bbbbbb } </style> <script> var canvas; var ctx; var x = 20; var y = 80; const DELAY = 30; const RADIUS = 10; function init() { canvas = document.getElementById('myCanvas'); ctx = canvas.getContext('2d'); setInterval(move_ball, DELAY); } function draw() { ctx.clearRect(0, 0, canvas.width, canvas.height); ctx.beginPath(); ctx.fillStyle = "cadetblue"; ctx.arc(x, y, RADIUS, 0, 2*Math.PI); ctx.fill(); } function move_ball() { x += 1; if (x > canvas.width + RADIUS) { x = 0; } y = Math.sin(x/32)*30 + 80; draw(); } </script> </head> <body onload="init();"> <canvas id="myCanvas" width="350" height="150"> </canvas> </body> </html>
The example moves a circle along a sine curve. After the circle moves past the end of the canvas, it reappears on the left side.
setInterval(move_ball, DELAY);
The setInterval()
function causes the move_ball()
function to be called every DELAY
ms.
function draw() { ctx.clearRect(0, 0, canvas.width, canvas.height); ctx.beginPath(); ctx.fillStyle = "cadetblue"; ctx.arc(x, y, RADIUS, 0, 2*Math.PI); ctx.fill(); }
The draw()
method clears the canvas with the clearRect()
method and draws a new circle with updated x and y coordinates.
function move_ball() { x += 1; if (x > canvas.width + RADIUS) { x = 0; } y = Math.sin(x/32)*30 + 80; draw(); }
In the move_ball()
function, we update the x and y coordinates of the circle's center point. We check if the ball has passed the right edge of the canvas and call the draw()
method to redraw the canvas.
Fading out
Fading out is an animation which changes the state of an object. It is a kind of a transition animation.
fading_out.html
<!DOCTYPE html> <html> <head> <style> canvas {border: 1px solid #bbbbbb} </style> <title>HTML5 canvas fading out</title> <script> var canvas; var ctx; var alpha = 1; var rx = 20; var ry = 20; var rw = 120; var rh = 80; const DELAY = 20; function init() { canvas = document.getElementById('myCanvas'); ctx = canvas.getContext('2d'); canvas.addEventListener("click", onClicked); ctx.fillRect(rx, ry, rw, rh) } function onClicked(e) { var cx = e.x; var cy = e.y; if (cx >= rx && cx <= rx + rw && cy >= ry && cy <= ry + rh) { fadeout(); } } function fadeout() { if (alpha < 0) { canvas.removeEventListener("click", onClicked); ctx.globalAlpha = 1; ctx.fillStyle = 'white'; ctx.fillRect(rx, ry, rw, rh); return; } ctx.clearRect(rx, ry, rw, rh); ctx.globalAlpha = alpha; ctx.fillRect(rx, ry, rw, rh) alpha -= 0.01; setTimeout(fadeout, DELAY); } </script> </head> <body onload="init();"> <canvas id="myCanvas" width="350" height="250"> </canvas> </body> </html>
There is a rectangle object. When we click on the rectangle, it starts fading out.
canvas.addEventListener("click", onClicked);
A click
listener is added to the canvas with the addEventListener()
method. Upon receveing a mouse click, the onClicked()
function is called.
ctx.fillRect(rx, ry, rw, rh)
Initially, a rectangle is drawn on the canvas in the default black fill.
function onClicked(e) { var cx = e.x; var cy = e.y; if (cx >= rx && cx <= rx + rw && cy >= ry && cy <= ry + rh) { fadeout(); } }
Inside the onClicked()
function, we figure out the x and y coordinates of the mouse click. We compare the mouse coordinates with the outside bounds of the rectagle and if it falls in the rectagle's area, the fadeout()
method is called.
if (alpha < 0) { canvas.removeEventListener("click", onClicked); ctx.globalAlpha = 1; ctx.fillStyle = 'white'; ctx.fillRect(rx, ry, rw, rh); return; }
When the rectagle is fully transparent, we remove the listener and fill the area in opaque white colour. The return statement ends the recursive calling of the fadeout()
function.
ctx.clearRect(rx, ry, rw, rh); ctx.globalAlpha = alpha; ctx.fillRect(rx, ry, rw, rh)
The area of the rectangle is cleared and filled with updated alpha state.
alpha -= 0.01;
The alpha
value is decreased by a small fraction.
setTimeout(fadeout, DELAY);
After DELAY
ms, the fadeout()
method is called from inside its own body. This practice is called recursion.
Bubbles
The following examples is inspired by example from the Java 2D demo.
bubbles.html
<!DOCTYPE html> <html> <head> <title>HTML5 canvas bubbles</title> <style> canvas { border: 1px solid #bbb; background: #000; } </style> <script> var cols = ["blue", "cadetblue", "green", "orange", "red", "yellow", "gray", "white"]; const NUMBER_OF_CIRCLES = 35; const DELAY = 30; var maxSize; var canvas; var ctx; var circles; function Circle(x, y, r, c) { this.x = x; this.y = y; this.r = r; this.c = c; } function init() { canvas = document.getElementById('myCanvas'); ctx = canvas.getContext('2d'); circles = new Array(NUMBER_OF_CIRCLES); initCircles(); doStep(); } function initCircles() { var w = canvas.width; var h = canvas.height; maxSize = w / 10; for (var i = 0; i < circles.length; i++) { var rc = getRandomCoordinates(); var r = Math.floor(maxSize * Math.random()); var c = cols[Math.floor(Math.random()*cols.length)] circles[i] = new Circle(rc[0], rc[1], r, c); } } function doStep() { for (var i = 0; i < circles.length; i++) { var c = circles[i]; c.r += 1; if (c.r > maxSize) { var rc = getRandomCoordinates(); c.x = rc[0]; c.y = rc[1]; c.r = 1; } } drawCircles(); setTimeout(doStep, DELAY); } function getRandomCoordinates() { var w = canvas.width; var h = canvas.height; var x = Math.floor(Math.random() * (w - (maxSize / 2))); var y = Math.floor(Math.random() * (h - (maxSize / 2))); return [x, y]; } function drawCircles() { ctx.clearRect(0, 0, canvas.width, canvas.height); for (var i = 0; i < circles.length; i++) { ctx.beginPath(); ctx.lineWidth = 2.5; var c = circles[i]; ctx.strokeStyle = c.c; ctx.arc(c.x, c.y, c.r, 0, 2*Math.PI); ctx.stroke(); } } </script> </head> <body onload="init();"> <canvas id="myCanvas" width="350" height="250"> </canvas> </body> </html>
In the example there are growing coloured bubbles that randomly appear and disappear on the screen.
var cols = ["blue", "cadetblue", "green", "orange", "red", "yellow", "gray", "white"];
These colours are used to paint the bubbles.
function Circle(x, y, r, c) { this.x = x; this.y = y; this.r = r; this.c = c; }
This is the constructor of the Circle
object. In addition to the x and y coordinates and the radius, it also contains the c property for the colour value.
circles = new Array(NUMBER_OF_CIRCLES);
The circles
array is used to hold circle objects.
for (var i = 0; i < circles.length; i++) { var rc = getRandomCoordinates(); var r = Math.floor(maxSize * Math.random()); var c = cols[Math.floor(Math.random()*cols.length)] circles[i] = new Circle(rc[0], rc[1], r, c); }
The circles
array is filled with circles. We calculate random coordinates, random initial radius, and random colour value.
function doStep() {
The doStep()
represents an animation cycle of the program.
for (var i = 0; i < circles.length; i++) { var c = circles[i]; c.r += 1; if (c.r > maxSize) { var rc = getRandomCoordinates(); c.x = rc[0]; c.y = rc[1]; c.r = 1; } }
We go through the circles
array and increase each circle's radius. When the circle reaches a maximum size, it is randomly repositioned and minimized.
setTimeout(doStep, DELAY);
The setTimeout()
method is used to create animation. You may need to adjust the DELAY
value to fit your hardware.
function drawCircles() { ctx.clearRect(0, 0, canvas.width, canvas.height); for (var i = 0; i < circles.length; i++) { ctx.beginPath(); ctx.lineWidth = 2.5; var c = circles[i]; ctx.strokeStyle = c.c; ctx.arc(c.x, c.y, c.r, 0, 2*Math.PI); ctx.stroke(); } }
The drawCircles()
function clears the canvas and paints all the circles from the array.
Star field
The following example creates a starfield animation.
starfield.html
<!DOCTYPE html> <html> <head> <title>HTML5 canvas star field</title> <script> var canvas_w; var canvas_h; var canvas; var ctx; var layer1; var layer2; var layer3; const DELAY = 20; const N_STARS = 60; const SPEED1 = 3; const SPEED2 = 2; const SPEED3 = 1; function init() { canvas = document.getElementById("myCanvas"); ctx = canvas.getContext("2d"); canvas_w = canvas.width; canvas_h = canvas.height; layer1 = new layer(N_STARS, SPEED1, "#ffffff"); layer2 = new layer(N_STARS, SPEED2, "#dddddd"); layer3 = new layer(N_STARS, SPEED3, "#999999"); setTimeout("drawLayers()", DELAY); } function star() { this.x = Math.floor(Math.random()*canvas_w); this.y = Math.floor(Math.random()*canvas_h); this.move = function(speed) { this.y = this.y + speed; if (this.y > canvas_h) { this.y = 0; this.x = Math.floor(Math.random()*canvas_w); } } this.draw = function(col) { ctx.fillStyle = col; ctx.fillRect(this.x, this.y , 1, 1); } } function layer(n, sp, col) { this.n = n; this.sp = sp; this.col = col; this.stars = new Array(this.n); for (var i=0; i < this.n; i++) { this.stars[i] = new star(); } this.moveLayer = function() { for (var i=0; i < this.n; i++) { this.stars[i].move(this.sp); } } this.drawLayer = function() { for (var i=0; i < this.n; i++) { this.stars[i].draw(this.col); } } } function drawLayers() { ctx.fillStyle = '#000000'; ctx.fillRect(0, 0, canvas_w, canvas_h); layer1.moveLayer(); layer2.moveLayer(); layer3.moveLayer(); layer1.drawLayer(); layer2.drawLayer(); layer3.drawLayer(); setTimeout("drawLayers()", DELAY); } </script> </head> <body onload="init();"> <canvas id="myCanvas" width="800" height="600"> </canvas> </body> </html>
The starfield animation is created by producing three different layers; each layer consists of stars (little dots) having different speed and colour shade. The stars in the front layer are brighter and move faster, the stars in the back are dimmer and move slower.
layer1 = new layer(N_STARS, SPEED1, "#ffffff"); layer2 = new layer(N_STARS, SPEED2, "#dddddd"); layer3 = new layer(N_STARS, SPEED3, "#999999");
Three layers of stars are created. They have different speeds and colour shades.
function star() { this.x = Math.floor(Math.random()*canvas_w); this.y = Math.floor(Math.random()*canvas_h); ...
When a star is created, it is given random coordinates.
this.move = function(speed) { this.y = this.y + speed; if (this.y > canvas_h) { this.y = 0; this.x = Math.floor(Math.random()*canvas_w); } }
The move()
method moves the star; it increases its y coordinate.
this.draw = function(col) { ctx.fillStyle = col; ctx.fillRect(this.x, this.y , 1, 1); }
The draw()
method draws the star on the canvas. It uses the fillRect()
method to draw a tiny rectangle in the given colour shade.
function layer(n, sp, col) { this.n = n; this.sp = sp; this.col = col; this.stars = new Array(this.n); ...
A layer is a collection of n
stars with the given speed and colour shade. The stars are stored in the stars
array.
for (var i=0; i < this.n; i++) { this.stars[i] = new star(); }
Upon creation of the layer, the stars
array is filled with star objects.
this.moveLayer = function() { for (var i=0; i < this.n; i++) { this.stars[i].move(this.sp); } }
The moveLayer()
method goes through the array of stars and calls each star's move()
method.
this.drawLayer = function() { for (var i=0; i < this.n; i++) { this.stars[i].draw(this.col); } }
Likewise, the drawLayer()
method calls each star's draw()
method.
function drawLayers() { ctx.fillStyle = '#000000'; ctx.fillRect(0, 0, canvas_w, canvas_h); layer1.moveLayer(); layer2.moveLayer(); layer3.moveLayer(); layer1.drawLayer(); layer2.drawLayer(); layer3.drawLayer(); setTimeout("drawLayers()", DELAY); }
The drawLayers()
function moves the stars of each layer and draws them on the canvas. It calls itself after DELAY
ms, thus creating animation.
In this chapter of the HTML5 canvas tutorial, we have covered animation.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论