Download as pdf or txt
Download as pdf or txt
You are on page 1of 88

HTML5 CANVAS and CSS3 by EXAMPLES 978-0-9777812-4-9 Graphics, Games, Animations 1

HTML5 CANVAS & CSS3


by EXAMPLES
Graphics, Games and Animations
for the Modern Browsers
by
Quan Nguyen
Exploring the new features of HTML5 and CSS3
Comparing codes by HTML5 canvas versus its DOM equivalence
Learning by examples with short and concise scripts
HTML5 CANVAS and CSS3 by EXAMPLES 978-0-9777812-4-9 Graphics, Games, Animations 2
Author's Biography
Quan Nguyen has designed IC chips Ior 30 years in the semiconductor industry in the area oI
computer and telecomnunication development. He graduated Irom the University oI Michigan
in 1982 with the degree oI BS in Electrical Engineering and MSEE at the University oI Vermont
in 1986. His recent mission involves designing circuitry Ior Qualcomm SnapDragon chipsets
Ior mobile phone and tablet applications. He is the author oI several books: "The Perl
Connection", "The CAD connection", "CAD Scripting Languages", "Programming The Canvas" and "HTML5
Canvas & CSS3 by Examples".
Limit of Liability and Disclaimer of Liability
This book is published "as is" basic and the inIormation is provided as "as is". The author and the publisher make
no warranty oI any kind, expressed or implied, with regard to these programs or the documentation contained in
this book.
This book is Ior instructional purpose only and should not be used in any commercial programs. The author and
the publisher shall not be liable in the event oI incidental or consequential damages in connection with, or arising
out oI, the Iurnishing, perIormance, or the use oI the programs, associated instructions, and/or claims oI
productivity gains.
CopyRight 2013 Protection
Copyright 2013 by Quan Nguyen. All rights reserved. No part oI this book may be reproduced, stored in a
retrieval system, or transmitted in any Iorm or by any means, electronic, photocopying or scanning, without the
express written consent oI the author and the publisher. The inIormation contained herein is Ior personal use and
may not be incorporated in any commercial programs, other books, databases, or any kind oI soItware without the
written consent oI the author and the publisher. Making copies oI this book or any portion Ior any purpose other
than your own use is a violation oI the United States copyright laws.
ISBN-13: 978-0-9777812-4-9 ISBN-10: 0-9777812-4-0
Library oI Congress Control Number: 2007942133
United States Copyright OIIice: CertiIicate oI Registration #TX 6-517-329
ramacadgmail.com
Printed in The United States oI America.
HTML5 CANVAS and CSS3 by EXAMPLES 978-0-9777812-4-9 Graphics, Games, Animations 3
Table of Contents
1. Basic Shapes ................................................................................................... 19
2. Basic Images .................................................................................................. 89
3. Basic Interactive .......................................................................................... 137
4. Basic Animation .......................................................................................... 197
5. Advanced Shapes ......................................................................................... 247
6. Advanced Interactive ................................................................................. 289
7. Advanced Images ........................................................................................ 315
8. Advanced Animation ................................................................................... 355
9. Game Essentials .......................................................................................... 397
10. Game Basic ................................................................................................ 443
11. Game Advanced ........................................................................................ 477
Sub-label Languages Tag elements
1 (Canvas) JavaScript canvas
2 (CSS3) Pure CSS3 div tags; no canvas
3 (DOM) JavaScript CSS3 (jQuery) div tags; (no canvas)
Example Catagory
HTML5 CANVAS and CSS3 by EXAMPLES 978-0-9777812-4-9 Graphics, Games, Animations 4
1. Basic Shapes .................................................................................................. 19
1.1 Array oI pixels (Canvas)
1.1.1 Random true/Ialse generator (JavaScript)
1.1.2 Random number generator Ior range oI numbers (JavaScript)
1.1.3 Random colors with RGB (Canvas)
1.2 Array oI pixels (DOM)
1.2.1 Array oI pixels (DOM & no jQuery)
1.2.2 Blinking pixels (Canvas)
1.2.3 Blinking pixels (DOM)
1.2.4 Walking pixels (Canvas)
1.2.5 Walking pixels (DOM)
1.2.6 Random colors with Hex #FFFFFF (Canvas)
1.3 Circles within circles (Canvas)
1.3.1 Random colors with HSL Iormat (Canvas)
1.4 Circles within circles (DOM)
1.5 Random circles (Canvas)
1.6 Random circles (DOM)
1.7 Ring oI circles (Canvas)
1.8 Ring oI circles (DOM)
1.9 Spider web (Canvas)
1.10 Spider web (DOM)
1.11 Moon crescent (Canvas)
1.12 Moon crescent (DOM)
1.12.1 Moon crescent with pseudo-elements (CSS3)
1.12.2 Basic CSS3 shapes (CSS3)
1.12.3 Moon crescent with color gradient (Canvas)
1.12.4 Moon crescent with color gradient (DOM)
1.13 Circle oI text (Canvas)
1.14 Circle oI text (DOM)
1.15 Circular text (Canvas)
1.16 Circular text (DOM & no jQuery)
1.17 Balloon popup (Canvas)
1.18 Balloon popup (DOM)
1.19 Pacman running (Canvas)
1.20 Pacman running (CSS3)
1.21 Pacman running (DOM)
1.22 The wheels (DOM)
1.23 Bezier curves (Canvas)
HTML5 CANVAS and CSS3 by EXAMPLES 978-0-9777812-4-9 Graphics, Games, Animations 5
2. Basic Images ................................................................................................ 85
2.1 Images with rounded corners
2.1.1 Images with rounded corners (CSS3)
2.1.2 Div with rounded-corner image (CSS3)
2.2 Images with rounded corners
2.2.1 Images with rounded corners (Canvas)
2.2.2 Import image with img~ tag (Canvas)
2.2.3 Import image with "new Image()" object (Canvas)
2.2.4 More details on .drawImage() (Canvas)
2.2.5 Rounded corner in canvas (Canvas)
2.3 A CSS3 pie
2.3.1 A CSS3 pie by clipping (CSS3)
2.3.2 A pie with image by clipping (Canvas)
2.3.3 Clipping with random shapes (Canvas)
2.4 Cropping Images
2.4.1 Cropping Images with CSS3 (CSS3)
2.4.2 Clipping Images with CSS3 (CSS3)
2.4.3 Expand sprite sheet into tiles (Canvas)
2.4.4 Expand sprite sheet into tiles (DOM)
2.5 Expand images into tiles
2.5.1 Expand images into tiles (Canvas)
2.5.2 Display image by Irame (Canvas)
2.5.3 ShuIIling image tiles (Canvas)
2.5.4 ShuIIling image tiles (DOM)
2.6 Background with multiple images
2.6.1 Background with multiple images (CSS3)
2.6.2 Background with multiple canvas & z-index (CSS3)
2.6.3 Background with multiple images (Canvas)
2.7 Adding text to image
2.7.1 Adding text to image (Canvas)
2.7.2 Creating image Iile Irom scratch (Canvas)
2.8 Duplicate canvas image drawing with .toDataURL()
2.8.1 Duplicate canvas image drawing with .toDataURL() (DOM)
2.8.2 Duplicate canvas drawing with .getImagaData/.putImageData
(DOM)
HTML5 CANVAS and CSS3 by EXAMPLES 978-0-9777812-4-9 Graphics, Games, Animations 6
3. Basic Interactive ...................................................................................... 131
3.1 Cursor Position
3.1.1 Cursor Position (Canvas)
3.1.2 Cursor Position (DOM)
3.1.3 Detecting keyboard codes (Canvas)
3.1.4 Plot circles with multiple Iingers (Canvas)
3.2 Interactive Drawing Basic
3.2.1 Drawing with touch and mouse move (Webkit)
3.2.2 Drawing with MSPointer (Touch & Mouse Ior Window-8)
3.2.3 Integrating support Ior MSPointer (Mouse & Touch)
3.3 Plot shapes
3.3.1 Plot shapes (Canvas)
3.3.2 Plot shapes (DOM)
3.4 Drawing by Click-n-drag & Touch-n-drag
3.4.1 Free-hand Drawing (Touch/Click-n-drag)
3.4.2 Free-hand Drawing with selected colors (Touch/Mouse)
3.4.3 Drawing with jQuery (DOM)
3.4.4 Drawing with DOM-based (DOM)
3.5 Making Things Move Interactively
3.5.1 Move by Cursor (Canvas)
3.5.2 Rotating needle by Arrows (Canvas)
3.5.3 Move by Arrows (Canvas)
3.5.4 Move by Arrows (DOM)
3.5.5 Ball Auto (Canvas)
3.5.6 Ball Auto (DOM)
3.5.7 Move Ball with CSS3 transition (CSS3)
3.6 Moving shapes interactively
3.6.1 Moving shapes by Touch/Click-n-drag (Canvas)
3.6.2 Moving shapes with HTML5 native Drag-n-Drop (Canvas)
3.6.3 Moving a shape by Click-n-Drag with JQuery (DOM)
3.6.4 Hovering to move the images (CSS3)
3.6.5 Moving a group oI shapes (Canvas)
3.6.6 Cloning shapes interactively (Canvas)
HTML5 CANVAS and CSS3 by EXAMPLES 978-0-9777812-4-9 Graphics, Games, Animations 7
4. Basic Animation ........................................................................................ 181
4.1 Things that spin
4.1.1 Spinning Image (Canvas)
4.1.2 Spinning Image (CSS3)
4.1.3 Spinning Shape (Canvas)
4.1.4 Spinning Shape (CSS3)
4.1.5 Spinning Earth with Ioreground (Canvas)
4.1.6 Spinning moons (Canvas)
4.2 Things that go around
4.2.1 Spinning balls (Canvas)
4.2.2 Rotating balls (Canvas)
4.2.3 spinning seal message (Canvas)
4.2.4 spinning text (Canvas)
4.2.5 Walking stick (Canvas)
4.3 Things that work
4.3.1 Earth Boring Machine (Canvas)
4.3.2 Spinning Wheels (Canvas)
4.3.3 Spinning Wheels (Canvas)
4.3.4 Zomming circles (Canvas)
4.4 Thing that bounce
4.4.1 Bouncing ball (Canvas)
4.4.2 ouncing ball (CSS3)
4.4.3 Bouncing ball with jQuery .animate() (DOM)
4.4.4 Bouncing ball with jQuery/CSS3 (DOM)
4.4.5 Bouncing Ball with image and Noise (Canvas)
4.4.6 Bouncing and rotating ball with CSS3 (DOM)
4.4.7 Bouncing and spinning (Canvas)
4.4.8 A trail oI balls (Canvas)
4.5 Things that scroll
4.5.1 Scrolling Background move right (Canvas)
4.5.2 Scrolling Background with jet (Canvas)
4.5.3 Scrolling Background move right (CSS3)
4.5.4 Scrolling Background with jet (CSS3)
HTML5 CANVAS and CSS3 by EXAMPLES 978-0-9777812-4-9 Graphics, Games, Animations 8
5. Advanced Shapes ................................................................................... 253
5.1 Horizontal Bar Chart (DOM)
5.1.1 Horizontal Bar Chart (Canvas)
5.1.2 Horizontal Bar Chart with multiple data (Canvas)
5.1.3 Animating Horizontal Bar Chart (Canvas)
5.1.4 Animating one bar at a time (Canvas)
5.2 Vertical Bar Chart (Canvas)
5.2.1 Vertical bar chart (DOM)
5.2.2 Animation vertical bar Chart (DOM)
5.3 A Fixed Pie (CSS3)
5.3.1 ModiIy the Iixed pie (DOM)
5.3.2 Pie Chart (Canvas)
5.3.3 Pie Chart with images (Canvas)
5.3.4 Pie Chart (DOM)
5.3.5 Pie Chart with greater than 180 degree (DOM)
5.4 XY Graph Chart (Canvas)
5.4.1 XY Graph Chart (DOM)
5.4.2 Background Grid (CSS3)
5.4.3 Line Chart (DOM)
6. Advanced Interactive ............................................................................... 265
6.1 Interactive Drawing Shapes (Canvas)
6.1.1 Drawing With Click-n-Dag and Touch-n-Drag (Canvas)
6.1.2 JavaScript with two canvases (Canvas)
6.1.3 JavaScript with one canvas (Canvas)
6.2 Interactive Drawing Shapes (DOM)
6.2.1 Drawing rectangles (DOM)
6.2.2 Drawing shapes (DOM)
6.3 Drawing With Click-n-Dag and Touch-n-Drag
6.3.1 Drawing & Moving shapes (canvas)
6.4 Processing shapes
6.4.1 Splitting shapes (Canvas)
6.4.2 Splitting & Intersecting shapes (Canvas)
HTML5 CANVAS and CSS3 by EXAMPLES 978-0-9777812-4-9 Graphics, Games, Animations 9
7. Advanced Images ......................................................................................... 289
7.1 Image manipulation
7.1.1 Free-hand drawing on image (Canvas)
7.1.2 Changing the dog color at pixel level (Canvas)
7.1.3 Transition the dog color (Canvas)
7.2 Sprite Animation
7.2.1 Basic Sprite animation (Canvas)
7.2.2 Earth rotation (Canvas)
7.2.3 Exploring Sprite (Canvas)
7.2.4 Walking man (Canvas)
7.2.5 CSS3 sprite (CSS3)
7.3 Cropping image (Canvas)
7.3.1 Cropping image with click-n-drag move (Canvas)
7.3.2 Zooming with image in circle (Canvas)
7.3.3 Cropping image with Touch-n-Drag move (Canvas)
7.3.4 Cropping image with one-Iinger touch (Canvas)
7.3.5 Cropping image with zooming rectangle (Canvas)
7.3.6 Cropping image with Touch-n-Drag (Canvas)
7.3.7 Cropping image with two-Iinger touch (Canvas)
8. Advanced Animation ............................................................................... 311
8.1 Things that popup
8.1.1 Popping and Rise/Fall (Canvas)
8.1.2 Popping and Rise/Fall (DOM)
8.1.3 Popping and move to close to cursor (Canvas)
8.1.4 Candy Quality Control (Canvas)
8.1.5 Ball sweeper (Canvas)
8.2 Parallax animation
8.2.1 Background Parallax (Canvas)
8.2.2 Background with moving clouds (Canvas)
8.2.3 Background with moving clouds (CSS3)
8.2.4 Moving clouds with diIIerent speeds (Canvas)
8.2.5 Moving clouds with diIIerent speeds (CSS3)
8.3 Solar System
8.3.1 Earth circular orbit (CSS3)
8.3.2 Earth elliptical orbit (Canvas)
8.3.3 Earth and its moon (CSS3)
8.3.4 Earth and its moon (Canvas)
8.3.5 Solar System (CSS3)
HTML5 CANVAS and CSS3 by EXAMPLES 978-0-9777812-4-9 Graphics, Games, Animations 10
8.3.6 Solar System (Canvas)
8.3.7 Solar System 2 (Canvas)
9. Game Essentials ......................................................................................... 361
9.1 Shooting (DOM)
9.1.1 Shooting a bullet (DOM)
9.1.2 A Jet Fighter (DOM)
9.1.3 A Jet Fighter-Bomber (DOM)
9.2 Shooting (Canvas)
9.2.1 Rotating Gun Station (Canvas)
9.2.2 Moveable Gun Station (Canvas)
9.2.3 Shooting a string oI bullets (Canvas)
9.2.4 Shooting a Iixed target (Canvas)
9.3 Pacman essentials
9.3.1 Pacman Turning (Canvas)
9.3.2 Pacman Turning (DOM)
9.3.3 Blinky Walking with shapes (Canvas)
9.3.4 Blinky Walking with images (Canvas)
9.3.5 Pacman baby (Canvas)
9.4 Pacman in maze
9.4.1 Tiling background (Canvas)
9.4.2 Pacman in maze (Canvas)
9.4.3 Pacman in random maze (Canvas)
10. Basic Games ............................................................................................ 405
10.1 Shooting games
10.1.1 Shooting planes with rotary gun station (Canvas)
10.1.2 Shooting balloons (Canvas)
10.1.3 Shooting jet Iighters (Canvas)
10.2 Ball games
10.2.1 Paddling bouncing ball (Canvas)
10.2.2 Paddling bouncing ball (DOM)
10.2.3 Bouncing ball game (DOM)
10.3 Pacman games
10.3.1 Pacman Junior (Canvas)
10.3.2 Pacman Senior (canvas)
HTML5 CANVAS and CSS3 by EXAMPLES 978-0-9777812-4-9 Graphics, Games, Animations 11
Introduction
For years, I have been exploring and has written many topics in graphics and
animations Ior Perl, Python and Ruby. Then came HTML5 canvas, which is certainly
one oI the most exciting Ieatures oI HTML5. Now we can have animations and we
can interactively draw shapes directly on the screen without the help oI any plugin
soItware. This was an impossible task, prior to the arrival oI HTML5 canvas.
The other workhorse or cornerstone oI HTML5 progress is the release oI CSS3 new
Ieatures like transition and animation. We can build animations and games in both
HTML5 canvas and in pure CSS3 with DOM elements.
In this book, we will explore the graphics in both HTML5 canvas as well as in CSS3.
In Iact, we attempt to duplicate each example in HTML5 canvas into its CSS3 DOM
equivalence. For example, iI we build a bouncing-ball animation script Ior HTML5
canvas, we also build a similar script in CSS3 with the DOM elements (i.e. mainly
with the div tags and without the canvas tag.) The author believes that this way oI
learning via the "Rosetta-Stone" Iormat with side-by-side examples is the best way to
learn new things, including any programming language.
The book does make assumptions that you have some basic knowledge about
programming in HTML, JavaScript and CSS. II not, don't worry. You just go with
the slower pace. To make liIe easier Ior beginners, all the examples in this book are
completely selI-contained. The examples are also "miniIied" to save space. We also
attempt to limit the average code size Ior each example to two pages with the hope
that the readers will not loose interests in looking at the short and concise code
details. The author strongly believes that the best way to learn is to learn by
examples.
Touch Screen
The world oI electronic gadgets is moving toward more touchscreen devices. It is
conceivable that in the very near Iuture, all computing devices including laptops will
have touchscreen capability. The prooI is the recent release oI Google Chromebook
Pixel and Window-8 by MicrosoIt with its touchscreen capability as one oI the main
Ieatures. Other companies will Iollow soon. The author has made every eIIort to
make all examples in this book to be touchscreen Iriendly. Yes, touchscreen
interactivity like gesture is the hot topic Ior the moment, mainly targeting comsumer
devices. But other conventional user interIaces like mouse and keyboard will not go
away; in Iact they are needed to do serious works in productivity devices.
HTML5 CANVAS and CSS3 by EXAMPLES 978-0-9777812-4-9 Graphics, Games, Animations 12
HTML5: The Language oI the Web
HTML5 is the reincarnation oI HTML mark-up language. The internet explosion
started when the last major release oI HTML4 was released Iourteen years ago.
There is no new major release oI HTML version since then. For the Iast-pacing oI
the internet era, the 14-year lapse is eternally long. Now with the HTML5 release,
the internet will again 'explode' to a new height. Some would claim that HTML5 is
not evolutionary, but revolutionary, shiIt Irom its older version HTML4. HTML5
will revolutionize the web industry again.
With the recent introduction oI the latest electronic gadgets like Apple and Google
phones and tablets, Giant social network companies like Facebook and Twitter also
announced that they plan Ior HTML5 as 'ultimate intent is to build an alternative
platIorm giving users the ability to easily install webapps" and also Ior the Iuture oI
online social gaming. It seems that the world is moving to HTML5. The hugely
popular YouTube, which previously used Flash, now can be run with HTML5.
Some oI many game-changing Ieatures oI HTML5 are audio, video, canvas, geo-
location, local storage and others. With the canvas tag alone, we now can draw
shapes like rectangles, graphs or even animations directly to the webpage. This is an
impossible task with HTML4. The canvas tag will change the landscape oI the game
industry as well as the educational delivery medium Ior years to come.
Just Ior a personal Iootnote on the powers oI HTML, all the author's engineering
technical notes and all the author's books as well are written and documented with
almost exclusively with HTML alone.
1avaScript: The Language oI the Browsers
JavaScript is known as the scripting language oI the web. With the web everywhere,
JavaScript is also everywhere. II you plan to work in any web development,
JavaScript may be your only choice. Without JavaScript, HTML would be a boring
place. JavaScript supercharges the web with dynamic interaction and almost
instantaneous response at the user request.
JavaScript is not designed to be a general-purpose programming language. Nor it is
designed to be a stand-alone language. It is designed to be an embedded client-side
programming language within the HTML Iramework. HTML by itselI lacks the Iull
processing capability oI a programming language. Fortunately, we can insert
JavaScript programs into the mists oI HTML code itselI, to explore the Iull powers oI
a programming language inside HTML environment. HTML together with
HTML5 CANVAS and CSS3 by EXAMPLES 978-0-9777812-4-9 Graphics, Games, Animations 13
JavaScript (and ) brings the web application programming to a new level oI
experiences.
With JavaScript, we can do programming work with the browser and the browser
only. For novice programmers or casual scripters like scientists and engineers, it's
very convenient that we can program the HTML webpage with the Iull capability oI
a programming language to process data, without the headache oI loading any
external soItware. Yes, there is no need Ior uploading or downloading any soItware
beIore we start do real programming. JavaScript is typically built-in in the browser.
: More than just the Styling Language
CSS3 is the latest version oI CSS (Cascade Style Sheets). There is no question that a
good web developer should master HTML5 CSS3 JavaScript. CSS3 is the styling
language Ior displaying the HTML elements. HTML5 CSS3 JavaScript is the
Iuture oI the web development. With CSS3, we can draw amazing picture and
perIorm animation with or without the help oI JavaScript.
Some new Ieatures oI CSS3 are border-radius Ior rounded corners, multiple
background images, multiple columns, complex matrix transIorm, etc... CSS3 is the
living styling language and constantly get upgraded with new Ieatures. For example,
the latest Ieature is the webkit transition and animation. The code below is to create
animation oI the bouncing ball with pure CSS3 (i.e. no JavaScript involved)
.earth { background-image.url(globe128.png),
-webkit-animation. moving 5s linear infinite , J
-webkit-keyframes moving {
0 {-webkit-transform. translate(80px,0px) J
25 {-webkit-transform. translate(220px,080px) J
50 {-webkit-transform. translate(100px,200px) J
75 {-webkit-transform. translate(-30px,100px) J
100 {-webkit-transform. translate(80px,0px) J
J
A word oI caution: CSS3 development is an on-going progress. The level oI CSS3
support get updated Irequently by the browsers. At the moment, we have to deal with
the issues that diIIerent browsers support CSS3 at diIIerent levels. It's being quoted
as "progressive enhancement" or "graceIul degradation". Some said "CSS is easy to
learn and but it's hard to master". This is even more true with CSS3.
HTML5 CANVAS and CSS3 by EXAMPLES 978-0-9777812-4-9 Graphics, Games, Animations 14
jQuery: Write Less Do More
The slogan oI jQuery is "more programming with less code". Just like the goal oI any
library or Iramework development, jQuery is a JavaScript library to simpliIy coding
Ior productivity purpose. There are other JavaScript libraries like YUI, Dojo and
Mootols. But jQuery is the most widely used.
Avoid buying books with any specific framework. In general, when we start
exploring a new language, it's best that we avoid using any particular library or
Iramework. But Ior the author, jQuery is the exception because jQuery has potential
to become one oI the de-Iacto standard libraries Ior HTML5.
Some oI the main Iunctions oI jQuery are to provide (1) convenient selectors oI
DOM elements, (2) CSS manipulation Ior styling the elements, (3) user-Iriendly
event handling Ior user interIace, (4) some built-in or custom animation, and (5)
common cross-platIorm interIace with diIIerent browsers and plug-in modules.
The selector/manipulation Iunction oI jQuery is equivalent and powerIul as the
"map/grep" oI the Unix world. For example, the code below is to select and move all
'span' elements in the DOM tree with the classname ID oI 'bomb' to the new position.
Just imagine how many lines oI code that are required to implement this Iunction in
pure JavaScript? This is the power oI jQuery library.
$(span[classbomb]).each( function(){
var top parseInt($(this).css("margin-top")),
$(this).css("margin-top", top1)
J),
II you are new to jQuery, we should take time to study the Iirst Iew examples oI
chapter 1, where we try to code the examples with jQuery and without jQuery, Ior
comparion purpose.
HTML5 CANVAS and CSS3 by EXAMPLES 978-0-9777812-4-9 Graphics, Games, Animations 15
Canvas-based versus DOM-based graphics
As one would expect, the canvas-based graphics is based on the canvas tag and the
canvas API to draw the primitive shapes at pixel level inside the canvas. DOM-based
graphics implies that no canvas~ element is involved. DOM-based graphic is based
primarily on div~ elements. Each div element gets styled by CSS3 into diIIerent
shapes.
A big diIIerence between canvas-based and DOM-based graphics is that canvas-
based graphic is "immediate mode" with draw-and-Iorget approach while DOM-
based graphic is considered "retainer mode" with all drawn objects getting saved.
Each div drawn in DOM-based is treated as an object, which can be modiIied or
reconIigured.
Canvas-based animation requires clearing the canvas and re-drawing every shape in
the canvas Ior each Irame. DOM-based animation re-draws only objects that get
changed by re-conIiguring the properties oI those objects only.
Canvas-based DOM-based
0 Based on canvas~ tag Other DOM elements except canvas
1 canvas~ : a place to draw pixels div~ span~ tag as container object
2 Primitive shapes: .arc() .strokeRect() .lineTo() many divs (styled by CSS3)
3 low-level drawing (at pixel level) high-level drawing (create object)
4 immediate mode retainer mode
5 draw and Iorget object reconIigurable
6 reIresh & redraw the whole canvas redraw selected divs only
7 can draw complex shapes medium-complex shapes
8 draggable eIIect diIIicult draggable eIIect easy
9 create objects with properties selector by jQuery
10 no individual identity retain individual identity
11 circle with arc() div with border-radius
Canvas-based vs. DOM-based
HTML5 CANVAS and CSS3 by EXAMPLES 978-0-9777812-4-9 Graphics, Games, Animations 16
Testing the examples
The examples in this book are tested with the Iour popular browsers in MicrosoIt
Window7 PC desktop environment: MicrosoIt Internet Explorer IE-10, Google
Chrome, Apple SaIari and Mozilla FireIox. The examples with touch-screen action
get tested with the three dominant mobile operating system platIorms: Apple IOS
and Google Android, and MicrosoIt Window-8. For touch-screen devices, we select
the latest mobile tablets, at the time oI this writing, to test the examples: MicrosoIt
SurIace RT Ior Window-8, Apple iPad3 Ior IOS device and Google Nexus
10/Samsung Galaxy Note 10.1 Ior Android devices.
Testing with IOS
Apple maintain two separate operating systems (OS): MacOs Ior Mac computers and
IOS Ior mobile devices like the iPad and iPod. To test the examples with iPad3 in
IOS environment, we need to transIer all the Iiles to iPad3. IOS does not provide any
native application to download, manage and execute the HTML5 Iiles directly.
For us, we download the "GoodReader" app and use iTunes to transIer all the Iiles to
iPad3. With the "Manages Iiles" tab in GoodReader, we move the example Iiles to
where ever we want in the Iile directory hierarchy. To execute the examples, we
select "Preview" tab in GoodReader and simply click on the .html example icon. You
will see the executed webpage on the screen Ior that example. You can open
many .html Iiles as you like.
We also use "textastic" app to test the codes but we use Textastic mainly Ior editing
the code. Opening an .html with textastic is easy with a simple click. However, you
can only open one html Iile at a time. And yes FireBug is bugged is there. The Iinal
word is that we can modiIy the codes in GoodReader environment but it is not
eIIicient. II you plan to do a lot oI typings, you should consider buying a bluetooth
keyboard.
Testing with Android
For Android, it's a lot simpler to transIer the example Iiles Irom PC to Samsung
Galaxy Note 10.1 and Nexus 10. There is no need to download any app. We simply
hook the connector between the PC and Android device, a small window "AutoPlay"
will pop up in the PC. Select "Open device to view Iiles" to open the tablet memory
Iile directory. Use click-n-drag to transIer the Iiles. To manage the Iiles even better,
you may want to download any Iree "Iile manager" Irom GooglePlay.
HTML5 CANVAS and CSS3 by EXAMPLES 978-0-9777812-4-9 Graphics, Games, Animations 17
We can click and open the html Iile with "HTMLviewer". But remember that
Android-native "HTMLviewer" has limited capability. To Iully execute an html
example, we need to open up a new Chrome browser window and type the Iile name
in. For example, iI we transIer and move the examples to /Root/sdcard/quan, then to
execute the html example, we type in the webpage browser:
file:///sdcard/quan/exam1.html or
file://Root/sdcard/quan/exam1.html
Testing with Microsoft Surface RT
Testing the MicrosoIt SurIace RT tablet is amazingly easy and convenient, thanks to
its intergrated touch/mouse user-interIace control. It's just like testing on the PC or
desktop environment. In Iact, you can open the "Desktop' icon on the SurIace,
transIer the Iiles via UBS port and test the examples in there.
For the author, one oI the advantage oI the surIace RT over other competitive tablets
is the native built-in physical keyboard, in addition to the virtual keyboard. The
arrow keystrokes, touch pad, and mouse clicking work seamlessly like in laptops or
desktops. Third-party bluetooth keyboards, that are used in many tablets, do help the
typings but have limitations.
On the personal note aIter toying with the MicroSoIt SurIace RT Ior Iew months, the
author Ieels like the design approach oI the SurIace RT, though it's not perIect in its
Iirst implementation, but it represents the Iuture design oI a modern tablet Ior more
Iunctional mobile productivity device out oI the box. My guess is that somedays
Apple will eventually Iollow MicrosoIt's Iootstep to integrate their IOS and MacOS
together. Similarly, in the Iuture Google may choose to merge Android and Chrome
into a single platIorm. Let's see.
The all-in-one "frig" is here
II we take and Iollow the printer business with all-in-one print/Iax/copy mode as a
guide, the Iuture computing device is likely to be all-in-one multi-Iunction mode
also, where a single device can transIorm into several convertible conIigurations:
laptop, desktop, and tablet modes.
HTML5 CANVAS and CSS3 by EXAMPLES 978-0-9777812-4-9 Graphics, Games, Animations 18
Tips for debugging in
II you are new and want to start playing around debugging with your HTML5 code,
modern browsers like Chrome provide a very convenient "JavaScript Console" by
clicking "Ctrl-ShiIt-J" (or hit Tools-~JavaScript Console) aIter you load the page.
The new window "Developer Tools" with two columns will popup. II you move the
cursor around on the leIt column, the webpage will reIlect to where you are pointing
the codes. Try it. It's very niIty. You can also type in the new command in the
command region to see the new eIIect on the webpage.
For example, aIter I load the codes in Example2.1.3.1, a rectangle shape will appear
in the webpage. I hit Ctrl-ShiIt-j at the webpage. The window above would popup.
AIter I type the below command, the rectangle shape in the webpage change to have
round corners.
~$('#myID').css( '-webkit-border-radius': 20 } ) ;
II I want to change the rectangle into a circle shape:
$('#myID').css('-webkit-border-radius':25, width:50, height:50 });
You may want to try other excellent independent debugging tools: jsIiddle.net,
dabblet.com and jsbin.com.
HTML5 CANVAS and CSS3 by EXAMPLES 978-0-9777812-4-9 Graphics, Games, Animations 19
Chapter 1
Basic Shapes
HTML5 CANVAS and CSS3 by EXAMPLES 978-0-9777812-4-9 Graphics, Games, Animations 20
1.0 Basic Shapes with CSS3 and HTML5 Canvas
1.1 Array of pixels (Canvas)
1.1.1 Random true/false generator (JavaScript)
1.1.2 Random number generator for range of numbers (JavaScript)
1.1.3 Random colors with RGB (Canvas)
1.2 Array of pixels (DOM)
1.2.1 Array of pixels (DOM & no jQuery)
1.2.2 Blinking pixels (Canvas)
1.2.3 Blinking pixels (DOM)
1.2.4 Walking pixels (Canvas)
1.2.5 Walking pixels (DOM)
1.2.6 Random colors with Hex #FFFFFF (Canvas)
1.3 Circles within circles (Canvas)
1.3.1 Random colors with HSL format (Canvas)
1.4 Circles within circles (DOM)
1.5 Random circles (Canvas)
1.6 Random circles (DOM)
1.7 Ring of circles (Canvas)
1.8 Ring of circles (DOM)
1.9 Spider web (Canvas)
1.10 Spider web (DOM)
1.11 Moon crescent (Canvas)
1.12 Moon crescent (DOM)
1.12.1 Moon crescent with pseudo-elements (CSS3)
1.12.2 Basic CSS3 shapes (CSS3)
1.12.3 Moon crescent with color gradient (Canvas)
1.12.4 Moon crescent with color gradient (DOM)
1.13 Circle of text (Canvas)
1.14 Circle of text (DOM)
1.15 Circular text (Canvas)
1.16 Circular text (DOM & no jQuery)
1.17 Balloon popup (Canvas)
1.18 Balloon popup (DOM)
1.19 Pacman running (Canvas)
1.20 Pacman running (CSS3)
1.21 Pacman running (DOM)
1.22 The wheels (DOM)
1.23 Bezier curves (Canvas)
HTML5 CANVAS and CSS3 by EXAMPLES 978-0-9777812-4-9 Graphics, Games, Animations 21
1.0 Static Shapes
Static graphics is about creating still images. No user interaction is involved. Static
images are created by painting the primitive shapes into the HTML5 canvas with the
help oI JavaScript. Similarly, we can also paint the primitive shapes into the non-
canvas DOM-based graphics with the help oI jQuery. With the new Ieatures oI
HTML5 and CSS3 properties, the created images can be visually very realistic,
vibrant, and exciting.
The goal oI this chapter is to show the readers oI how to create images Irom scratch.
The images are painted into the HTML5 canvas. Each example will also be
duplicated into an equivalent DOM-based graphics with the help oI jQuery. BeIore
we delve into details oI the examples, we like to go over what's the diIIerence
between the examples oI canvas-based and DOM-based graphics.
The examples are labeled with three categories: 1.(Canvas) 2.(DOM) 3.(CSS3).
Example with label (Canvas) is based on canvas tag and javaScript; we draw shapes
and images into the canvas contents with the help oI javaScript. Example with label
(DOM) is DOM-based graphics, which we style the divs into desired shapes with or
without the help oI jQuery. Example with label (CSS3) is based on pure CSS3 code:
no canvas tag nor javaScript is involved.
Sub-label Languages Tag elements
1 (Canvas) JavaScript canvas
2 (Canvasj) JavaScript jQuery canvas
3 (CSS3) Pure CSS3 div tags; no canvas
4 (DOM) JavaScript div tags; no canvas
5 (DOMJ) JavaScript jQuery div tags; no canvas
Example Catagory
In this chapter, we introduce the canvas, the meaning oI pixel, basic random number
generator, color Iormat schemes (i.e. RGBA and HSLA), and color gradient in the
Iirst Iew examples. We will go over how to transIorm and rotate text into circular
shape. Besides covering static images in this chapter, we also provide a sneak
preview oI animation with HTML5 canvas and with CSS3.
It is essential that the readers read, test and comprehend most oI the examples beIore
going to the next chapter. The reader should get a taste oI what the book is about.
HTML5 CANVAS and CSS3 by EXAMPLES 978-0-9777812-4-9 Graphics, Games, Animations 22
1.1 Array of pixels (Canvas)
The task is create multiple an array oI squares
with random colors. Each square contains a
circle. ReIresh the webpage Ior diIIerent
colors. The goal oI the script is to explore
ways to generate random color in RBGA (Red
Blue Green Alpha) Iormat:
* RGBA rgba( 255 , 255 , 255 , 1 )
<htmI>
<body>
<canvas id="myCanv" styIe="border:1px dashed red">
You use oId browser: no support for canvas. Get new version!!
</canvas>
<script>
function init() { // - - init
canv = document.getEIementById("myCanv") ; // defauIt: 300 x 150 px
ctx = canv.getContext("2d") ; //
num = 10 ; // # of squares per axis
s = canv.height/num ; // 20x10 squares (15px)
s = canv.width/num ; // 10x5 squares (30px)
for (var j = 0; j < canv.height; j+=s) { // iterate coIumn
for (var i = 0; i < canv.width; i+=s) { // iterate row
var red = Math.fIoor(Math.random() * 255 ) ; // red Math.ceiI()
var green = Math.fIoor(Math.random() * 255 ) ; // green 0-255
var bIue = Math.fIoor(Math.random() * 255 ) ; // bIue
var aIpha = Math.random() ; // aIpha 0.00-1.00
var rgba = "rgba(" +red +", " +green +", " +bIue +", " +aIpha +")" ;
ctx.fiIIStyIe = rgba ; // set fiIIStyIe for rect
ctx.fiIIRect(i,j,s,s) ; // draw rect
ctx.fiIIStyIe= "rgb("+ green +", "+ bIue +", "+ red +")"; // set fiIIStyIe for circIe
ctx.beginPath() ; // new path
ctx.arc( i+s/2, j+s/2, s/2, 0,Math.PI*2,faIse) ; // sketch circIe
ctx.fiII() ; // draw circIe
}
}
}
window.onIoad = init ; // wait for DOM
</script> </body> </htmI>
HTML5 CANVAS and CSS3 by EXAMPLES 978-0-9777812-4-9 Graphics, Games, Animations 23
Try to reIresh the webpage. You will get diIIerent colors every time you reIresh. You
will not get bored. This is the beauty oI random color generation. Most examples in
this book involve random color generation. Take times to study it. Random color
generation with HEX Iormat and HSLA Iormat are discussed in examples 1.2 and
1.3, respectively. In the script, we create two loop iterations, one Ior row and the
other Ior column. We also generate color with RBGA and RBG. The RBG Iormat is
the same as RGBA but without opacity. The numbers used Ior RGBA are generated
randomly. We set the color with "ctx.IillStyle" beIore we actually draw the shape
with "ctx.Iill()" command.
<canvas id"myCanv" style"border:1px dashed red">
Since we do not speciIy the width and height oI the canvas, the deIault size is 300 x
150 pixels: 300 pixels in horizontal direction and 150 pixels in vertical down
direction. A good practice is to put CSS styling codes in a separate Iile. But to save
space, we also "miniIy" the codes with in-line CSS coding and short-hand notation.
CSS statement style"border:1px dashed red" is the short Iorm oI:
<style> canvas border-width:1px; border-style:dashed; border-color:red ]
</style>
s canv.width/num ;
The canvas size is deIaulted to 300x150 pixels iI the user does not speciIy its size. In
the script, we like to have ten squares Ior the x-axis so we set num10. The size oI
the square is 30x30 pixels. There would be a total oI 50 squares (10 x5). II we set:
* s canv.height/num ;
The size oI the square is 15x15 pixels. There would be 200 squares ( 20 x 10).
The colors of HTML5/CSS3
In HTML5, we can use several Iormats Ior the colors. Formats RGBA and HSLA
allow alpha transparency/opaque option. The other option is to speciIy RBG and
HSL Ior colors Iirst , then set opacity0.5.
HTML5/CSS Colors Alpha
1 RGBA rgba( Red, Green, Blue, Alpha ) rgba( 255 , 0 , 100 , 0.5 ) 0 opaque
2 HSLA hsla( Hue, Saturation, Lightness, Alpha ) hsla( 360 , 0 , 100 , 1.0 ) 1 transparent
3 RGB rgb( Red, Green, Blue ) rgba( 255 , 0 , 100 )
4 HSL hsl( Hue, Saturation, Lightness ) hsla( 360 , 0 , 100 )
5 CMYK cmyk( Cyan, Magenta, Yellow, Black ) cmyk( 0.0 , 1.0 , 0.5 , 0.5 )
6 HEX #RRGGBB #II0034
7 Colors red skyblue lightcyan darkorange mediumorchid lightblue aqua
HTML5 CANVAS and CSS3 by EXAMPLES 978-0-9777812-4-9 Graphics, Games, Animations 24
Random Number Generator
Is there a practical need Ior random number generation? Yes, deIinitely, especially in
game design. Random-number generation enhances the excitement in game play by
introducing the unpredictability Iactor. Study it careIully. In this book, we have used
random-number-generator extensively to create exiting animation and game designs.
Why do we need a random number generator? There are many applications using
random number as their basic Iabric operation like the slot machines. Many examples
in this book use random number. In game development, we do not want a predictable
pattern but we want some random patterns to keep the game interesting and
challenging. In this sub-section, we will go over how to generate:
1.1.1 Random true/Ialse binary integer
1.1.2 Random integer with range oI 20 to 300
1.1.3 Random color in the RGBA Iormat with the range oI RGBA(0,0,0,0) to
RGBA(255,255,255,1)
1.1.1 Generating random number with 0 (false) or 1 (true)
We want to generate a true/Ialse random integer, based on 0 Ior Ialse and 1 Ior true.
The basic random generator Ior JavaScript is Math.random(), which generates a
decimal number between 0.0 and 1.0. We categorize the number into low or high
number. Low number below 0.5 would be set to zero. High number above 0.5 would
be set to one. The trick to generate binary integer 0 or 1 is to multiply the
Math.random() number by 2 to get random number Irom 0.0000 to 1.99999. We then
extract the base number without decimal. The result is either a 1 or a 0.
1 Math.random() generates 0.000 to 1.0000 0.7345234623
2 Math.random() * 2 generates 0.000 to 1.99999 1.4690469246
3 Math.Iloor(Math.random() * 2 ) generates 0 or 1 1
Generate random number either 0 or 1
There are other alternative ways to generate random true/Ialse variable:
1 Ilag ( Math.Iloor( Math.random() * 2 ) ? "true" : "Ialse" ;
2 iI ( Math.random() ~ 0.49999 ) Ilag"true" } else Ilag"Ialse" } ;
3 Ilag ( Math.random() 0.49999) ? "true" : "Ialse" ;
4 Ilag ( Math.Iloor( Math.random() 0.5 ) ? "true" : "Ialse" ;
HTML5 CANVAS and CSS3 by EXAMPLES 978-0-9777812-4-9 Graphics, Games, Animations 25
1.1.2 Generating random number with range of 20 to 300
In this script oI 1.1.1, we choose the color, the position and the size oI any ball
randomly to make sure that the chance oI two balls having the same color or size is
unlikely. Let say we want to generate a random integer number between 20 and 300
Ior the ball size.
1 Math.random() generates 0.000 to 1.0000 0.7345234623
2 Math.random() * 280 generates 0.000 to 280.0000 250.66656944
3 Math.Iloor(Math.random() * 280 ) generates 0 to 280 250
4 Math.Iloor(Math.random() * 280) 20 generates 20 to 380 270
Generate random number between 20 and 300
We start with Math.random() method which generates random number between 0
and 1, like 0.7345234623. Next we multiply it by 280, which results in number
between 0.0000 and 280.0000, like 250.6665694444. We then extract the base
number (i.e. no decimal) using Math.Iloor() method, like 250. Finally, we add 20 to
make sure that 20 is the minimum number. We could also increase the randomness
level by providing random seed like Math.random((Math.random()).
Math.floor(Math.random() ` 10) + 10 ~ get number between 10 and 20
Math.floor(Math.random() ` 10) + 90 ~ get number between 90 and 100
To generate a range oI integers between negative and positive number, we simply
use the subtraction.
1 Math.random() * 2 - 1 get Iloating number between -1.00 and 1.00
2 Math.Iloor(Math.random() * 20) - 10 get number between -10 and 10
3 Math.Iloor(Math.random() * 100) - 50 get number between -50 and 50
The pixel
The pixel (px) unit is deIined as the smallest addressable (and visible) element in a
display device. One pixel is equal to one dot on the computer screen. The pixel does
not scale to mobile devices. All examples in this book use "pixel" unit Ior setting the
dimension oI the objects like the canvas size. It's worth mentioning that there are
other Iont sizes: px em pt cm mm pc in.
1in 2.54cm 25.4mm 72pt 12pc
1em 12pt 16px 100
HTML5 CANVAS and CSS3 by EXAMPLES 978-0-9777812-4-9 Graphics, Games, Animations 26
1.1.3 Generating random color with RGBA(0-255,0-255,0-255,0-1) (Canvas)
RBG stands Ior Red, Green and Blue. We can
set the range oI rgb(0, 0, 0) to rbg( 255, 255,
255) to get any desired color. II we want to
speciIy opacity property along with the color,
we can use more advanced RGBA scheme. A
is Ior Alpha opacity. RGB is the same as
RGBA but without opacity property. Alpha
range is between 0.00 and 1.00. Alpha opacity is set to "0" Ior Iull transparency and
"1" Ior Iull opaque. To generate random color, we simply need to create three
random integer number between 0 and 255. Math.random() is used to generate
decimal number Irom 0.000 to 0.999 Ior opacity.
<htmI> <body> <canvas id="myCanv" width=600 height=600 > </canvas>
<script>
function init() { // - - init
var canv = document.getEIementById("myCanv"); // get canv DOM object
var ctx = canv.getContext("2d"); //
var w = 70 ; var h = w/2 ; // rect size
ctx.fiIIText( "rgb( RR, GG , BB )" , 100, 220) ; //
for (var j = 0; j < 6; j++) { // 6 coIums
for (var i = 0; i < 5; i++) { // 5 rows
var red = Math.ceiI(Math.random() * 255 ) ; // random red
var green = Math.ceiI(Math.random() * 255 ) ; // random green
var bIue = Math.ceiI(Math.random() * 255 ) ; // random bIue
if (j==4) { // for 2nd Iast row
if (i==0) { red = 255 ; green = 255 ; bIue = 0 } ; // yeIIow 255 255 0
if (i==1) { red = 255 ; green = 0 ; bIue = 255 } ; // pink 255 0 255
if (i==2) { red = 0 ; green = 255 ; bIue = 255 } ; // IighbIue 0 255 255
if (i==3) { red = 256 ; green = 128 ; bIue = 0 } ; // dark-orange 256 128 0
if (i==4) { red = 256 ; green = 0 ; bIue = 128 } ; // dark-pink 256 0 128
}
if (j==5) { // for Iast row
if (i==0) { red = 255 ; green = 0 ; bIue = 0 } ; // red 255 0 0
if (i==1) { red = 0 ; green = 255 ; bIue = 0 } ; // green 0 255 0
if (i==2) { red = 0 ; green = 0 ; bIue = 255 } ; // bIue 0 0 255
if (i==3) { red = 255 ; green = 255 ; bIue = 255 } ; // white 255 255 255
if (i==4) { red = 255 ; green = 128 ; bIue = 128 } ; // bIack 0 0 0
}
HTML5 CANVAS and CSS3 by EXAMPLES 978-0-9777812-4-9 Graphics, Games, Animations 27
var rgb = "rgb("+ red +", "+ green +", "+ bIue +")" ; // rbg
ctx.fiIIStyIe = rgb ; // set rect coIor
ctx.fiIIRect( i*w , j*h , w, h ); // draw rect
ctx.fiIIStyIe="bIack"; // draw text
ctx.fiIIText( red +" "+ green +" "+ bIue , i*w+3, j*h+h/2 );
}
}
}
window.onIoad = init ; // run script
</script> </body> </htmI>
In the script, we create Iive columns and six rows oI rectangle blocks. The colors oI
the blocks are generated randomly. For the last row, we hardcode the colors Ior the
blocks: red, green, blue , and white.

1 rgb( 255, 0, 0 ) red
2 rgb( 0, 255, 0 ) green
3 rgb( 0, 0, 255 ) blue
4 rgb( 0, 0, 0 ) black
5 rgb( 255, 255, 255 ) red green blue ~ white
6 rgb( 255, 255, 0 ) red green ~ yellow
7 rgb( 255, 0, 255 ) red blue ~ pink
8 rgb( 0, 255, 255 ) green blue ~ lightblue
For more discussions on other color schemes, check examples:
1.1.3 Random colors with RGB rbg(255,255,255)
1.2.6 Random colors with Hex #FFFFFF
1.3.1 Random colors with HSL hsl(360, 100 100)
3.3.1 Selected color with color picker with input type"color" . . ~
HTML5 CANVAS and CSS3 by EXAMPLES 978-0-9777812-4-9 Graphics, Games, Animations 28
1.2 Array of pixels (DOMJ)
The task is create multiple an array oI squares
with random colors in the DOM-based
graphics. No canvas is involved. Each drawn
square contains a circle. The goal oI the script
is to explore ways to generate random color
with hex Iormat: #FFFFFF #RRGGBB
The other goal is to understand how to create new DOM elements with the help oI
jQuery. The script makes direct link to the Google jQuery. II you do not have
Internet, you have to down jQuery Iirst beIore testing the script.
<htmI>
<head>
<script src="http://ajax.googIeapis.com/ajax/Iibs/jquery/1/jquery.min.js"></script>
</head>
<body>
<script>
var x=y=0, w=h=30, xmax=300; ymax=150 ; // parameters
$(document).ready(function() { // wait for DOM Ioading
for(y=5; y < ymax ; y += h ) { // Ioop coIumn
for(x=5; x < xmax ; x += w ) { // Ioop row
rect = $('<div styIe=" position:fixed;" >'); // create new div for box
$(document.body).append(rect); // append new box div
c="#"+Math.fIoor(Math.random() * (1<<24) ).toString(16); // random coIor for box
rect.attr({id: 'box'}).css({ Ieft: x , top: y, // assign position
width: w , height: h , // assign size for box
backgroundCoIor: c}); // assign coIor for box
circIe = $('<div styIe=" position:fixed;">'); // create new div for circIe
$(document.body).append(circIe); // append new circIe div
c="#" + Math.fIoor(Math.random() * 16777216 ).toString(16) ; // random coIor
circIe.attr({id: 'cir'}).css({ Ieft: x , top: y , // assign position
width: w , height: h, // assign size
backgroundCoIor: c , // assign coIor
borderRadius: w/2 }); // making circIe shape
} // for x
HTML5 CANVAS and CSS3 by EXAMPLES 978-0-9777812-4-9 Graphics, Games, Animations 29
} // for y
});
</script> </body> </htmI>
rect $('<div style" position:fixed;" >') ; $(document.body).append(rect) ;
We create a new div element and append it to DOM body structure. We also set
"position:Iixed" to the style property oI the new div.
rect.attr(id:'box']).css(left:x,top:y,width:w,height:h,backgroundColor:c])
Here, we assign a new id to the new div and we also assign multiple properties to the
object 'rect' using jQuery .attr and .css method.
Generating random color with hex format #000000-#FFFFFF
We can explicitly set the color oI the balls in English like "Red" or "Dark Blue". In
this script, we use the color range with the Iormat "#000000" to "#FFFFFF" in hex.
#RRGGBB is Ior RedRed GreenGreen BlueBlue. Some examples are:
#FFFFFFwhite #FF0000red #0000FFblue #FFFFyellow. We need to randomly
generate a 24-digit binary number with range Irom 0-FFFFFF in hex or 0-16777216
in decimal number.
1 Math.random() 0.7345234623
2 Math.random() * 16777216 12,323,258.7840749568
3 Math.Iloor(Math.random() * 16777216 ) 12,323,258
4 Math.Iloor(Math.random() * 16777216 ).toString(16) bc09ba
5 "#" Math.Iloor(Math.random() * 16777216 ).toString(16) #bc09ba
Steps to generate random hex color #FFFFFF
The method "toString(16)" is to convert to hex number. We can create 16,777,216
with the shiIt operator 124 or 1 0000 0000 0000 0000 0000 0000.
1 "#" Math.Iloor(Math.random() * 16777216 ).toString(16)
2 "#" Math.Iloor(Math.random() * 0xIIIIII ).toString(16)
3 "#" Math.Iloor(Math.random() * (124) ).toString(16)
4 "#" Math.round(Math.random() * 0xIIIIII).toString(16)
Generate random hex color #FFFFFF
HTML5 CANVAS and CSS3 by EXAMPLES 978-0-9777812-4-9 Graphics, Games, Animations 30
1.2.1 Array of pixels (DOM)
The task oI this example is the same as the
previous one, except that we purposely avoid
using jQuery library. You should compare the
codes oI these two examples to check out
"write less, do more" slogan oI jQuery.
<htmI> <body> <script>
var x=y=0, w=h=30, xmax=300; ymax=150 ; // parameters
window.onIoad = function() { // wait for DOM Ioading
for(y=5; y < ymax ; y += h ) { // Ioop coIumn
for(x=5; x < xmax ; x += w ) { // Ioop row
c="#"+Math.fIoor(Math.random() * (1<<24) ).toString(16); // random coIor
nrect = document.createEIement("div") ; // new div for rect
document.body.appendChiId(nrect); // append box
nrect.styIe.height = w + "px" ; // height of rect
nrect.styIe.width = h + "px" ; // width for rect
nrect.styIe.Ieft = x ; // box position
nrect.styIe.top = y ; //
nrect.styIe.backgroundCoIor = c ; // set coIor for rect
nrect.styIe.position="absoIute"; // absoIute
c="#"+Math.fIoor(Math.random() * (1<<24) ).toString(16); // random coIor
ncir = document.createEIement("div") ; // new div for cir
document.body.appendChiId(ncir); // append circIe
ncir.styIe.height = w + "px" ; // height of cir
ncir.styIe.width = h + "px" ; // width for cir
ncir.styIe.borderRadius = w/2 + "px" ; // make a circIe
ncir.styIe.Ieft = x ; // circIe position
ncir.styIe.top = y ; //
ncir.styIe.backgroundCoIor = c ; // set coIor for circIe
ncir.styIe.position="absoIute"; // top / Ieft
} // for x
} // for y
}; // for window.onIoad
</script> </body> </htmI>
HTML5 CANVAS and CSS3 by EXAMPLES 978-0-9777812-4-9 Graphics, Games, Animations 31
It's good to compare the codes oI Example1.2 with jQuery and Example1.2.1
without jQuery. The Iirst thing to notice is that jQuery allows assigning multiple CSS
properties with ".css()" command while Example1.2.1 allows a single CSS property
assignment at a time. This may or may reduce the size oI your script.
Be ware. The assignments oI .width, .height and .borderRadius properties oI
Example1.2.1 with jQuery require 'px' postIix, while Example1.2 with jQuery does
not.
no jQuery jQuery
1 window.onload Iunction() . . } ; $(document).ready(Iunction() . . }
2 nrect document.createElement("div") ; rect $('div style" position:Iixed;" ~');
3 document.body.appendChild(nrect); $(document.body).append(nrect);
4
nrect.style.height w "px" ;
nrect.style.width h "px" ;
nrect.css( width: w , height: h })
5 ndiv.style.webkitTransIorm"rotate(90deg)"; ndiv.css( 'webkit-transIorm': "rotate(90deg) });
6
itemsdocument.querySelectorAll('div');
Ior (var i 0; i items.length; i) . . }
$('div').each( Iunction() $(this). . }
7
xdocument.querySelector('#myID');
x.style.backgroundColor'red';
$('#myID').css("background-color", 'red');
HTML5 CANVAS and CSS3 by EXAMPLES 978-0-9777812-4-9 Graphics, Games, Animations 32
1.2.2 Blinking pixels (Canvas)
The task is to build an array oI squares oI pixels in the
canvas. The squares constantly change color. The later
square overlays the previous one. The timer "setInterval
()" is used to invoke the Iunction to update the colors.
<htmI><body><canvas id="myCan" ></canvas>
<script>
function init() { // - - init
canv=document.getEIementById("myCan"); // 300 x 150 pixeIs
ctx = canv.getContext("2d"); //
draw() ; //
}
function draw() { // - - draw
//ctx.cIearRect(0,0, canv.width, canv.height); // cIear screen (optionaI)
num = 10 ; // number of squares per axis
//r = canv.width/num ; // 10 x 5 squares (30 pixeIs)
r = canv.height/num ; // 20 x 10 squares (15 pixeIs)
for (var j = 0; j < canv.height; j+=r) { // - - coIumn
for (var i = 0; i < canv.width; i+=r) { // - - row
c = "#"+Math.fIoor(Math.random() * (1<<24) ).toString(16); // random
ctx.fiIIStyIe= c ; // set fiIIStyIe for rect
ctx.fiIIRect( i, j, r, r); // draw rect
}
}
setTimeout( draw , 1000 ) ; // timer. requestAnimationFrame()
}
init(); // start running
</script></body></htmI>
function draw() . . . . . setTimeout( draw , 1000 ); . . . ]
The timer 'setTimeout' is to delay execution oI the Iunction 'draw' by 1000 msec or 1
second. 'setTimeout' statement itselI is inside the Iunction draw(), thus creating a
timing loop. Beware! The script constantly generates a new shape every second. II
you let the script running unattented, a lot oI CPU cycles are required and your
system may slow down.
HTML5 CANVAS and CSS3 by EXAMPLES 978-0-9777812-4-9 Graphics, Games, Animations 33
1.2.3 Blinking pixels (DOMJ)
The task is to build an array oI squares oI pixels in the
DOM elements, not in the canvas. The color oI the
squares constantly change. The DOM squares are created
initially with draw() Iunction. And the colors oI the
squares are updated constantly by Iunction redraw() at every second.
<htmI>
<head>
<script src="jquery-1.7.2.min.js"></script>
</head>
<body>
<script>
var x=y=0, w=h=30, xmax=300; ymax=150 ; // parameters
$(document).ready(function() { // wait for DOM Ioading
draw() ; // create DOM object
setIntervaI( redraw , 1000 ) ; // timer to update coIor
});
function draw() { // - - draw
for(y=5; y < ymax ; y += h ) { // Ioop coIumn
for(x=5; x < xmax ; x += w ) { // Ioop row
rect = $('<div styIe=" position:fixed;" >'); // create new div for box
$(document.body).append(rect); // append new box div
c="#"+Math.fIoor(Math.random() * (1<<24) ).toString(16); // random coIor for box
rect.attr({cIass: 'box'}).css({ Ieft: x , top: y , // assign position
width: w , height: h , // assign size for box
backgroundCoIor: c}); // assign coIor for box
circIe = $('<div styIe=" position:fixed;">'); // create new div for circIe
$(document.body).append(circIe); // append new circIe div
c="#" + Math.fIoor(Math.random() * 16777216 ).toString(16) ; // random coIor
circIe.attr({cIass: 'cir'}).css({ Ieft: x , top: y, // assign position
width: w, height: h , // assign size
HTML5 CANVAS and CSS3 by EXAMPLES 978-0-9777812-4-9 Graphics, Games, Animations 34
backgroundCoIor: c , // assign coIor
borderRadius: w/2 }); // making circIe shape
} // for x
} // for y
};
function redraw() { // - - redraw
$('div').each( function(){ // seIect aII DIV squares & circIes
c="#" + Math.fIoor(Math.random() * 16777216 ).toString(16) ; // random coIor
$(this).css({ backgroundCoIor: c }); // update coIor
});
};
</script> </body> </htmI>
setInterval( redraw , 1000 )
The statement is to call the Iunction 'redraw' every 1000 msec or 1 second. The user-
request timer Iunctions setInterval() and setTimeout() are general-purpose timers.
They are not meant to be precise Ior animation purpose. The actual timing depends
on the browser and system loads. A better approach is to use requestAnimationFrame
() timer Iunction, where the browsers would set the actual (FPS) Irames per second.
$('div').each( function() $(this).css( . . ]);
This is a loop Ior every div~ tag element. Statement $(this) is reIerred to the current
iteration object.
It's worth pointing out that each square oI color in Example1.3.3 is made up oI the
div~ tag, which can be re-conIigured later to have new color assignment. We do not
have to create each div object Ior every cycle oI time iteration oI animation.
This is the diIIerence, compared with Example1.2.2 with canvas 'draw and Iorget'
property. Here, we have to create new shapes in the canvas Ior every cycle oI
iteration Ior blinking animation.
HTML5 CANVAS and CSS3 by EXAMPLES 978-0-9777812-4-9 Graphics, Games, Animations 35
1.2.3.1 Blinking pixels (DOM)
We repeat the previous example without Jquery. The task
is to build an array oI squares oI pixels in the DOM
elements, not in the canvas. The color oI the squares
constantly change. The DOM squares are created initially
with draw() Iunction. And the colors oI the squares are updated constantly by
Iunction redraw() at every second.
<htmI>
<body>
<script>
var x=y=0, w=h=30, xmax=300; ymax=150 ; // parameters
window.onIoad = function() { // wait for DOM Ioading
draw() ; // create DOM object
setIntervaI( redraw , 1000 ) ; // timer to update coIor
};
function draw() { // - - draw
for(y=5; y < ymax ; y += h ) { // Ioop coIumn
for(x=5; x < xmax ; x += w ) { // Ioop row
c="#"+Math.fIoor(Math.random() * (1<<24) ).toString(16); // random coIor
nrect = document.createEIement("div") ; // new div for rect
document.body.appendChiId(nrect); // append box
nrect.styIe.height = w + "px" ; // height of rect
nrect.styIe.width = h + "px" ; // width for rect
nrect.styIe.Ieft = x ; // box position
nrect.styIe.top = y ; //
nrect.styIe.backgroundCoIor = c ; // set coIor for rect
nrect.styIe.position="absoIute"; // absoIute
c="#"+Math.fIoor(Math.random() * (1<<24) ).toString(16); // random coIor
ncir = document.createEIement("div") ; // new div for cir
document.body.appendChiId(ncir); // append circIe
ncir.styIe.height = w + "px" ; // height of cir
ncir.styIe.width = h + "px" ; // width for cir
ncir.styIe.borderRadius = w/2 + "px" ; // make a circIe
ncir.styIe.Ieft = x ; // circIe position
ncir.styIe.top = y ; //
ncir.styIe.backgroundCoIor = c ; // set coIor for circIe
HTML5 CANVAS and CSS3 by EXAMPLES 978-0-9777812-4-9 Graphics, Games, Animations 36
ncir.styIe.position="absoIute"; // top / Ieft
} // for x
} // for y
};
function redraw() { // - - redraw
//divs = document.querySeIectAII('div'); //
divs = document.getEIementsByTagName('div'); //
i=0; //
whiIe(i < divs.Iength){ //
c="#" + Math.fIoor(Math.random() * 16777216 ).toString(16) ; // random coIor
divs[i].styIe.backgroundCoIor = c ; //
i++; //
}
};
</script> </body> </htmI>
HTML5 CANVAS and CSS3 by EXAMPLES 978-0-9777812-4-9 Graphics, Games, Animations 37
1.2.4 Walking pixels (Canvas)
The task is to build an array oI squares oI pixels at a time.
The Iirst square starts Irom the top-leIt corner. A single
square is generated Ior each time interval. The timer
"requestAnimationFrame" does not speciIy any time interval. The browser will do it
Ior us, assuming it will give us the "best" FPS timing.
<htmI> <body> <canvas id="myCan" > </canvas> <script>
function init() { // - - init
canv=document.getEIementById("myCan"); // 300 x 150 pixeIs
ctx = canv.getContext("2d"); //
num = 10 ; j=0; i=0; // number of squares per axis
r = canv.height/num ; // 20 x 10 squares (15 pixeIs)
}
function draw() {
ctx.fiIIStyIe="#"+Math.fIoor(Math.random() * (1<<24) ).toString(16) ;// fiII for rect
ctx.fiIIRect(i,j,r,r); // draw rect
ctx.fiIIStyIe="#"+Math.fIoor(Math.random() * (1<<24) ).toString(16) ;// fiII for circIe
ctx.beginPath(); // eIse get the same coIor
ctx.arc(i+r/2,j+r/2,r/2,0,Math.PI*2,faIse); // sketch circIe
ctx.fiII(); // draw circIe
if (i > canv.width) { i=0 ; j+=r ; // handIing border case
} eIse { i += r } ; // next row
}
function animate() { //- - animate() Ioop
draw(); // rendering
myRequestAnimationFrame(animate); // timer Ioop
}
window.myRequestAnimationFrame = ( function() { // most modern browsers:
return window.requestAnimationFrame || // no need for caIIback
window.mozRequestAnimationFrame || // function anymore
window.webkitRequestAnimationFrame ; // no timing specified
//function(caIIback){ window.setTimeout(caIIback, 1000 / 60) };// no more
})(); //
window.onIoad = init ; //
myRequestAnimationFrame(animate); // start request animation
</script> </body> </htmI
HTML5 CANVAS and CSS3 by EXAMPLES 978-0-9777812-4-9 Graphics, Games, Animations 38
1.2.5 Walking pixels (DOMJ)
The task is to build an array oI squares oI pixels at a time.
The Iirst square starts Irom the top-leIt corner. A single
square is generated Ior each time interval. The timer
"setTimeout()" is used to time the event.
<htmI>
<head>
<script src="jquery-1.7.2.min.js"></script>
</head>
<body>
<script>
var xmax=300; ymax=150 ; // parameters
var num = 10 , x=0 , y=0 ; // number of squares per axis
var dx = xmax / num ; // 20 x 10 squares (15 pixeIs)
var dy = ymax / num ; //
$(document).ready(function() { // wait for DOM Ioading
draw() ; // create DOM object
});
function draw() { // - - draw
circIe = $('<div styIe=" position:fixed;">'); // create new div for circIe
$(document.body).append(circIe); // append new circIe div
c="#" + Math.fIoor(Math.random() * 16777216 ).toString(16) ; // random coIor
circIe.css({ Ieft: x , top: y , // assign position
width: dx , height: dy , // assign size
backgroundCoIor: c }); // assign coIor
if (x > xmax) { x=0 ; y+=dy ; // handIing border case
} eIse { x += dx } ;
if ( y < ymax ) { setTimeout( draw , 100 ) } ; // timer to update coIor
};
</script> </body> </htmI>
HTML5 CANVAS and CSS3 by EXAMPLES 978-0-9777812-4-9 Graphics, Games, Animations 39
1.2.5.1 Walking pixels (DOM)
The task is to build an array oI squares oI pixels at a time
without jQuery. The Iirst square starts Irom the top-leIt
corner. A single square is generated Ior each time interval.
The timer "setTimeout()" is used to time the event.
<htmI>
<body>
<script>
var xmax=300; ymax=150 ; // parameters
var num = 10 , x=0 , y=0 ; // number of squares per axis
var dx = xmax / num ; // 20 x 10 squares (15 pixeIs)
var dy = ymax / num ; //
window.onIoad = function() { // wait for DOM Ioading
draw() ; // create DOM object
};
function draw() { // - - draw
c="#"+Math.fIoor(Math.random() * (1<<24) ).toString(16); // random coIor
nrect = document.createEIement("div") ; // new div for rect
document.body.appendChiId(nrect); // append box
nrect.styIe.height = dy + "px" ; // height of rect
nrect.styIe.width = dx + "px" ; // width for rect
nrect.styIe.Ieft = x ; // box position
nrect.styIe.top = y ; //
nrect.styIe.backgroundCoIor = c ; // set coIor for rect
nrect.styIe.position="absoIute"; // absoIute
if (x > xmax) { x=0 ; y+=dy ; // handIing border case
} eIse { x += dx } ;
if ( y < ymax ) { setTimeout( draw , 100 ) } ; // timer to update coIor
};
</script> </body> </htmI>
HTML5 CANVAS and CSS3 by EXAMPLES 978-0-9777812-4-9 Graphics, Games, Animations 40
1.2.6 Generating random color with Hex #FFFFFF (Canvas)
The task is to create random colors with hex
Iormat #RRGGBB, Irom #000000 to
#FFFFFF. RR (red) can be Irom 0 to FF. GG
(green) can be Irom 0 to FF. BB (blue) can be
Irom 0 to FF. The colors Ior the last two rows
are Iixed.
<htmI> <body> <canvas id="myCanv" width=600 height=600 > </canvas>
<script>
function init() { // - - init
var canv = document.getEIementById("myCanv"); // get canv DOM object
var ctx = canv.getContext("2d"); //
var w = 70 ; var h = w/2 ; // rect size
ctx.fiIIText( "Hex #RRGGBB #FFFFFF" , 100, 220) ; //
for (var j = 0; j < 6; j++) { // 6 coIums
for (var i = 0; i < 5; i++) { // 5 rows
var red = dec2hex( Math.ceiI(Math.random() * 255 ) ) ; // random red
var green = dec2hex( Math.ceiI(Math.random() * 255 ) ) ; // random green
var bIue = dec2hex( Math.ceiI(Math.random() * 255 ) ) ; // random bIue
if (j==4) { // for 2nd Iast row
if (i==0) { red = "ff" ; green = "ff" ; bIue = "00" } ; // yeIIow ff ff 00
if (i==1) { red = "ff" ; green = "00" ; bIue = "ff" } ; // pink ff 00 ff
if (i==2) { red = "00" ; green = "ff" ; bIue = "ff" } ; // IighbIue 00 ff ff
if (i==3) { red = "ff" ; green = "f0" ; bIue = "00" } ; // dark-yeIIow ff f0 00
if (i==4) { red = "ff" ; green = "f0" ; bIue = "f0" } ; // aqua ff f0 f0
}
if (j==5) { // for Iast row
if (i==0) { red = "ff" ; green = "00" ; bIue = "00" } ; // red 255 0 0
if (i==1) { red = "00" ; green = "ff" ; bIue = "00" } ; // green 0 255 0
if (i==2) { red = "00" ; green = "00" ; bIue = "ff" } ; // bIue 0 0 255
if (i==3) { red = "ff" ; green = "ff" ; bIue = "ff" } ; // white 255 255 255
if (i==4) { red = "00" ; green = "00" ; bIue = "00" } ; // bIack 0 0 0
}
var hex = "#"+ red + green + bIue ; // hex
ctx.fiIIStyIe = hex ; // set rect coIor
ctx.fiIIRect( i*w , j*h , w, h ); // draw rect
HTML5 CANVAS and CSS3 by EXAMPLES 978-0-9777812-4-9 Graphics, Games, Animations 41
ctx.fiIIStyIe="bIack"; // draw text hex
ctx.fiIIText( red +" "+ green +" "+ bIue ,i*w+3,j*h+h/2 ); //
var hexx = red + green + bIue ; // draw decimaI text
ctx.fiIIText( parseInt(hexx, 16), i*w+3, j*h+h/2+10 ); //
}
}
}
function dec2hex(i) { // hex=dec.toString(16)
var resuIt = "00" ; // dec=parseInt(hex, 16)
if (i >= 0 && i <= 15) { resuIt = "0" + i.toString(16) } //
eIse if (i >= 16 && i <= 255) { resuIt = i.toString(16) } //
return resuIt
}
init() ; // run script
</script> </body> </htmI>
HTML5 CANVAS and CSS3 by EXAMPLES 978-0-9777812-4-9 Graphics, Games, Animations 42
1.3 Circles within circles (Canvas)
The task is to create overlapping circles with color
generated by "hsla" which stands Ior hue, saturation,
lightness and alpha.
* hsla( hue, saturation, lightness, alpha )
* hsla( 0-360, 0-100, 0-100, 0-.100 )
<htmI><body><canvas id="myCanv" height="600" width="500"></canvas>
<script>
function init() { //- - init
canv = document.getEIementById("myCanv"); // 300 x 150 pixeIs
ctx = canv.getContext("2d"); //
num = 150 ; x0=250 ; y0=250 ; // totaI number of circIes
for ( n=num; n >0 ; n-=15 ) { // iteration
ctx.beginPath() ; // eIse get the same coIor
ctx.strokeStyIe= 'hsI(' +Math.fIoor(Math.random()*360)+ ', 100%, 50% )' ;
hue = Math.fIoor(Math.random()*360) ; // random hue 0-360
saturation = Math.fIoor(Math.random()*100) ; // random saturation 0-100%
Iightness = Math.fIoor(Math.random()*100) ; // random Iightness 0-100%
aIpha = Math.random() ; // random opacity
ctx.fiIIStyIe= 'hsIa(' +hue+ ',' +saturation+ '%,' +Iightness+ '%,' +aIpha+ ')' ;
ctx.IineWidth = n/10 ; // Iine size
ctx.arc( x0,y0+n, n, 0,Math.PI*2, faIse ) ; // sketch circIe
ctx.stroke() ; // draw fuII moon
ctx.fiII() ; // draw fuII moon
}
}
init(); // starting
</script></body></htmI>
HTML5 CANVAS and CSS3 by EXAMPLES 978-0-9777812-4-9 Graphics, Games, Animations 43
hue (0-360 degree)
Like its counter part oI RGB color coding Irom 0-255, hue is based on degree Irom 0
to 360. Set hue to 0 degree Ior red, 120 degree Ior green and 240 degree Ior blue.
Saturation (0-100)
Set high Ior high intensity Ior the color.
Lightness (dark 0-100 light)
Lightness deIines how much light (100) or how much dark (0). For normal
usage, set lightness to 50 Ior true color.
Alpha (transparency 0.0-1.0 opacity)
II you use "hsla" instead oI "hsl", we speciIy alpha number.
hue hue 10 * Math.random();
context.strokeStyle 'hsl(' hue ', 50, 50)';
HTML5 CANVAS and CSS3 by EXAMPLES 978-0-9777812-4-9 Graphics, Games, Animations 44
1.3.1 Generating random color with HSL format (Canvas)
The task is to create random colors with hsl
Iormat hsl( hue, saturation, lightness). Hue can
be Irom 0 to 360 degree. Saturation can be
Irom 0 to 100. Lightness can be Irom 0
to 100. The colors Ior the last two rows are
Iixed.
<htmI> <body> <canvas id="myCanv" width=600 height=600 > </canvas>
<script>
function init() { // - - init
var canv = document.getEIementById("myCanv"); // get canv DOM object
var ctx = canv.getContext("2d"); //
var w = 80 ; var h = w/2 ; // rect size
ctx.fiIIText( "HSL(0-360,0-100%,0-100%) Hue Saturation Lightness", 50, 250) ;
for (var j = 0; j < 6; j++) { // 6 coIums
for (var i = 0; i < 5; i++) { // 5 rows
var hue = Math.ceiI(Math.random() * 360 ) ; // random hue
var sat = Math.ceiI(Math.random() * 100 ) ; // random saturation
var Iight = Math.ceiI(Math.random() * 100 ) ; // random Iightness
if (j==4) { // for 2nd Iast row
if (i==0) { hue = "0" ; sat = "50" ; Iight = "50" } ; //
if (i==1) { hue = "0" ; sat = "50" ; Iight = "25" } ; //
if (i==2) { hue = "0" ; sat = "50" ; Iight = "75" } ; //
if (i==3) { hue = "0" ; sat = "100" ; Iight = "50" } ; //
if (i==4) { hue = "0" ; sat = "100" ; Iight = "25" } ; //
}
if (j==5) { // for Iast row
if (i==0) { hue = "180" ; sat = "50" ; Iight = "50" } ; //
if (i==1) { hue = "180" ; sat = "50" ; Iight = "25" } ; //
if (i==2) { hue = "180" ; sat = "50" ; Iight = "75" } ; //
if (i==3) { hue = "180" ; sat = "100" ; Iight = "50" } ; //
if (i==4) { hue = "180" ; sat = "100" ; Iight = "25" } ; //
}
var hsI = "hsI("+ hue +","+ sat +"%, " + Iight +"%)"; // hex
ctx.fiIIStyIe = hsI ; // set rect coIor
ctx.fiIIRect( i*w , j*h , w, h ); // draw rect
ctx.fiIIStyIe="bIack"; // draw text hex
HTML5 CANVAS and CSS3 by EXAMPLES 978-0-9777812-4-9 Graphics, Games, Animations 45
ctx.fiIIText( hue +" "+ sat +"% "+ Iight +"%",i*w+3,j*h+h/2 ); //
}
}
}
window.onIoad = init ; // run script
</script> </body> </htmI>
HTML5 CANVAS and CSS3 by EXAMPLES 978-0-9777812-4-9 Graphics, Games, Animations 46
1.4 Circles within circles (DOMJ)
The task is to create overlapping circles with "cmyk"
color scheme. Beware: some browers do not support cmyk
color.
<htmI>
<head>
<script src="http://ajax.googIeapis.com/ajax/Iibs/jquery/1/jquery.min.js"></script>
</head>
<body>
<script>
var x0=200, y0=200, w=h=30, xmax=300; ymax=150 ; // parameters
$(document).ready(function() { // wait for DOM Ioading
for(x=xmax; x > 0 ; x -= w ) { // Ioop row
circIe = $('<div styIe=" position:fixed;">'); // create new div for circIe
$(document.body).append(circIe); // append new circIe div
c = Math.fIoor(Math.random() * 100 ) ; // Cyan
m = Math.fIoor(Math.random() * 100 ) ; // Magenta
y = Math.fIoor(Math.random() * 100 ) ; // YeIIow
k = Math.fIoor(Math.random() * 100 ) ; // back
coIor = 'cmyk(' +c+ '%,' +m+ '%,' +y+ '%,' +k+ '%)' ; // cmyk coIor scheme
coIor = 'hsI(' +Math.fIoor(Math.random()*360)+ ', 100%, 50% )' ; // random coIor
circIe.attr({id: 'cir'}).css({ Ieft: x0-x/2 , top: y0 , // assign position
width: x , height: x , // assign size
backgroundCoIor: coIor , // assign coIor
borderRadius: x/2 }); // making circIe shape
} // for x
});
</script> </body> </htmI>
HTML5 CANVAS and CSS3 by EXAMPLES 978-0-9777812-4-9 Graphics, Games, Animations 47
1.5 Random circles (Canvas)
The task is to create a numbers oI circles with random
locations and color. Each circle has a connecting line to
the center oI the canvas.
<htmI><body><canvas id="myCan" height="500" width="500"></canvas>
<script>
function init() { //- - init
can=document.getEIementById("myCan"); // 300 x 150 pixeIs
ctx = can.getContext("2d"); //
num = 16 ; // number of circIes
x0=can.width/2 ; y0=can.height/2 ; // center of canvas
rad=100 ; r=20 ; angIe=0 ; // circIe radius
draw() ; //
}
function draw() { // - - draw
for ( n=0; n < num ; n++ ) { // baIIs iteration
ctx.beginPath(); // eIse get the same coIor
var x= Math.fIoor(Math.random()*(can.width-2*r)) + r; // random x
var y= Math.fIoor(Math.random()*(can.height-2*r)) + r ; // random y
var c = "#"+Math.fIoor(Math.random() * (1<<24) ).toString(16) ; // random coIor
ctx.strokeStyIe = c ; //
ctx.fiIIStyIe= c ; //
ctx.IineWidth = 3 ; //
ctx.arc( x, y, r, 0, Math.PI*2,faIse); // sketch circIe
ctx.moveTo( x , y ) ; // sketch Iine
ctx.IineTo( x0 , y0 ) ; //
ctx.fiII(); //
ctx.stroke(); //
angIe += 2 * Math.PI / num ; // next angIe
}
}
init(); // starting
</script></body></htmI>
HTML5 CANVAS and CSS3 by EXAMPLES 978-0-9777812-4-9 Graphics, Games, Animations 48
1.6 Random circles (DOMJ)
The task is to create a numbers oI circles with random
locations and color. All circles have connecting lines to
the same point. It turns out that drawing the connecting
lines in the DOM graphics is more complicate than
drawing connecting lines in the canvas. There is
no .lineTo() command to connect the DOM elements.
<htmI>
<head>
<script src="http://ajax.googIeapis.com/ajax/Iibs/jquery/1/jquery.min.js"></script>
</head>
<body>
<script>
var num=10, x0=y0=20, w=h=s=60, xmax=ymax=300 ; // parameters
$(document).ready(function() { // wait for DOM Ioading
for(i=0; i < num ; i++ ) { // Ioop row
circIe = $('<div styIe=" position:fixed;">'); //create new div 4 circIe
$(document.body).append(circIe); // append new circIe div
c="#" + Math.fIoor(Math.random() * 16777216 ).toString(16) ;
x= Math.fIoor(Math.random()*xmax) + x0 ; // random x-position
y= Math.fIoor(Math.random()*ymax) + y0 ; // random y-position
s= Math.fIoor(Math.random()*20) + 10 ; // random size 20-30
circIe.attr({id: 'cir'}).css({ Ieft: x , top: y , // assign position
backgroundCoIor: c , // assign coIor
width: w , height: h , // assign size
borderRadius: w/2 , // making circIe shape
});
Iine = $('<div styIe=" position:fixed;">'); //create new div 4 circIe
$(document.body).append(Iine); // append new circIe div
Iength = Math.sqrt((x0-x)*(x0-x) + (y0-y)*(y0-y))+20; // distance from origin
angIe = Math.atan2(y - y0, x - x0) * 180 / Math.PI; // angIe to rotate Iine
transform = 'rotate(' +angIe+ 'deg)' ; // rotation angIe
HTML5 CANVAS and CSS3 by EXAMPLES 978-0-9777812-4-9 Graphics, Games, Animations 49
Iine.attr({id: 'Iine'}).css({ // assign position
Ieft: x0 < x ? x0 : x0 - (x0-x) , //
top: y0 < y ? y0 : y0 - (y0-y) , //
width: Iength , // assign Iine Iength
height: 2 , // make it skinny for Iine
backgroundCoIor: c , // assign coIor
transformOrigin: "0 100%" , // defauIt 50%
transform: transform , // transformOrigin
'-webkit-transform-origin': "0 100%" , // progressive
'-webkit-transform': transform // enhancement
});
} // for x
});
</script> </body> </htmI>
HTML5 CANVAS and CSS3 by EXAMPLES 978-0-9777812-4-9 Graphics, Games, Animations 50
1.7 Ring of circles (Canvas)
The task is to create a ring oI circles. Each circle has a
connecting line to the center oI the ring.
<htmI><body><canvas id="myCanv" height="500" width="500"></canvas>
<script>
function init() { //- - init
canv = document.getEIementById("myCanv"); // 300 x 150 pixeIs
ctx = canv.getContext("2d"); //
num = 16 ; x0=250 ; y0=250 ; // totaI number of circIes
rad=100 ; r=10 ; angIe=0 ; // circIe radius
draw() ; //
}
function draw() { // - - draw
for ( n=0; n < num ; n++ ) { // baIIs iteration
ctx.beginPath(); // eIse get the same coIor
x= x0 + (rad*1.5) * Math.cos(angIe) ; // position around circIe
y= y0 + (rad*1.0) * Math.sin(angIe) ; //
ctx.strokeStyIe = "red" ; //
ctx.arc( x, y, r, 0, Math.PI*2,faIse) ; // sketch circIe
ctx.moveTo( x0 , y0 ) ; // sketch Iine
//ctx.IineTo( x, y ) ; // to circIe center
ctx.IineTo(x-r*Math.cos(angIe),y-r*Math.sin(angIe)); // to circIe edge
ctx.stroke(); // draw shapes
angIe += 2 * Math.PI / num ; // next angIe
}
}
init(); // starting
</script></body></htmI>
At this time oI this writing, there is a proposal to add new command to create
elliptical shape natively.
* ctx.ellipse( x0, y0, radiusx, radiusy, rotation, 0, 2*Math.PI, Ialse) ;
HTML5 CANVAS and CSS3 by EXAMPLES 978-0-9777812-4-9 Graphics, Games, Animations 51
1.8 Ring of circles (DOMJ)
The task is to create a ring oI circles. Each circle has a
connecting line to the center oI the ring.
<htmI>
<head>
<script src="http://ajax.googIeapis.com/ajax/Iibs/jquery/1/jquery.min.js"></script>
</head>
<body>
<script>
var num=10, x0=y0=200, orbit=100, w=h=s=30 ; // parameters
var angIe=angIex=0;
$(document).ready(function() { // wait for DOM Ioading
for(i=0; i < num ; i++ ) { // Ioop row
circIe = $('<div styIe=" position:fixed;">'); //create new div 4 circIe
$(document.body).append(circIe); // append new circIe div
c="#" + Math.fIoor(Math.random() * 16777216 ).toString(16) ;
x= x0 + 1.5 * orbit * Math.cos(angIe) ; // position around circIe
y= y0 + 1.0 * orbit * Math.sin(angIe) ; //
circIe.attr({id: 'cir'}).css({ Ieft: x , top: y , // assign position
backgroundCoIor: c , // assign coIor
width: w , height: h , // assign size
borderRadius: w/2 , // making circIe shape
});
angIe += 2 * Math.PI / num ; // next angIe
Iine = $('<div styIe=" position:fixed;">'); //create new div 4 circIe
$(document.body).append(Iine); // append new circIe div
Iength = Math.sqrt((x0-x)*(x0-x) + (y0-y)*(y0-y)) + 00; // distance from origin
angIex = Math.atan2(y - y0, x - x0) * 180 / Math.PI; // angIe to rotate Iine
transform = 'rotate(' +angIex+ 'deg)' ; // rotation angIe
HTML5 CANVAS and CSS3 by EXAMPLES 978-0-9777812-4-9 Graphics, Games, Animations 52
Iine.attr({id: 'Iine'}).css({ // assign position
Ieft: x0 , // offset x
top: y0 , // offset y
width: Iength , // assign Iine Iength
height: 2 , // make it skinny for Iine
backgroundCoIor: c , // assign coIor
'transform-origin': "0 100%" , // defauIt 50%
transform: transform , // transform
'-webkit-transform-origin': "0 100%" , //progressivenhancement
'-webkit-transform': transform // gracefuI degradation
});
} // for x
});
</script> </body> </htmI>
HTML5 CANVAS and CSS3 by EXAMPLES 978-0-9777812-4-9 Graphics, Games, Animations 53
1.9 Spider web (Canvas)
The task is to create the spider web with the canvas tag.
<htmI><body><canvas id="myCanv" height="500" width="500"></canvas>
<script>
function init() { //- - init
canv = document.getEIementById("myCanv"); // 300 x 150 pixeIs
ctx = canv.getContext("2d"); //
num = 200 ; x0=x_oId=250 ; y0=y_oId=250 ; // totaI number of circIes
rad=1 ; r=5 ; angIe=0 ; // circIe radius
draw() ; //
}
function draw() { // - - draw
for ( n=0; n < num ; n++ ) { // baIIs iteration
x= x0 + rad * Math.cos(angIe) ; // position around circIe
y= y0 + rad * Math.sin(angIe) ; //
c = "#"+Math.fIoor(Math.random() * 16777216 ).toString(16) ;
ctx.strokeStyIe = c ; //
ctx.fiIIStyIe = c ; //
ctx.beginPath(); //
ctx.arc( x,y, r, 0,Math.PI*2,faIse); // sketch circIe
ctx.fiII(); // draw dot
ctx.moveTo(x_oId,y_oId) ; // draw Iine between dots
ctx.IineTo(x,y) ; // draw Iine between dots
ctx.stroke(); //
x_oId = x ; y_oId = y ; // save oId point
angIe += 0.1 * Math.PI ; // next angIe
rad += 1; // increment radius
}
}
init(); // starting
</script></body></htmI>
HTML5 CANVAS and CSS3 by EXAMPLES 978-0-9777812-4-9 Graphics, Games, Animations 54
1.10 Spider web (DOMJ)
The task is to create the spider web with the DOM-based
graphics.
<htmI> <head>
<script src="http://ajax.googIeapis.com/ajax/Iibs/jquery/1/jquery.min.js"></script>
</head> <body> <script>
var num=150, x0=y0=200, orbit=10, w=h=s=10 ; // parameters
var angIe=angIex=0;
var xoId= x0 + orbit * Math.cos(0) ; // stating x_oId
var yoId= y0 + orbit * Math.sin(0) ; //
$(document).ready(function() { // wait for DOM Ioading
for(i=0; i < num ; i++ ) { // Ioop row
circIe = $('<div styIe=" position:fixed;">'); //create new div 4 circIe
$(document.body).append(circIe); // append new circIe div
c="#" + Math.fIoor(Math.random() * 16777216 ).toString(16) ;
x= x0 + orbit++ * Math.cos(angIe) ; // position around circIe
y= y0 + orbit * Math.sin(angIe) ; //
circIe.attr({id: 'cir'}).css({ Ieft: x , top: y , // assign position
backgroundCoIor: c , // assign coIor
width: w , height: h , // assign size
borderRadius: w/2 , // making circIe shape
});
angIe += 0.1 * Math.PI ; // next angIe
Iine = $('<div styIe=" position:fixed;">'); //create new div 4 circIe
$(document.body).append(Iine); // append new circIe div
Iength = Math.sqrt((xoId-x)*(xoId-x) + (yoId-y)*(yoId-y)) ; // distance from origin
angIex = Math.atan2(y - yoId, x - xoId) * 180 / Math.PI; // angIe to rotate Iine
transform = 'rotate(' +angIex+ 'deg)' ; // rotation angIe
HTML5 CANVAS and CSS3 by EXAMPLES 978-0-9777812-4-9 Graphics, Games, Animations 55
Iine.attr({id: 'Iine'}).css({ // assign position
Ieft: xoId , // offset x
top: yoId , // offset y
width: Iength , // assign Iine Iength
height: 2 , // make it skinny for Iine
backgroundCoIor: c , // assign coIor
'transform-origin': "0 100%" , // defauIt 50%
transform: transform , // transform
'-webkit-transform-origin': "0 100%" , //progressivenhancement
'-webkit-transform': transform // gracefuI degradation
});
xoId = x ; yoId = y ; //
} // for x
});
</script> </body> </htmI>
HTML5 CANVAS and CSS3 by EXAMPLES 978-0-9777812-4-9 Graphics, Games, Animations 56
1.11 Moon crescent (Canvas)
The task is to create various shapes oI the moon crescent.
The crescent is create by two overlapped circles. The
second overlapped circle has the same color as the
background.
<htmI> <head> <styIe>
body {
background:
repeating-Iinear-gradient(0deg, transparent , transparent 49px, bIue 51px);
background:
-webkit-repeating-Iinear-gradient(0deg, transparent , transparent 49%, bIue 51%);
}
</styIe> </head>
<body><canvas id="myCanv" height="500" width="500"></canvas>
<script>
function init() { //- - init
canv = document.getEIementById("myCanv"); // 300 x 150 pixeIs
ctx = canv.getContext("2d"); //
num = 8; x0=250 ; y0=250 ; // totaI number of circIes
rad=100 ; r=20 ; angIe=0 ; // circIe radius
draw(); //
}
function draw() { // - - draw
for ( n=0; n < num ; n++ ) { // baIIs iteration
ctx.beginPath(); // eIse get the same coIor
x= x0 + (rad*1.0) * Math.cos(angIe) ; // position around circIe
y= y0 + (rad*1.0) * Math.sin(angIe) ; //
ctx.fiIIStyIe="bIack"; //
ctx.arc( x,y, r, 0,Math.PI*2,faIse); // sketch circIe
ctx.fiII(); // draw fuII moon
if ( n > 0 ) { // skip fuII moon
ctx.beginPath(); //
HTML5 CANVAS and CSS3 by EXAMPLES 978-0-9777812-4-9 Graphics, Games, Animations 57
x= x0 + rad * Math.cos(angIe + Math.PI * n * 0.015) ; // 2nd transparent moon
y= y0 + rad * Math.sin(angIe + Math.PI * n * 0.015) ; //
ctx.fiIIStyIe="white"; // for overIap masking
ctx.arc( x,y, r, 0,Math.PI*2,faIse); // sketch circIe
ctx.fiII(); // 2nd transparent moon
}
angIe += 2 * Math.PI / num ; // next angIe
}
}
init(); // starting
</script></body></htmI>
HTML5 CANVAS and CSS3 by EXAMPLES 978-0-9777812-4-9 Graphics, Games, Animations 58
1.12 Moon crescent (DOMJ)
The task is to create various shapes oI the moon crescent.
The crescent is create by two overlapped circles. The
second overlapped circle has the same color as the
background.
<htmI> <head> <styIe>
body {
background:
repeating-Iinear-gradient(90deg, transparent , transparent 49px, bIue 51px);
background:
-webkit-repeating-Iinear-gradient(90deg, transparent , transparent 49%, bIue 51%);
}
</styIe>
<script src="http://ajax.googIeapis.com/ajax/Iibs/jquery/1/jquery.min.js"></script>
</head> <body> <script>
var num=8, x0=y0=200, orbit=100, w=h=s=30 ; // parameters
var angIe=angIex=0;
var xoId= x0 + orbit * Math.cos(0) ; // position around circIe
var yoId= y0 + orbit * Math.sin(0) ; //
$(document).ready(function() { // wait for DOM Ioading
for(i=0; i < num ; i++ ) { // Ioop row
circIe = $('<div styIe=" position:fixed;">'); // create new div for circIe
$(document.body).append(circIe); // append new circIe div
x= x0 + orbit * Math.cos(angIe) ; // position around circIe
y= y0 + orbit * Math.sin(angIe) ; //
circIe.attr({id: 'cir'}).css({ Ieft: x , top: y , // assign position
backgroundCoIor: 'bIack' , // assign coIor
width: w , height: h , // assign size
borderRadius: w/2 , // making circIe shape
});
if ( i > 0 ) { // for 2nd and on
circIe2 = $('<div styIe=" position:fixed;">'); // create new div for circIe
$(document.body).append(circIe2); // append new circIe div
HTML5 CANVAS and CSS3 by EXAMPLES 978-0-9777812-4-9 Graphics, Games, Animations 59
x= x0 + orbit * Math.cos(angIe + Math.PI * i * 0.010) ; // position around circIe
y= y0 + orbit * Math.sin(angIe + Math.PI * i * 0.010) ; //
circIe2.attr({id: 'cir2'}).css({ Ieft: x , top: y , // assign position
backgroundCoIor: 'white' , // assign coIor
width: w , height: h , // assign size
borderRadius: w/2 , // making circIe shape
});
} // if
angIe += 2 * Math.PI / num ; // next angIe
} // for x
});
</script> </body> </htmI>
HTML5 CANVAS and CSS3 by EXAMPLES 978-0-9777812-4-9 Graphics, Games, Animations 60
1.12.1 Moon crescent with pseudo-elements (CSS3)
Given a single div markup element, can we create the
moon crescent as shown in the picture? Yes, with the
help oI pseudo-elements: ":after". Pseudo-elements
are used to insert contents to the webpage without
changing HTML codes. We use ":aIter" to create
white circle Ior "cutting out" part oI the Iull moon and
turning it into the crescent moon. The Iinal shape oI
the moon crescent is tailored by setting the physical
attributes (i.e. top, leIt, width, height) oI #crescent:aIter selector.
To insert the earth image behind the moon, we use the ":beIore" pseudo-element. The
"content" attribute is set to the earth image Iile. The z-index is set to -1 to hide the
earth behind the moon.
<htmI> <head> <styIe>
.bg {
width:1000px ; height:1000px ;
background:
repeating-Iinear-gradient(90deg, transparent , transparent 49px, bIue 51px);
background:
-webkit-repeating-Iinear-gradient(90deg, transparent , transparent 49%, bIue 51%);
background-size:50px 50px;
}
.bg:after {
content: ''; /* empty content */
position:absoIute; /* */
width:1000px ; height:1000px; /* */
background: /* */
repeating-Iinear-gradient(0deg, transparent , transparent 49px, red 51px);
background: /* */
-webkit-repeating-Iinear-gradient(0deg, transparent , transparent 49%, red 51%);
background-size:50px 50px; /* */
}
#crescent { /* the onIy DOM eIement */
position: reIative; /* fuII moon */
top: 175px; /* position */
Ieft: 175px; /* */
width: 100px; /* size */
height: 100px; /* */
border-radius: 100%; /* make circIe */
HTML5 CANVAS and CSS3 by EXAMPLES 978-0-9777812-4-9 Graphics, Games, Animations 61
background: bIue urI(dog.jpg); /* */
}
#crescent:after { /* cut out shape */
content: ''; /* empty content */
position: absoIute; /* */
top: -5px; /* position */
Ieft: -35px; /* */
width: 100px; /* size */
height: 100px; /* */
border-radius: 100%; /* make cutout circIe */
background: white; /* background coIor */
}
#crescent:before { /* insert earth */
content: urI(gIobe_72.png); /* earth image */
position: absoIute; /* */
top: 45px; /* position */
Ieft: 55px; /* */
width: 125px; /* size */
height: 125px; /* */
border-radius: 100%; /* make circIe */
z-index : -1 ; /* earth behind moon */
background: Iinear-gradient( red, yeIIow); /* IE10 */
background: -webkit-Iinear-gradient( red, yeIIow); /* Chrome Safari */
}
</styIe> </head>
HTML5 CANVAS and CSS3 by EXAMPLES 978-0-9777812-4-9 Graphics, Games, Animations 62
1.12.2 The shapes of CSS3 (CSS3)
This chapter is about creating basic
shapes with HTML5. It's hard not to
mention about the CSS3 capabilities
oI drawing complex shapes. Each shape on the leIt image is created with a single
DOM element. The Iirst three shapes use border-radius properties to get the desired
shapes. Note the last three images are created with widthheight0 and use border-
top/right/bottom/leIt properties.
<htmI> <head> <styIe>
#haIf_circIe { /* */
height:50px; width:25px; /* */
border-radius: 0 25px 25px 0; /* top right bottom Ieft */
-webkit-border-radius: 0 25px 25px 0; /* 0 right bottom 0 */
background:red; /* */
}
#quarter_circIe { /* */
width:40px; height:40px; /* */
background: red; /* */
border-radius: 40px 0px 0px 0; /* border-top-Ieft-radius */
-webkit-border-radius: 40px 0px 0px 0; /* top 0 0 0 */
position: absoIute; Ieft: 50px; top: 10px; /* */
}
#ruby { /* */
width:40px; height:40px; /* */
background: red; /* */
border-radius: 40px 0px 40px 0; /* top 0 bottom 0 */
-webkit-border-radius: 40px 0px 40px 0px; /* top-Ieft bottom-right */
position: absoIute; Ieft: 100px; top: 10px; /* */
}
#circIe { /* */
width:0; height:0; /* size=0 use border-radius */
border-top:25px soIid red; /* top */
border-right:25px soIid bIue; /* right */
border-bottom:25px soIid orange; /* bottom */
border-Ieft:25px soIid yeIIow; /* Ieft */
border-radius: 25px; /* */
-webkit-border-radius: 25px; /* */
position: absoIute; Ieft: 170px; top: 10px; /* */
-webkit-transform: rotate(45deg); /* rotate 45 degree */
transform: rotate(45deg); /* */
}
#pacman { /* */
HTML5 CANVAS and CSS3 by EXAMPLES 978-0-9777812-4-9 Graphics, Games, Animations 63
width:0; height:0; /* size=0 */
border-top:25px soIid red; /* top */
border-right:25px soIid transparent; /* right empty */
border-bottom:25px soIid purpIe; /* bottom */
border-Ieft:25px soIid orange; /* Ieft */
border-radius: 25px; /* */
-webkit-border-radius: 25px; /* */
position: absoIute; Ieft: 230px; top: 10px; /* */
}
#triangIe { /* size=0 */
width:0; height:0; /* no border-radius */
border-top:25px soIid orange; /* top */
border-right:50px soIid yeIIow; /* right */
border-bottom:25px soIid transparent; /* bottom */
border-Ieft:50px soIid red; /* Ieft */
position: absoIute; Ieft: 280px; top: 10px; /* */
}
</styIe>
<head><body>
<div id="haIf_circIe"> </div>
<div id="quarter_circIe"> </div>
<div id="ruby"> </div>
<div id="circIe"> </div>
<div id="pacman"> </div>
<div id="triangIe"> </div>
</body>
</htmI>
The Iirst two shapes on the picture are about the partial circle. Imagine that the circle
is divided into Iour quadrants with the border-radius properties:
(1) border-top-leIt-radius
(2) border-top-right-radius
(3) border-bottom-right-radius
(4) border-bottom-leIt-radius
The short Ior is:
border-radius: top-left top-right bottom-right bottom-left
For example, iI we want the top halI oI the circle with radius oI 25px, we
set (1) border-top-leIt-radius25px and (2) border-top-right-radius25px.
The border-radius oI bottom part oI the circle is set to zero: (3) border-bottom-right-
radius0 and (4) border-bottom-leIt-radius0. The short Iorm oI top halI circle
would be:
* border-radius: 25px 25px 0 0 ; /* top halI circle */
HTML5 CANVAS and CSS3 by EXAMPLES 978-0-9777812-4-9 Graphics, Games, Animations 64
The 5th image oI Pacman is created with widthheight0 and border-radius25px.
We use boundary or "border" properties to get the desired shape. Imagine again that
the circle is created by the Iour borders. The 'border-top' attribute occupies the top
portion oI the circle while the border-bottom occupies the bottom oI the circle.
Similarly, border-leIt and border-right occupy the leIt and right sides oI the circle,
respectively. To create Pacman shape, we simply make border-right to transparent.
II we want create the top halI oI the cycle Irom the 4th circle shape in the
picture, we simply set transparent to 'border-right:25px solid transparent'
and 'border-bottom:25px solid transparent'. See CSS styling code Ior Ior #circle in
the above script.
The code Ior on the last image oI the triangle in the picture is similar to
the code Ior 5th shape oI Pacman, except that we do not set the property
oI the border-radius. II we like to get the Iorward triangle shape, we only
set 'border-leIt25px solid red'. Other three border properties are set transparent.
HTML5 CANVAS and CSS3 by EXAMPLES 978-0-9777812-4-9 Graphics, Games, Animations 65
1.12.2.1 Advanced shapes with CSS3 (CSS3)
CSS3 can create much more
complex shapes with the help
oI :beIore/:aIter pseudo-elements.
<htmI> <head> <styIe>
#egg {margin-Ieft: 0; margin-top: 0 ; /* */
width: 50px; height: 75px; /* */
background-coIor: red; /* */
-webkit-border-radius: 25px 25px 25px 25px / 30px 30px 45px 45px;
border-radius: 50% 50% 50% 50% / 40% 40% 60% 60%;
}
#baIIoon { position: reIative; height:100; margin-Ieft: 60; margin-top: -90 }
#baIIoon:before { /* */
content: ""; /* empty content */
position: absoIute; /* */
Ieft: 0; top: 0; /* */
width: 75px; height: 75px; /* */
background: purpIe; /* */
border-radius: 50px 50px 0 50px; /* bot-right unchanged */
-webkit-transform: rotate(45deg); /* rotate 45 degree */
transform: rotate(45deg); /* */
}
#baIIoon:after { /* baIIoon taiI */
content: ""; /* */
position: absoIute; /* */
Ieft: 35; top: 80; /* */
width: 5px; height: 50px; /* */
background: purpIe; /* */
}
/*-- 6-star is made up of two triangIes in upside down --*/
#star { position: reIative; height:100; margin-Ieft: 150; margin-top: -110}
#star:before, #star:after {opacity:0.5; /* up triangIe */
position: absoIute; /* */
content: ""; /* */
width: 0; height: 0; /* width=height=0 */
border-Ieft: 25px soIid transparent; /* */
border-right:25px soIid transparent;/* */
border-bottom: 50px soIid bIue; /* */
Ieft: 0px; top: 0px; /* */
}
#star:after { /* bottom triangIe */
HTML5 CANVAS and CSS3 by EXAMPLES 978-0-9777812-4-9 Graphics, Games, Animations 66
border-bottom:25px soIid transparent; /* */
border-top: 50px soIid bIue; /* */
Ieft: 0px; top: 15px; /* */
}
/*-- heart is made up of two shapes, tiIIed 45 and -45 degrees --*/
#heart { position: reIative; opacity:0.5; /* */
height:100; margin-Ieft: 150; margin-top: -120;/* */
}
#heart:before { opacity:0.5; /* 45 degree shape */
position: absoIute; /* */
content: ""; /* */
width: 50px; height: 75px; /* */
border-radius: 50px 50px 0 0; /* */
background: bIue; /* */
-webkit-transform: rotate(45deg); /* */
transform: rotate(45deg); /* */
Ieft: 100px; /* */
}
#heart:after { opacity:0.5; /* -45 degree shape */
position: absoIute; /* */
content: ""; /* */
width: 50px; height: 75px; /* */
border-radius: 50px 50px 0 0; /* */
background: bIue; /* */
-webkit-transform: rotate(-45deg); /* */
transform: rotate(-45deg); /* */
Ieft: 82px;
}
/*-- peace is made up of three shapes: circIe, Iine and v-shape --*/
#peace { opacity:0.5; margin-Ieft: 300; margin-top:-10;
position: absoIute; /* outer circIe */
content: ""; /* */
width: 50px; height: 50px; /* */
border-radius: 100px ; /* */
border: 10px soIid bIue; /* */
Ieft: 25px; top: 25px; /* */
}
#peace:after { opacity:0.5; /* verticaI Iine */
position: absoIute; /* */
content: ""; /* */
border: 5px soIid bIue; /* */
width: 0px; height: 50px; /* */
Ieft: 20px; top: -0px; /* */
}
#peace:before { opacity:0.5; /* reverse v shape */
position: absoIute; /* */
HTML5 CANVAS and CSS3 by EXAMPLES 978-0-9777812-4-9 Graphics, Games, Animations 67
content: ""; /* */
border-top: 10px soIid bIue; /* */
border-right: 10px soIid bIue; /* */
width: 30px; height: 30px; /* */
-webkit-transform: rotate(-45deg); /* */
transform: rotate(-45deg); /* */
Ieft: 5px; top: 25px; /* */
}
</styIe>
<head><body>
<div id="egg"> </div><p>
<div id="baIIoon"></div><p>
<div id="star"> </div><p>
<div id="heart"> </div><p>
<div id="peace"> </div><p>
</body>
</htmI>
II you have the urge in creating more complex shapes with CSS3, you may want to
visit the webapage oI Nicolas Gallagher at http://nicolasgallagher.com.
border-radius: 50 50 50 50 / 40 40 60 60 ;
This is equivalent to the top-leIt (50/40), top-right (50/40), bottom-right
(50/60) and bottom-leIt (50/60) corner. The x-curve is applied equally at
50 oI the width or 25px Ior all corners. The y-curvatures oI the two bottom coners
(60 oI the height or 45px) are more pronounced than those oI the two top coners
(40 oI the height or 30px), hence we see the egg shape upside down.
border-radius: 50px 50px 0 50px ;
This is almost like a circle, except that we set zero to the bottom-right
corner, which still has original sharp corner. This shape is beIore 45-
degree rotation.
border-top: 10px solid blue ; border-right: 10px solid blue ;
Here we speciIy the top and right sides oI the rectangle. Other sides (leIt
and bottom) are not visible. This shape is beIore -45 degree rotation.
HTML5 CANVAS and CSS3 by EXAMPLES 978-0-9777812-4-9 Graphics, Games, Animations 68
1.12.3 Moon crescent with color gradient (Canvas)
In the linear gradient, colors
change smoothly Irom one region
to an opposite region in the
straight-line manner. The deIault
is the color transition starting Irom
the top to the bottom. We can
speciIy many intermediate colors,
besides the starting color and
ending color. We can control the
percentage amount that a
particular color occupies. There is
also a repeating option where the
same color pattern keeps
repeating. In this example, we
have created seven linear gradient objects: six Ior shapes and one Ior background.
<htmI> <head> <styIe>
body {
background-coIor: transparent;
background:
repeating-Iinear-gradient(45deg, transparent , transparent 49px, bIue 51px);
background:
-webkit-repeating-Iinear-gradient(45deg, transparent , transparent 49%, bIue 51%);
background-size:50px 50px;
}
body:before {
content: ''; /* empty content */
position:absoIute; /* */
width:1000px ; height:1000px ; /* */
background-coIor: transparent; /* */
background: /* */
repeating-Iinear-gradient(-45deg, transparent , transparent 49px, red 51px);
background: /* */
-webkit-repeating-Iinear-gradient(-45deg, transparent , transparent 49%, red 51%);
background-size:50px 50px; /* */
}
</styIe> </head>
<body><canvas id="myCanv" height="500" width="500"></canvas>
<script>
function init() { //- - init
canv = document.getEIementById("myCanv"); // 300 x 150 pixeIs
HTML5 CANVAS and CSS3 by EXAMPLES 978-0-9777812-4-9 Graphics, Games, Animations 69
ctx = canv.getContext("2d"); //
num = 11; x0=250 ; y0=250 ; // totaI number of circIes
rad=150 ; r=35 ; angIe=0 ; // circIe radius
draw(); //
}
function draw() { // - - draw
for ( n=0.0; n < 1.0 ; n += 0.1 ) { // baIIs iteration
ctx.beginPath(); // eIse get the same coIor
x= x0 + rad * Math.cos(angIe) ; // position around circIe
y= y0 + rad * Math.sin(angIe) ; //
set_radiaI( x,y,0, x+25,y,r, 'white', 'white', 'bIue', n ) ; // off-center
ctx.arc( x,y,r,0,2*Math.PI,faIse ) ; // smaIIer inner circIe
ctx.fiII() ; //
ctx.strokeText(Math.round(n*100)/100 , x, y) ; // round to 2 digits
angIe += 2 * Math.PI / num ; // next angIe
}
}
function set_radiaI( x1,y1,r1, x2,y2,r2, c0,c1,c2, i1 ) { // - - radiaI gradient
fiIICoIor = ctx.createRadiaIGradient(x1,y1,r1, x2,y2,r2 ) ; //
fiIICoIor.addCoIorStop( 0 , c0 ) ; // inner circIe
fiIICoIor.addCoIorStop( i1, c1 ) ; // transitionaI coIor
fiIICoIor.addCoIorStop( 1 , c2 ) ; // outer circIe
ctx.fiIIStyIe= fiIICoIor ; //
}
init(); // starting
</script></body></htmI>
HTML5 CANVAS and CSS3 by EXAMPLES 978-0-9777812-4-9 Graphics, Games, Animations 70
1.12.4 Moon crescent with color gradient (DOMJ)
In the linear gradient, colors change smoothly
Irom one region to an opposite region in the
straight-line manner. The deIault is the color
transition starting Irom the top to the bottom.
We can speciIy many intermediate colors,
besides the starting color and ending color. We
can control the percentage amount that a
particular color occupies. There is also a
repeating option where the same color pattern
keeps repeating. In this example, we have
created seven linear gradient objects: six Ior
shapes and one Ior background.
<htmI> <head> <styIe>
body {
width:300px ; height:300px ;
background: radiaI-gradient(circIe, red 2%, transparent 10%) 50px 50px ,
radiaI-gradient(circIe, bIue 2%, transparent 10%) 0px 0px ;
background: -webkit-radiaI-gradient(circIe,red 2%,transparent 10%) 50px 50px,
-webkit-radiaI-gradient(circIe,bIue 2%,transparent 10%) 0px 0px;
background-size: 100px 100px;
}
</styIe>
<script src="http://ajax.googIeapis.com/ajax/Iibs/jquery/1/jquery.min.js"></script>
</head> <body> <script>
var num=8, x0=y0=200, orbit=100, w=h=s=60 ; // parameters
var angIe=angIex=0;
var xoId= x0 + orbit * Math.cos(0) ; // position around circIe
var yoId= y0 + orbit * Math.sin(0) ; //
$(document).ready(function() { // wait for DOM Ioading
for(i=-200; i < 200 ; i += 50 ) { // Ioop row
circIe = $('<div styIe=" position:fixed;">'); // create new div for circIe
$(document.body).append(circIe); // append new circIe div
x= x0 + orbit * Math.cos(angIe) ; // position around circIe
y= y0 + orbit * Math.sin(angIe) ; //
if (navigator.appName == 'Microsoft Internet ExpIorer') { // ie? Netscape
HTML5 CANVAS and CSS3 by EXAMPLES 978-0-9777812-4-9 Graphics, Games, Animations 71
c = "-ms-radiaI-gradient("+ i +"% 50%, white, white,bIue)"; // yes
} eIse { c = "-webkit-radiaI-gradient("+ i +"% 50%, white, white,bIue)" } ; // no
circIe.attr({id: 'cir'}).css({ Ieft: x , top: y , // assign position
background: c , // assign coIor
width: w , height: h , // assign size
borderRadius: w/2 , // making circIe shape
});
angIe += 2 * Math.PI / num ; // next angIe
} // for x
});
</script> </body> </htmI>
HTML5 CANVAS and CSS3 by EXAMPLES 978-0-9777812-4-9 Graphics, Games, Animations 72
1.13 Circle of Text with .transform() (Canvas)
This example is to show the power oI using
cumulative eIIect oI .transIorm() in the loop.
Each loop iteration executes one .transIorm()
command. II we have the loop with 32
iterations, then it's like we execute .transIorm
() 32 times in the accumulation Iashion.
We create 32 texts (HTML0-HTML31)
surrounding the inner circle as shown in the
picture. We divide the Iull circle into 32
portions. Each portion is Ior each loop iteration. The text oI the outer circle increases
in the clock-wise direction.
<!DOCTYPE HTML>
<htmI> <head> <script type="text/javascript">
function draw(){ //- - draw()
var can = document.getEIementById('mycan'); //
var ctx = can.getContext('2d'); //
var sin = Math.sin(Math.PI/16); // ~0.1950 fuII circIe: 32 portions
var cos = Math.cos(Math.PI/16); // ~0.9807
ctx.transIate(200, 200); // move circIe center to 200,200
for (i=0; i <= 31; i++) { // inner Ioop
ctx.fiIIText("HTML"+i,40, 0); // radius -> 40
ctx.transform(cos, -sin, sin, cos,0,0); // anticIock direction;same size
}
for (i=0; i <= 16; i++) { // outer Ioop
ctx.fiIIText("HTML"+i,100, 0); // radius-> 100
ctx.transform(cos, sin, -sin, cos,0,0); // cIockwise direction;same size
}
}
</script>
</head>
<body onIoad="draw();">
<canvas id="mycan" width="800" height="800"></canvas>
</body>
</htmI>
HTML5 CANVAS and CSS3 by EXAMPLES 978-0-9777812-4-9 Graphics, Games, Animations 73
1.14 Circle of Text with jQuery/CSS3 (DOMJ)
The task is to create a circle oI text in the
DOM-based graphics.
<htmI> <head>
<script src="jquery-1.7.2.min.js"></script>
</head> <body> <script>
var num=31, x0=y0=200, orbit=100, w=h=s=30 ; // parameters
var angIe=angIex=0; //
$(document).ready(function() { // wait for DOM Ioading
for(i=0; i < num ; i++ ) { // Ioop row
circIe = $('<div styIe=" position:fixed;">'); // create new div for circIe
$(document.body).append(circIe); // append new circIe div
x= x0 + orbit * Math.cos(angIe) ; // assign position around circIe
y= y0 + orbit * Math.sin(angIe) ; //
angIex = angIe * 180 / Math.PI ; // angIe to rotate Iine
transform = 'rotate(' +angIex+ 'deg)' ; // rotation angIe
circIe.attr({id: 'cir'}).css({ Ieft: x , top: y , // assign position
backgroundCoIor: 'yeIIow' , // assign coIor
width: 60 , height: 20 , // assign size
transformOrigin: "0 100%" , // defauIt 50%
transform: transform, // transform
webkitTransformOrigin:"0 100%", // progressive enhancement
webkitTransform: transform // gracefuI degradation
}).htmI( "HTML" + i ) ;
angIe += 2 * Math.PI / num ; // next angIe
} // for x
});
</script> </body> </htmI>
HTML5 CANVAS and CSS3 by EXAMPLES 978-0-9777812-4-9 Graphics, Games, Animations 74
1.15 Text wrapped around a circle (Canvas)
The task is to wrap the two text messages around
a circle. The message in the outer ring is wrapped
with the bottom oI the letters pointing to the
center the circle. The message in the inner ring is
wrapped with the side oI the letters pointing to
the center oI the circle.
<htmI> <head> <script>
var ctx;
function draw(x,y,r,startAngIe,font,message){ //- - draw()
ctx.font=font; //
ctx.transIate(x,y); //
ctx.rotate(startAngIe); //
ctx.beginPath(); //
ctx.IineWidth=5; //
ctx.arc(0,0,r-8,0,Math.PI * 2, faIse); //
ctx.stroke(); //
for(var i=0;i<message.Iength;i++){ //
ctx.save(); //
ctx.transIate(r, 0); //
ctx.rotate(Math.PI/2) ; //
ctx.fiIIText(message[i],0,0); //
ctx.restore(); //
ctx.rotate(2*Math.PI / message.Iength); //
}
}
function init() { //- - init()
var canv = document.getEIementById('mycan'); //
ctx = canv.getContext('2d'); //
ctx.save() ; //
draw(200,200,70,Math.PI,"boId 20px sans-Serif","UNITED NATIONS SECURITY " );
ctx.restore(); //
draw(200,200,100,Math.PI*2.00,"boId 20px sans-serif",
"UNITED STATES CALIFORNIA");
}
</script> </head>
<body onLoad="init()";>
<canvas id="mycan" width="800" height="800"></canvas>
</body> </htmI>
HTML5 CANVAS and CSS3 by EXAMPLES 978-0-9777812-4-9 Graphics, Games, Animations 75
1.16 Text wrapped around a circle (DOM)
The task is to wrap the two text messages around a
circle. The text can be rotated at any angle. The
message "CALIFORNIA" in the inner circle is
rotated with 0 degree. The message on the outer
circle is rotated 90-degree.
This example is very similar to example 1.14. But
here we intentionally do not use jQuery and we also
avoid explicit calculation oI circle coordinates.
<htmI>
<head>
<script>
function draw(id,rad,angIe,Ieft,top,rot,c ) { // - - draw
var Iis = document.getEIementById(id).getEIementsByTagName("Ii"); //
for(var j = 0; j < Iis.Iength; j++) { // 1 message
ncir = document.createEIement("div") ; // new div
document.getEIementById(id).appendChiId(ncir); // append
ncir.styIe.height = 2*rad-50 + "px" ; // height of circIe
ncir.styIe.width = 2*rad-50 + "px" ; // width for circIe
ncir.styIe.borderRadius = 2*rad + "px" ; // make circIe
ncir.styIe.border="35px soIid " + c ; // set coIor for circIe
ncir.styIe.marginLeft = Ieft-rad-10 +"px" ; //
ncir.styIe.marginTop = top-8 +"px" ; //
ncir.styIe.position="absoIute"; // fixed
var vaIue = Iis.item(i).innerHTML; //
for(var i=0;i<vaIue.Iength;i++){ //
ndiv = document.createEIement("div") ; // new div
document.getEIementById(id).appendChiId(ndiv); // append
ndiv.styIe.marginLeft = Ieft +"px" ; //
ndiv.styIe.marginTop = top +"px" ; //
ndiv.styIe.height = rad ; // height of circIe
ndiv.styIe.position="absoIute"; // fixed
HTML5 CANVAS and CSS3 by EXAMPLES 978-0-9777812-4-9 Graphics, Games, Animations 76
ndiv.styIe.transformOrigin="0 100%" ; //
ndiv.styIe.webkitTransformOrigin="0 100%" ; //
angIe += 360/vaIue.Iength ; //
ndiv.styIe.transform = "rotate(" + angIe + "deg)"; //
ndiv.styIe.webkitTransform="rotate(" + angIe + "deg)"; //
ndiv2 = document.createEIement("div") ; // new div
ndiv.appendChiId(ndiv2); // append
ndiv2.styIe.transform = "rotate(" + rot + "deg)"; //
ndiv2.styIe.webkitTransform = "rotate(" + rot + "deg)"; //
ndiv2.innerHTML= vaIue[i] ; //
} // message
}
}
</script>
</head>
<body onIoad="draw('msg' ,80 ,-65 , 120 ,30, -90, 'red' );
draw('msg2',40 ,-65 , 120 ,50, 0, 'bIue' );">
<div id="msg"><Ii>UNITED NATIONS SECURITY </div>
<div id="msg2"><Ii>CALIFORNIA </div>
</body>
</htmI>
HTML5 CANVAS and CSS3 by EXAMPLES 978-0-9777812-4-9 Graphics, Games, Animations 77
1.17 Popping Up (Canvas)
The task is to randomly popping up the
balloons with random sizes, locations, and
colors. Given times, the balloons will Iill the
whole canvas. The balls are created with color
radial gradient.
<htmI>
<canvas id="canv" width="560" height="420" styIe="background:bIack">
<script>
var canv = document.getEIementById('canv'); //
var ctx = canv.getContext('2d'); //
var n = 0 ; // baII number
function draw() { //- - draw()
ctx.beginPath(); // beginPath
var x = Math.random() * canv.width ; // random x y
var y = Math.random() * canv.height ; // ipad 2048 x 1536
var r = Math.random() * 50 + 20 ; // random radius
var red =Math.fIoor(Math.random()*255) ; // random red
var green=Math.fIoor(Math.random()*255) ; // random green
var bIue =Math.fIoor(Math.random()*255) ; // random bIue
var c = "rgb(" +red +"," +green +"," +bIue +")"; // rbg(0-255,0-255,0-255)
var fiIICoIor = ctx.createRadiaIGradient(x-5,y-5,0, x,y,r ); // radiaI gradient
fiIICoIor.addCoIorStop( 0, "white" ); // inner white
fiIICoIor.addCoIorStop( 1, c ); // outer coIor
ctx.fiIIStyIe= fiIICoIor; //
ctx.gIobaIAIpha = 0.8; // opacity
ctx.arc( x, y, r, 0, Math.PI*2, faIse); // draw circIe
ctx.fiII(); // fiII
ctx.strokeText( n++, x, y); // draw text
}
setIntervaI( function() { draw() } , 500 ); // timer
</script> </body></htmI>
HTML5 CANVAS and CSS3 by EXAMPLES 978-0-9777812-4-9 Graphics, Games, Animations 78
1.18 Popping up (DOM)
The task is to randomly popping up the
balloons with random sizes and colors in the
DOM-based webpage. No canvas tag is
involved. We use setTimeout() timer Ior each
new balloon. To prevent the balloons popping
up the same time, we increase the timer
duration Ior each new balloon.
<htmI> <script>
var nDiv = nuII; // new div circIe
var n=0; // counting circIe
for( i=0; i < 200; i++){ // popping 200 circIes
setTimeout(addCircIe, i*66 ); // timer: increasing in time
}
function addCircIe() { // - - addCircIe
nDiv = document.createEIement("div"); // create new div for baII
var r = Math.fIoor( Math.random() *90 ) + 5; // random radius
var c = "#" + Math.fIoor(Math.random() * 16777216 ).toString(16); // random coIor
var x = Math.fIoor( Math.random() * 520 ) + 00 ; // random x
var y = Math.fIoor( Math.random() * 420 ) + 00 ; // random y
nDiv.styIe.width=r; // assign width to object
nDiv.styIe.height=r; // assign height to object
nDiv.styIe.borderRadius=r/2 + "px"; // circIe shape
nDiv.styIe.background=c; // assign coIor to object
nDiv.styIe.background="radiaI-gradient(circIe,white,"+c+")" ; // assign coIor
nDiv.styIe.marginLeft=x; // assign Ieft margin
nDiv.styIe.marginTop=y; // assign top margin
nDiv.styIe.position="absoIute"; // position absoIute
nDiv.styIe.opacity=0.8; // opacity
nContent=document.createTextNode(n++); // create text object
nDiv.appendChiId(nContent); // append text object
topi = document.getEIementById("top"); // get existing div
document.body.insertBefore(nDiv, topi); // insert new div
}
</script>
<body>
<div id='top' styIe="background:bIue; width:520; height:420;" > Popping Up</div>
</body> </htmI>
HTML5 CANVAS and CSS3 by EXAMPLES 978-0-9777812-4-9 Graphics, Games, Animations 79
1.19 Pacman running (Canvas)
The task is to create Pacman running across the screen with its mouth
chewing.
<htmI> <head> <script type="text/javascript" >
var can, ctx, intervaIID ; //
var x = 0, y = 50 ; // starting position
var dx = 1 , dt =33 ; // speed; refresh
var dr = Math.PI*0.02 ; // angIe rate
var angIe = 0 ; // stating angIe
function init() { // - - init
can = document.getEIementById("canv"); // get canvas ID
ctx = can.getContext("2d"); // get 2-D context
ctx.fiIIStyIe="red" ; // set pacman coIor
draw(); // draw
}
function startdraw() { // - - start draw
cIearIntervaI(intervaIID); // cIear time intervaI
intervaIID = setIntervaI(draw, dt); // set time intervaI
}
function draw() { // - - draw
ctx.cIearRect(0,0,can.width,can.height); // cIear screen
// pacman drawing
ctx.beginPath(); // drawing pacman
angIe += dr ; // new mouth angIe
ctx.moveTo(x,y); //
ctx.arc(x,y,10, angIe, Math.PI * 2 - angIe, faIse); //
ctx.cIosePath(); //
ctx.fiII(); //
// reset range for moving mouth
if (Math.abs(angIe) > Math.PI*0.1) angIe=0 ; // set max mouth angIe
x += dx ; // new position
startdraw(); // startdraw
}
</script>
</head>
<body onIoad="init()">
<canvas id="canv" width="300" height="720" ></canvas>
</body> </htmI>
HTML5 CANVAS and CSS3 by EXAMPLES 978-0-9777812-4-9 Graphics, Games, Animations 80
1.20 Pacman running (CSS3)
The task is to create Pacman a running across the screen with its mouth
chewing. The trick is to create two halI-circles: the top halI-circle is Ior
the upper jaw while the bottom halI is Ior lower jaw. The two jaws
rotate in opposite directions to make the Pacman chewing.
<htmI> <head>
<styIe>
.top { /* */
position:reIative; /* */
Ieft: 20px ; top: 50px ;
-ms-animation: moving 5s Iinear infinite; /* */
-webkit-animation: moving 5s Iinear infinite; /* */
}
.pacman-top { /* */
position: absoIute; /* */
width: 100px; /* */
height: 100px; /* */
border-radius: 50px; /* */
cIip: rect(0px, 50px, 100px, 0px); /* cIip Ieft */
background-coIor: yeIIow; /* */
-webkit-animation: toggIe_top 0.5s Iinear infinite; /* */
-ms-animation: toggIe_top 0.5s Iinear infinite; /* */
}
.pacman-bot { /* */
position: absoIute; /* */
width: 100px; /* */
height: 100px; /* */
border-radius: 50px; /* */
cIip: rect(0px, 100px, 100px, 50px); /* cIip right */
background-coIor: yeIIow; /* */
-webkit-animation: toggIe_bot 0.5s Iinear infinite; /* */
-ms-animation: toggIe_bot 0.5s Iinear infinite; /* */
}
@-webkit-keyframes moving { /* */
0% { Ieft:0px ; } /* */
100% { Ieft:500px; } /* */
}
@-ms-keyframes moving { /* */
0% { Ieft:0px } /* */
100% { Ieft:500px } /* */
HTML5 CANVAS and CSS3 by EXAMPLES 978-0-9777812-4-9 Graphics, Games, Animations 81
}
@-webkit-keyframes toggIe_top { /* */
0% {-webkit-transform:rotate(90deg)} /* */
50% {-webkit-transform:rotate(45deg)} /* */
100% {-webkit-transform:rotate(90deg)} /* */
}
@-ms-keyframes toggIe_top { /* */
0% { -ms-transform:rotate(90deg); } /* */
50% { -ms-transform:rotate(45deg); } /* */
100% { -ms-transform:rotate(90deg); } /* */
}
@-webkit-keyframes toggIe_bot { /* */
0% {-webkit-transform:rotate(90deg) } /* */
50% {-webkit-transform:rotate(125deg)} /* */
100% {-webkit-transform:rotate(90deg) } /* */
}
@-ms-keyframes toggIe_bot { /* */
0% { -ms-transform:rotate(90deg); } /* */
50% { -ms-transform:rotate(125deg); } /* */
100% { -ms-transform:rotate(90deg); } /* */
}
</styIe>
</head>
<body>
<div cIass="top">
<div cIass="pacman-top"></div>
<div cIass="pacman-bot"></div>
</div>
</body> </htmI>
HTML5 CANVAS and CSS3 by EXAMPLES 978-0-9777812-4-9 Graphics, Games, Animations 82
1.21 Pacman running (DOMJ)
The task is to create Pacman a running across the screen with its mouth
chewing. The trick is to create two halI-circles: the top halI-circle is Ior
the upper jaw while the bottom halI is Ior lower jaw. The two jaws
rotate in opposite directions to make the Pacman chewing.
<htmI> <head>
<script src="http://code.jquery.com/jquery-Iatest.js"></script>
<styIe>
.pacman { /* */
position:reIative; /* */
Ieft: 20px ; top: 50px ; /* */
}
.pacman-top, .pacman-bot { /* */
position: absoIute; /* */
width: 100px; /* */
height: 100px; /* */
border-radius: 50px; /* */
background-coIor: yeIIow; /* */
}
.pacman-top { /* */
cIip: rect(0px, 100px, 50px, 0px); /* cIip top */
}
.pacman-bot { /* */
cIip: rect(50px, 100px, 100px, 0px); /* cIip bottom */
}
</styIe>
<script>
deIta = 20 ; deg = -deIta ; ddeg = 1 ; // parameters
$(function(){ //
function chewing() { // mouth chewing
//$(".pacman-top").css({ WebkitTransform: 'rotate(' + deg + 'deg)' });
//$(".pacman-bot").css({ WebkitTransform: 'rotate(' + -deg + 'deg)' });
$(".pacman-top").css({ transform: 'rotate(' + deg + 'deg)' });
$(".pacman-bot").css({ transform: 'rotate(' + -deg + 'deg)' });
deg += ddeg ;
if ( deg > 0 || deg < -deIta ) ddeg *= -1 ; // toggIing mouth
}
function moving() { // pacman moving
HTML5 CANVAS and CSS3 by EXAMPLES 978-0-9777812-4-9 Graphics, Games, Animations 83
Ieft = parseInt($(".pacman").css("Ieft")); // get current x of pacman
$(".pacman").css("Ieft", ++Ieft ); // move up
}
function draw() { chewing() ; moving() ; } // - - draw
setIntervaI( draw, 33 ) ; // shooting timer
}); // function
</script>
</head>
<body onLoad="draw();">
<div cIass="pacman">
<div cIass="pacman-top"></div>
<div cIass="pacman-bot"></div>
</div>
</body> </htmI>
HTML5 CANVAS and CSS3 by EXAMPLES 978-0-9777812-4-9 Graphics, Games, Animations 84
1.22 A wheel (DOMJ)
The task is to create a Iunction to create
wheels in various shapes. The user speciIies
the wheel radius, the number oI spokes, the
spoke width, etc...
<htmI>
<head>
<script src="jquery-1.7.2.min.js"></script>
</head>
<body>
<script>
$(document).ready(function() { // wait for DOM Ioading
wheeI(64, 200, 200, 75, 1,"green",0,0 ); // 1st wheeI
wheeI(16, 400, 200, 75, 5,"red" ,1,0 ); // 2nd wheeI
wheeI( 8, 600, 200, 50, 5,"bIue" ,1,0 ); // 3rd wheeI
function wheeI(num,x0,y0,orbit, w,c,outer,angIe) { // - - wheeI
circIe = $('<div styIe=" position:absoIute;">'); //create new div 4 circIe
if (outer) $(document.body).append(circIe); // append new circIe div
circIe.attr({id: 'cir'}).css({ //
Ieft: x0-orbit-10 , top: y0-orbit-3 , // assign position
border: "20px soIid " + c , //
width: orbit*2-20 , height: orbit*2-20 , // assign size
borderRadius: orbit*2, // making circIe shape
});
for(i=0; i < num ; i++ ) { // Ioop row
x= x0 + orbit * Math.cos(angIe) ; // position around circIe
y= y0 + orbit * Math.sin(angIe) ; //
angIe += 2 * Math.PI / num ; // next angIe
Iine = $('<div styIe=" position:fixed;">'); //create new div 4 circIe
$(document.body).append(Iine); // append new circIe div
Iength = Math.sqrt((x0-x)*(x0-x) + (y0-y)*(y0-y)) + 00; // distance from origin
angIex = Math.atan2(y - y0, x - x0) * 180 / Math.PI; // angIe to rotate Iine
transform = 'rotate(' +angIex+ 'deg)' ; // rotation angIe
Iine.attr({id: 'Iine'}).css({ // assign position
Ieft: x0 , // offset x
HTML5 CANVAS and CSS3 by EXAMPLES 978-0-9777812-4-9 Graphics, Games, Animations 85
top: y0 , // offset y
width: Iength , // assign Iine Iength
height: w , // make it skinny for Iine
backgroundCoIor: c , // assign coIor
'transform-origin': "0 100%" , // defauIt 50%
transform: transform , // transform
'-webkit-transform-origin': "0 100%" , // progressive
'-webkit-transform': transform // enhancement
});
} // for x
} // function
});
</script> </body> </htmI>
HTML5 CANVAS and CSS3 by EXAMPLES 978-0-9777812-4-9 Graphics, Games, Animations 86
1.23 Bezier curves (Canvas)
The task is to create Bezier curves with two
random control points. A new Bezier shape is
poped up every 500 msec. We also create a
timer Iunction to clear the screen every 5000
msec or 5 seconds, so the maximum oI ten
curves are displayed on the screen.
<htmI>
<body>
<canvas id="myCan" styIe="background:bIacK" width=720 height=420>
</canvas>
<script>
var canv = document.getEIementById('myCan'); //
var ctx = canv.getContext('2d'); //
var t=1500 ; // time iteration
function draw() { // - - draw
ctx.beginPath(); //
c1x = canv.height * Math.random(); // bezier controI 1
c1y = canv.height * Math.random(); // bezier controI
c2x = canv.height * Math.random(); // bezier controI 2
c2y = canv.height * Math.random(); // bezier controI
x = canv.width * Math.random(); // random point
y = canv.height * Math.random(); //
x1 = canv.width / 2 ; // mid- point
y1 = canv.height / 2 ; //
ctx.moveTo( x1 , y1 ) ; // starting point
ctx.bezierCurveTo( c1x,c1y, c2x,c2y, x,y ); // bezier curve
ctx.cIosePath(); // fuII Ioop
ctx.IineWidth = Math.random() * 20; //
ctx.strokeStyIe = 'hsI(' + Math.random()*360 + ', 50%, 50%)'; //
ctx.shadowCoIor = 'white'; //
ctx.shadowBIur = Math.random()*50 ; //
ctx.stroke(); //
ctx.strokeRect(c1x,c1y,1,1); // pIot controI point 1
ctx.strokeRect(c2x,c2y,2,2); // pIot controI point 2
}
draw();
setIntervaI(draw, t); // timer
HTML5 CANVAS and CSS3 by EXAMPLES 978-0-9777812-4-9 Graphics, Games, Animations 87
// if want to see maximum of 10 shapes
setIntervaI(function(){ ctx.cIearRect(0,0, canv.width, canv.height)},10*t);
</script>
</body>
</htmI>
HTML5 CANVAS and CSS3 by EXAMPLES 978-0-9777812-4-9 Graphics, Games, Animations 88

You might also like