SlideShare a Scribd company logo
1 of 53
March 19, 2012



        7 – 9 PM CLASS
        WELCOME
HOST: APPNEXUS
THANK YOU
INTRODUCTION



       INSTRUCTOR
 ROBYN OVERSTREET
WHAT IS
          HTML5 CANVAS?
• HTML5 element, now part of HTML5 API
• Used for drawing and animating directly in HTML, with
JavaScript scripting
• Originally developed by Apple for Dashboard widgets
WHAT CAN IT DO?

• Dynamically draw shapes, images and text
• Respond to user input – mouse, keyboard, touch, etc.
• Animation without Flash
• Create interactive charts and graphs
CANVAS IN       ACTION
• Rough GuidesKEXP Archive Sketchpad Wired
  Mind NYC Restaurant Health Ratings Map
BROWSER SUPPORT
• Firefox
•Chrome
•Safari
•IE 9
• See CanIUse.com for up-to-date support info
2D
DRAWING
THE
GRID
SET-UP FOR DRAWING
                                           grab the canvas
                                               element


var mycanvas = document.getElementById("the_canvas");

var context = mycanvas.getContext("2d");



  set up a 2D context
DRAWING A RECTANGLE
context.fillStyle = "rgba(0, 204, 204, 1)";

context.fillRect(40,50,110,70);
DRAWING LINES

 context.beginPath(); //set up to draw a path
 context.moveTo(x,y); //move to the start position
 context.lineTo(x,y); //set the end
 pointcontext.stroke(); //draw the line




                                              3. Draw line between
1. Set start position                                points




                        2. Set end position
DRAWING CURVES
        Control point 1          Control point 2
   bezierCurveTo(100,25 ...       ...400,25...




  Start point
MoveTo(25,125)                Destination point
                                ...325,125);
CODING CURVES

var controlPt1 = {x:110,y:30};
var controlPt2 = {x:130,y:80};
var startPt = {x:75,y:140};
ctx.beginPath(); //prepare path
ctx.moveTo(startPt.x,startPt.y);
ctx.bezierCurveTo(
      controlPt1.x,controlPt1.y,
      controlPt2.x,controlPt2.y,
      startPt.x,startPt.y
);
ctx.stroke();
DRAWING ARCS
                 1.5 * PI
Start angle
Start angle




PI                                 0


  Center point               End angle
                             End angle
  Center point

                 0.5 * PI
DRAWING ARCS & CIRCLES
• Circles are types of arcs
• Angles are in radians (need to calculate
  between degrees and radians)

ctx.beginPath();ctx.arc(x, y, radius, 0, Math.PI*2,
true);ctx.closePath();ctx.fill();



              Start angle
              Start angle      End angle
                               End angle
TEXT
• Text is "drawn" to the canvas
  context.fillText("Hello world", 10, 50);




• Style text in CSS syntax with .font property


• Get the dimensions of a text area
textObj = ctx.measureText(d);
width = textObj.width;
TRANSFORMATION
      S
TRANSFORMATIONS

• To change the orientation of one element on
  the canvas, you must shift the entire canvas
• Translate: move the canvas and its origin to a
  different point in the grid
• Rotate: rotate the canvas around the current
  origin
TRANSLATE CONTEXT




  Context moved.
   Context moved.
The origin point now
The origin point now
 has a new location.
 has a new location.
TRANSLATE & ROTATE




Translate         Rotate
translate(x, y)   rotate(angle)
THE         STATE STACK
State 1Fill Style: redRotation: 45deg             State 2
Fill Style: redRotation: 45deg


                                                        State 1
                                    save()
tate 2Fill Style: blackLine Style: blue
cale: 50%
                                               restore()
cale: 50%
SAVE & RESTORE
ctx.fillRect(0,0,150,150); //Draw with default settings
ctx.save(); // Save the default state    ctx.fillStyle =
'#09F'; //Change the fill color
                                                         state 1
ctx.fillRect(15,15,120,120); // Draw with new settings
ctx.save(); //Save the current state

ctx.fillStyle = '#FFF'; //Change fill again
ctx.fillRect(15,15,120,120); // Draw with new settings     state 2

ctx.restore(); //Restore to last saved state
ctx.fillRect(45,45,60,60); //Draw with restored settings
                                                   back to state 2
IMAGE
MANIPULATION
DRAW IMAGE
var img = new Image();   //Create an image objectimg.src =
'dog.png'; //Set source
img.onload = function(){ //Wait for the image to load
      context.drawImage(img,x,y); //Draw image to canvas
}
REDRAW IMAGE
//clear the stage
clearRect(0,0,canvas.width,canvas.height);
speed = 10;
if (previous_x < mouse_x){
direction = 1; //moving left to right
} else {
direction = -1; //moving right to left
}
var new_x = previous_x + (speed * direction);
context.drawImage(img,new_x,y);
IMAGES AT THE PIXEL LEVEL
Get image data and loop through pixel by pixel
LOOPING THROUGH PIXELS

c.drawImage(img,0,0);var imgData =
c.getImageData(0,0,canvas.width,canvas.height);
for(n=0; n<data.width*data.height; n++) {var index =
n*4; //each pixel has 4 data points
//rgb values from 0-255
red = imgData.data[index];green = imgData.data[index+1];blue
= imgData.data[index+2];
alpha = imgData.data[index+3];
//to reset pixels, change the values in the data array
imgData.data[index+2] = 255; //change the blue value
}
}
ANIMATION
ANIMATION


Canvas doesn't track objects on the screen –
You must redraw the stage for each movement



        Use event listeners or timers
FOLLOW THE             MOUSE


• Draw the image on the canvas
• Track the position of the mouse (event listener
  for every mouse move)
• Redraw the image every n seconds based on
  the x position of the mouse
VISUALIZE DATA
USE JSON DATA TO CREATE
DYNAMIC DRAWINGS

CONNECT TO A WEB SERVICE
(TWITTER, FOURSQUARE, ETC)
BAR CHART
MAP DATA TO CANVAS

//the data could also come in as a JSON object
var data = {jane: 231,julie: 325,ben: 276}; //js object
var highest_value = 325; //find programmatically
var pixel_units = canvas.height/highest_value;
for (user in data){ //loop through data points
var bar_height = data[user] * pixel_units;
var bar_title = user;
}
//now it's time to draw!
COOL EXAMPLE
Each bubble represents a tweet containing the word "water". Popping the
bubble displays the tweet.
GRAPHING LIBRAIRIES


• jQuery VisualizeAwesomeChartJS ... many
  more
• ... many more
MOBILE TIPS
• Javascript touch events instead of mouse
  events
• PhoneGap Framework to compile to native iOS
  and Android apps
CANVAS
GAMES
GAMES EXAMPLES
• Alex the Alligator http://alex4.tapjs.com
• CATcher http://wpsystem.com.br/catcher/
• Catch the goblin http
  ://www.lostdecadegames.com/how-to-make-a-
  simple-html5-canvas-game/
• Magician Fairy Rescue
  http://www.relfind.com/game/magician.html
• Canvas Rider, bike game http://canvasrider.com/
CANVAS RIDER
ORBIUM
SIMPLE GAME EXAMPLE
CODING GOBLINS
1.Draw images for background, player, and
  goblin
2.Listen for arrow keys and change player
  coordinates accordingly
3.Detect hit by comparing monster's
  coordinates to player's coordinates
4.Redraw as frequently as possible
3D
DRAWING
3D IN CANVAS
3D
•   A few options:
•   Canvas 3D context
•   Canvas WebGL context
•   Simulated 3D in 2D context
•   Libraries ... three.js, c3dl, k3d, Sylvester
WebGL CONTEXT
var canvas = document.getElementById("glcanvas");
// Use standard WebGL context or experimental if it's not
available
gl = canvas.getContext("webgl") ||
     canvas.getContext("experimental-webgl");

// Define initial WebGL settings
if (gl) {
    gl.clearColor(0.0, 0.0, 0.0, 1.0);
    gl.enable(gl.DEPTH_TEST);
    gl.depthFunc(gl.LEQUAL);
    gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
}
// It gets more complex from here!
LIBRARIES
•   KineticJS Canvas drawing & animation library
•   Three.JS 3D library
•   Processing.js Port of Processing environment
•   GLGE WebGL library
•   melonJS game engine
•   ImpactJS game engine
PROCESSING.js

• Reads files from Processing programming
  environment
• Uses processing-like code in Javascript
• More flexibility with objects -- collisions,
  mouseover, etc
KINETIC JS

• Dynamically creates a series of canvas
elements as "layers"
• Provides a Stage class and code similar to
Actionscript
• Allow easy object moving, dragging, and
tracking
LEARNING
RESOURCES

BEST LIBRARIES
TUTORIALS
& TOP EXAMPLES
Q&A
THANK YOU!
 Robyn Overstreet & Jovena Whatmoor

More Related Content

What's hot (20)

Bootstrap Part - 1
Bootstrap Part - 1Bootstrap Part - 1
Bootstrap Part - 1
 
Css3
Css3Css3
Css3
 
CSS3 Media Queries
CSS3 Media QueriesCSS3 Media Queries
CSS3 Media Queries
 
Introduction to BOOTSTRAP
Introduction to BOOTSTRAPIntroduction to BOOTSTRAP
Introduction to BOOTSTRAP
 
HTML and CSS crash course!
HTML and CSS crash course!HTML and CSS crash course!
HTML and CSS crash course!
 
CSS
CSSCSS
CSS
 
Intro to HTML and CSS basics
Intro to HTML and CSS basicsIntro to HTML and CSS basics
Intro to HTML and CSS basics
 
Java script
Java scriptJava script
Java script
 
Introduction to HTML5
Introduction to HTML5Introduction to HTML5
Introduction to HTML5
 
Cascading style sheet
Cascading style sheetCascading style sheet
Cascading style sheet
 
HTML5 & CSS3
HTML5 & CSS3 HTML5 & CSS3
HTML5 & CSS3
 
CSS Positioning
CSS PositioningCSS Positioning
CSS Positioning
 
Css selectors
Css selectorsCss selectors
Css selectors
 
Bootstrap 4 ppt
Bootstrap 4 pptBootstrap 4 ppt
Bootstrap 4 ppt
 
jQuery for beginners
jQuery for beginnersjQuery for beginners
jQuery for beginners
 
CSS Basics
CSS BasicsCSS Basics
CSS Basics
 
Bootstrap PPT by Mukesh
Bootstrap PPT by MukeshBootstrap PPT by Mukesh
Bootstrap PPT by Mukesh
 
An introduction to bootstrap
An introduction to bootstrapAn introduction to bootstrap
An introduction to bootstrap
 
Css animation
Css animationCss animation
Css animation
 
Introducing CSS Grid
Introducing CSS GridIntroducing CSS Grid
Introducing CSS Grid
 

Viewers also liked

What REALLY Differentiates The Best Content Marketers From The Rest
What REALLY Differentiates The Best Content Marketers From The RestWhat REALLY Differentiates The Best Content Marketers From The Rest
What REALLY Differentiates The Best Content Marketers From The RestRoss Simmonds
 
20 Tweetable Quotes to Inspire Marketing & Design Creative Genius
20 Tweetable Quotes to Inspire Marketing & Design Creative Genius20 Tweetable Quotes to Inspire Marketing & Design Creative Genius
20 Tweetable Quotes to Inspire Marketing & Design Creative GeniusIMPACT Branding & Design LLC
 
How to Craft Your Company's Storytelling Voice by Ann Handley of MarketingProfs
How to Craft Your Company's Storytelling Voice by Ann Handley of MarketingProfsHow to Craft Your Company's Storytelling Voice by Ann Handley of MarketingProfs
How to Craft Your Company's Storytelling Voice by Ann Handley of MarketingProfsMarketingProfs
 
40 Tools in 20 Minutes: Hacking your Marketing Career
40 Tools in 20 Minutes: Hacking your Marketing Career40 Tools in 20 Minutes: Hacking your Marketing Career
40 Tools in 20 Minutes: Hacking your Marketing CareerEric Leist
 
Creating Powerful Customer Experiences
Creating Powerful Customer ExperiencesCreating Powerful Customer Experiences
Creating Powerful Customer ExperiencesDigital Surgeons
 
Eco-nomics, The hidden costs of consumption
Eco-nomics, The hidden costs of consumptionEco-nomics, The hidden costs of consumption
Eco-nomics, The hidden costs of consumptionJosh Beatty
 
6 Snapchat Hacks Too Easy To Ignore
6 Snapchat Hacks Too Easy To Ignore6 Snapchat Hacks Too Easy To Ignore
6 Snapchat Hacks Too Easy To IgnoreGary Vaynerchuk
 
Digital transformation in 50 soundbites
Digital transformation in 50 soundbitesDigital transformation in 50 soundbites
Digital transformation in 50 soundbitesJulie Dodd
 
All About Beer
All About Beer All About Beer
All About Beer Ethos3
 
Healthcare Napkins All
Healthcare Napkins AllHealthcare Napkins All
Healthcare Napkins AllDan Roam
 
SMOKE - The Convenient Truth [1st place Worlds Best Presentation Contest] by ...
SMOKE - The Convenient Truth [1st place Worlds Best Presentation Contest] by ...SMOKE - The Convenient Truth [1st place Worlds Best Presentation Contest] by ...
SMOKE - The Convenient Truth [1st place Worlds Best Presentation Contest] by ...Empowered Presentations
 
Pixar's 22 Rules to Phenomenal Storytelling
Pixar's 22 Rules to Phenomenal StorytellingPixar's 22 Rules to Phenomenal Storytelling
Pixar's 22 Rules to Phenomenal StorytellingGavin McMahon
 
The Search for Meaning in B2B Marketing
The Search for Meaning in B2B MarketingThe Search for Meaning in B2B Marketing
The Search for Meaning in B2B MarketingVelocity Partners
 
10 Powerful Body Language Tips for your next Presentation
10 Powerful Body Language Tips for your next Presentation10 Powerful Body Language Tips for your next Presentation
10 Powerful Body Language Tips for your next PresentationSOAP Presentations
 

Viewers also liked (19)

What REALLY Differentiates The Best Content Marketers From The Rest
What REALLY Differentiates The Best Content Marketers From The RestWhat REALLY Differentiates The Best Content Marketers From The Rest
What REALLY Differentiates The Best Content Marketers From The Rest
 
20 Tweetable Quotes to Inspire Marketing & Design Creative Genius
20 Tweetable Quotes to Inspire Marketing & Design Creative Genius20 Tweetable Quotes to Inspire Marketing & Design Creative Genius
20 Tweetable Quotes to Inspire Marketing & Design Creative Genius
 
How to Craft Your Company's Storytelling Voice by Ann Handley of MarketingProfs
How to Craft Your Company's Storytelling Voice by Ann Handley of MarketingProfsHow to Craft Your Company's Storytelling Voice by Ann Handley of MarketingProfs
How to Craft Your Company's Storytelling Voice by Ann Handley of MarketingProfs
 
40 Tools in 20 Minutes: Hacking your Marketing Career
40 Tools in 20 Minutes: Hacking your Marketing Career40 Tools in 20 Minutes: Hacking your Marketing Career
40 Tools in 20 Minutes: Hacking your Marketing Career
 
2015 Travel Trends
2015 Travel Trends 2015 Travel Trends
2015 Travel Trends
 
Creating Powerful Customer Experiences
Creating Powerful Customer ExperiencesCreating Powerful Customer Experiences
Creating Powerful Customer Experiences
 
Eco-nomics, The hidden costs of consumption
Eco-nomics, The hidden costs of consumptionEco-nomics, The hidden costs of consumption
Eco-nomics, The hidden costs of consumption
 
Build a Better Entrepreneur Pitch Deck
Build a Better Entrepreneur Pitch DeckBuild a Better Entrepreneur Pitch Deck
Build a Better Entrepreneur Pitch Deck
 
6 Snapchat Hacks Too Easy To Ignore
6 Snapchat Hacks Too Easy To Ignore6 Snapchat Hacks Too Easy To Ignore
6 Snapchat Hacks Too Easy To Ignore
 
Digital transformation in 50 soundbites
Digital transformation in 50 soundbitesDigital transformation in 50 soundbites
Digital transformation in 50 soundbites
 
All About Beer
All About Beer All About Beer
All About Beer
 
Digital, Social & Mobile in 2015
Digital, Social & Mobile in 2015Digital, Social & Mobile in 2015
Digital, Social & Mobile in 2015
 
Healthcare Napkins All
Healthcare Napkins AllHealthcare Napkins All
Healthcare Napkins All
 
SMOKE - The Convenient Truth [1st place Worlds Best Presentation Contest] by ...
SMOKE - The Convenient Truth [1st place Worlds Best Presentation Contest] by ...SMOKE - The Convenient Truth [1st place Worlds Best Presentation Contest] by ...
SMOKE - The Convenient Truth [1st place Worlds Best Presentation Contest] by ...
 
Pixar's 22 Rules to Phenomenal Storytelling
Pixar's 22 Rules to Phenomenal StorytellingPixar's 22 Rules to Phenomenal Storytelling
Pixar's 22 Rules to Phenomenal Storytelling
 
The Search for Meaning in B2B Marketing
The Search for Meaning in B2B MarketingThe Search for Meaning in B2B Marketing
The Search for Meaning in B2B Marketing
 
You Suck At PowerPoint! by @jessedee
You Suck At PowerPoint! by @jessedeeYou Suck At PowerPoint! by @jessedee
You Suck At PowerPoint! by @jessedee
 
How Google Works
How Google WorksHow Google Works
How Google Works
 
10 Powerful Body Language Tips for your next Presentation
10 Powerful Body Language Tips for your next Presentation10 Powerful Body Language Tips for your next Presentation
10 Powerful Body Language Tips for your next Presentation
 

Similar to HTML5 Canvas

Writing a Space Shooter with HTML5 Canvas
Writing a Space Shooter with HTML5 CanvasWriting a Space Shooter with HTML5 Canvas
Writing a Space Shooter with HTML5 CanvasSteve Purkis
 
Rotoscope inthebrowserppt billy
Rotoscope inthebrowserppt billyRotoscope inthebrowserppt billy
Rotoscope inthebrowserppt billynimbleltd
 
HTML5 Canvas - The Future of Graphics on the Web
HTML5 Canvas - The Future of Graphics on the WebHTML5 Canvas - The Future of Graphics on the Web
HTML5 Canvas - The Future of Graphics on the WebRobin Hawkes
 
How to make a video game
How to make a video gameHow to make a video game
How to make a video gamedandylion13
 
How to build a html5 websites.v1
How to build a html5 websites.v1How to build a html5 websites.v1
How to build a html5 websites.v1Bitla Software
 
Exploring Canvas
Exploring CanvasExploring Canvas
Exploring CanvasKevin Hoyt
 
Exploring Canvas
Exploring CanvasExploring Canvas
Exploring CanvasKevin Hoyt
 
Canvas
CanvasCanvas
CanvasRajon
 
Drawing with the HTML5 Canvas
Drawing with the HTML5 CanvasDrawing with the HTML5 Canvas
Drawing with the HTML5 CanvasHenry Osborne
 
Introduction to Canvas - Toronto HTML5 User Group
Introduction to Canvas - Toronto HTML5 User GroupIntroduction to Canvas - Toronto HTML5 User Group
Introduction to Canvas - Toronto HTML5 User Groupdreambreeze
 
Introduction to Canvas - Toronto HTML5 User Group
Introduction to Canvas - Toronto HTML5 User GroupIntroduction to Canvas - Toronto HTML5 User Group
Introduction to Canvas - Toronto HTML5 User Groupbernice-chan
 
Html5 canvas
Html5 canvasHtml5 canvas
Html5 canvasGary Yeh
 
Computer vision Nebraska (Nebraska Code)
Computer vision Nebraska (Nebraska Code)Computer vision Nebraska (Nebraska Code)
Computer vision Nebraska (Nebraska Code)Andrew Rangel
 

Similar to HTML5 Canvas (20)

Writing a Space Shooter with HTML5 Canvas
Writing a Space Shooter with HTML5 CanvasWriting a Space Shooter with HTML5 Canvas
Writing a Space Shooter with HTML5 Canvas
 
Rotoscope inthebrowserppt billy
Rotoscope inthebrowserppt billyRotoscope inthebrowserppt billy
Rotoscope inthebrowserppt billy
 
HTML5 Canvas - The Future of Graphics on the Web
HTML5 Canvas - The Future of Graphics on the WebHTML5 Canvas - The Future of Graphics on the Web
HTML5 Canvas - The Future of Graphics on the Web
 
How to make a video game
How to make a video gameHow to make a video game
How to make a video game
 
How to build a html5 websites.v1
How to build a html5 websites.v1How to build a html5 websites.v1
How to build a html5 websites.v1
 
Css5 canvas
Css5 canvasCss5 canvas
Css5 canvas
 
Exploring Canvas
Exploring CanvasExploring Canvas
Exploring Canvas
 
Exploring Canvas
Exploring CanvasExploring Canvas
Exploring Canvas
 
Intro to HTML5 Canvas
Intro to HTML5 CanvasIntro to HTML5 Canvas
Intro to HTML5 Canvas
 
Yavorsky
YavorskyYavorsky
Yavorsky
 
Canvas
CanvasCanvas
Canvas
 
Drawing with the HTML5 Canvas
Drawing with the HTML5 CanvasDrawing with the HTML5 Canvas
Drawing with the HTML5 Canvas
 
Canvas
CanvasCanvas
Canvas
 
Intro to HTML5
Intro to HTML5Intro to HTML5
Intro to HTML5
 
Html5
Html5Html5
Html5
 
Introduction to Canvas - Toronto HTML5 User Group
Introduction to Canvas - Toronto HTML5 User GroupIntroduction to Canvas - Toronto HTML5 User Group
Introduction to Canvas - Toronto HTML5 User Group
 
Introduction to Canvas - Toronto HTML5 User Group
Introduction to Canvas - Toronto HTML5 User GroupIntroduction to Canvas - Toronto HTML5 User Group
Introduction to Canvas - Toronto HTML5 User Group
 
Intro to Canva
Intro to CanvaIntro to Canva
Intro to Canva
 
Html5 canvas
Html5 canvasHtml5 canvas
Html5 canvas
 
Computer vision Nebraska (Nebraska Code)
Computer vision Nebraska (Nebraska Code)Computer vision Nebraska (Nebraska Code)
Computer vision Nebraska (Nebraska Code)
 

HTML5 Canvas

  • 1. March 19, 2012 7 – 9 PM CLASS WELCOME
  • 3. INTRODUCTION INSTRUCTOR ROBYN OVERSTREET
  • 4. WHAT IS HTML5 CANVAS? • HTML5 element, now part of HTML5 API • Used for drawing and animating directly in HTML, with JavaScript scripting • Originally developed by Apple for Dashboard widgets
  • 5. WHAT CAN IT DO? • Dynamically draw shapes, images and text • Respond to user input – mouse, keyboard, touch, etc. • Animation without Flash • Create interactive charts and graphs
  • 6. CANVAS IN ACTION • Rough GuidesKEXP Archive Sketchpad Wired Mind NYC Restaurant Health Ratings Map
  • 7. BROWSER SUPPORT • Firefox •Chrome •Safari •IE 9 • See CanIUse.com for up-to-date support info
  • 10. SET-UP FOR DRAWING grab the canvas element var mycanvas = document.getElementById("the_canvas"); var context = mycanvas.getContext("2d"); set up a 2D context
  • 11. DRAWING A RECTANGLE context.fillStyle = "rgba(0, 204, 204, 1)"; context.fillRect(40,50,110,70);
  • 12. DRAWING LINES context.beginPath(); //set up to draw a path context.moveTo(x,y); //move to the start position context.lineTo(x,y); //set the end pointcontext.stroke(); //draw the line 3. Draw line between 1. Set start position points 2. Set end position
  • 13. DRAWING CURVES Control point 1 Control point 2 bezierCurveTo(100,25 ... ...400,25... Start point MoveTo(25,125) Destination point ...325,125);
  • 14. CODING CURVES var controlPt1 = {x:110,y:30}; var controlPt2 = {x:130,y:80}; var startPt = {x:75,y:140}; ctx.beginPath(); //prepare path ctx.moveTo(startPt.x,startPt.y); ctx.bezierCurveTo( controlPt1.x,controlPt1.y, controlPt2.x,controlPt2.y, startPt.x,startPt.y ); ctx.stroke();
  • 15. DRAWING ARCS 1.5 * PI Start angle Start angle PI 0 Center point End angle End angle Center point 0.5 * PI
  • 16. DRAWING ARCS & CIRCLES • Circles are types of arcs • Angles are in radians (need to calculate between degrees and radians) ctx.beginPath();ctx.arc(x, y, radius, 0, Math.PI*2, true);ctx.closePath();ctx.fill(); Start angle Start angle End angle End angle
  • 17. TEXT • Text is "drawn" to the canvas context.fillText("Hello world", 10, 50); • Style text in CSS syntax with .font property • Get the dimensions of a text area textObj = ctx.measureText(d); width = textObj.width;
  • 19. TRANSFORMATIONS • To change the orientation of one element on the canvas, you must shift the entire canvas • Translate: move the canvas and its origin to a different point in the grid • Rotate: rotate the canvas around the current origin
  • 20. TRANSLATE CONTEXT Context moved. Context moved. The origin point now The origin point now has a new location. has a new location.
  • 21. TRANSLATE & ROTATE Translate Rotate translate(x, y) rotate(angle)
  • 22. THE STATE STACK State 1Fill Style: redRotation: 45deg State 2 Fill Style: redRotation: 45deg State 1 save() tate 2Fill Style: blackLine Style: blue cale: 50% restore() cale: 50%
  • 23. SAVE & RESTORE ctx.fillRect(0,0,150,150); //Draw with default settings ctx.save(); // Save the default state ctx.fillStyle = '#09F'; //Change the fill color state 1 ctx.fillRect(15,15,120,120); // Draw with new settings ctx.save(); //Save the current state ctx.fillStyle = '#FFF'; //Change fill again ctx.fillRect(15,15,120,120); // Draw with new settings state 2 ctx.restore(); //Restore to last saved state ctx.fillRect(45,45,60,60); //Draw with restored settings back to state 2
  • 25. DRAW IMAGE var img = new Image(); //Create an image objectimg.src = 'dog.png'; //Set source img.onload = function(){ //Wait for the image to load context.drawImage(img,x,y); //Draw image to canvas }
  • 26. REDRAW IMAGE //clear the stage clearRect(0,0,canvas.width,canvas.height); speed = 10; if (previous_x < mouse_x){ direction = 1; //moving left to right } else { direction = -1; //moving right to left } var new_x = previous_x + (speed * direction); context.drawImage(img,new_x,y);
  • 27. IMAGES AT THE PIXEL LEVEL Get image data and loop through pixel by pixel
  • 28. LOOPING THROUGH PIXELS c.drawImage(img,0,0);var imgData = c.getImageData(0,0,canvas.width,canvas.height); for(n=0; n<data.width*data.height; n++) {var index = n*4; //each pixel has 4 data points //rgb values from 0-255 red = imgData.data[index];green = imgData.data[index+1];blue = imgData.data[index+2]; alpha = imgData.data[index+3]; //to reset pixels, change the values in the data array imgData.data[index+2] = 255; //change the blue value } }
  • 30. ANIMATION Canvas doesn't track objects on the screen – You must redraw the stage for each movement Use event listeners or timers
  • 31. FOLLOW THE MOUSE • Draw the image on the canvas • Track the position of the mouse (event listener for every mouse move) • Redraw the image every n seconds based on the x position of the mouse
  • 32. VISUALIZE DATA USE JSON DATA TO CREATE DYNAMIC DRAWINGS CONNECT TO A WEB SERVICE (TWITTER, FOURSQUARE, ETC)
  • 34. MAP DATA TO CANVAS //the data could also come in as a JSON object var data = {jane: 231,julie: 325,ben: 276}; //js object var highest_value = 325; //find programmatically var pixel_units = canvas.height/highest_value; for (user in data){ //loop through data points var bar_height = data[user] * pixel_units; var bar_title = user; } //now it's time to draw!
  • 35. COOL EXAMPLE Each bubble represents a tweet containing the word "water". Popping the bubble displays the tweet.
  • 36. GRAPHING LIBRAIRIES • jQuery VisualizeAwesomeChartJS ... many more • ... many more
  • 37. MOBILE TIPS • Javascript touch events instead of mouse events • PhoneGap Framework to compile to native iOS and Android apps
  • 39. GAMES EXAMPLES • Alex the Alligator http://alex4.tapjs.com • CATcher http://wpsystem.com.br/catcher/ • Catch the goblin http ://www.lostdecadegames.com/how-to-make-a- simple-html5-canvas-game/ • Magician Fairy Rescue http://www.relfind.com/game/magician.html • Canvas Rider, bike game http://canvasrider.com/
  • 43. CODING GOBLINS 1.Draw images for background, player, and goblin 2.Listen for arrow keys and change player coordinates accordingly 3.Detect hit by comparing monster's coordinates to player's coordinates 4.Redraw as frequently as possible
  • 46. 3D • A few options: • Canvas 3D context • Canvas WebGL context • Simulated 3D in 2D context • Libraries ... three.js, c3dl, k3d, Sylvester
  • 47. WebGL CONTEXT var canvas = document.getElementById("glcanvas"); // Use standard WebGL context or experimental if it's not available gl = canvas.getContext("webgl") || canvas.getContext("experimental-webgl"); // Define initial WebGL settings if (gl) { gl.clearColor(0.0, 0.0, 0.0, 1.0); gl.enable(gl.DEPTH_TEST); gl.depthFunc(gl.LEQUAL); gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT); } // It gets more complex from here!
  • 48. LIBRARIES • KineticJS Canvas drawing & animation library • Three.JS 3D library • Processing.js Port of Processing environment • GLGE WebGL library • melonJS game engine • ImpactJS game engine
  • 49. PROCESSING.js • Reads files from Processing programming environment • Uses processing-like code in Javascript • More flexibility with objects -- collisions, mouseover, etc
  • 50. KINETIC JS • Dynamically creates a series of canvas elements as "layers" • Provides a Stage class and code similar to Actionscript • Allow easy object moving, dragging, and tracking
  • 52. Q&A
  • 53. THANK YOU! Robyn Overstreet & Jovena Whatmoor

Editor's Notes

  1. http://www.wired.co.uk/mind http://mugtug.com/sketchpad http://www.nytimes.com/interactive/dining/new-york-hea lth-department-restaurant-ratings-map.html http://kexparchive.org/ http://makethemost.roughguide s.com
  2. 1canvas-base.html
  3. 2canvas-lineclick.html The code example uses a mouse listener
  4. 3canvas-bezier.html
  5. radians = degrees * (pi/180) last parameter (bool) is anticlockwise Circle example in canvas-keyboard.html - also keyboard listener example Circle in: canvas-bounce.html
  6. The foursqare example uses text
  7. build slide?
  8. Translate code is used in canvas-dogrun.html Also in the foursquare example, used to rotate text
  9. canvas-dogrun.html
  10. Dog run example is in code/canvas-img.html
  11. http://hakim.se/experiments/html5/wave/03/
  12. http://webdesigneraid.com/html5-canvas-graphing-solutions-every-web-developers-must-know/ Awesome JS http://cyberpython.github.com/AwesomeChartJS/ jQuery Visualize: http://www.filamentgroup .com/lab/update_to_jquery_visualize_accessibl e_charts_with_html5_from_designing_with/
  13. http://www.lostdecadegames.com/how-to-make-a-simple-html5-canvas-game/
  14. Tutorial: https://developer.mozilla.org/en/WebGL/Getting_started_with_WebGL
  15. cakejs http://code.google.com/p/cakejs/ GLGE WebGL library http://www.glge.org http://www.m elonjs.org/ http:// www.aerotwist.com/tu torials/getting-started -with-three-js/