SlideShare ist ein Scribd-Unternehmen logo
1 von 18
HTML5 Canvas Exploring
On the Menu…
1. Introducing HTML5 Canvas
2. Drawing on the Canvas
3. Simple Compositing
4. Canvas Transformations
5. Sprite Animations
6. Rocket Science
Understanding HTML5 Canvas
Immediate Mode
Canvas is an IMMEDIATE MODE bitmapped area of browser screen that can
be manipulated by you through JavaScript.
   › Canvas completely redraws bitmapped screen on every frame using Canvas API
   › Flash, Silverlight, SVG use retained mode

2D Context
The Canvas API includes a 2D context allowing you to draw shapes, render
text, and display images onto the defined area of browser screen.
   › The 2D context is a display API used to render the Canvas graphics
   › The JavaScript applied to this API allows for keyboard and mouse inputs, timer
      intervals, events, objects, classes, sounds… etc
Understanding HTML5 Canvas
Canvas Effects
Transformations are applied to the canvas (with exceptions)
Objects can be drawn onto the surface discretely, but once on the
canvas, they are a single collection of pixels in a single space
Result:
       There is then only one object on the Canvas: the context
The DOM cannot access individual graphical elements created on Canvas

Browser Support
Dummy Canvas Creation – by Mark Pilgrim (http://diveintohtml5.org)
function canvasSupport () {
    return !!document.createElement('testcanvas').getContext;
}

function canvasApp() {
     if (!canvasSupport) {
           return;
     }
}
Simple Objects
Basic objects can be placed on the canvas in three ways:
› FillRect(posX, posY, width, height);
     › Draws a filled rectangle
›   StrokeRect(posX, posY, width, height);
     › Draws a rectangle outline
›   ClearRect(posX, posY, width, height);
     › Clears the specified area making it fully transparent
Utilizing Style functions:
› fillStyle
     › Takes a hexidecimal colour code
›   strokeStyle
     › Takes a hexidecimal colour code

Text
› fillText( message, posX, posY)
     › Takes a hexidecimal colour code
›   strokeStyle
     › Takes a hexidecimal colour code
Simple Lines
Paths can be used to draw any shape on Canvas
› Paths are simply lists of points for lines to be drawn in-between

Path drawing
› beginPath()
      › Function call to start a path
›   moveTo(posX, posY)
      › Defines a point at position (x, y)
›   lineTo(posX, posY)
      › Creates a subpath between current point and position (x, y)
›   stroke()
      › Draws the line (stroke) on the path
›   closePath()
      › Function call to end a path
Simple Lines
Utilizing Style functions:
› strokeStyle
      › Takes a hexadecimal colour code
›   lineWidth
      › Defines width of line to be drawn
›   lineJoin
      › Bevel, Round, Miter (default – edge drawn at the join)
›   lineCap
      › Butt, Round, Square

Arcs and curves can be drawn on the canvas in four ways
                          An arc can be a circle or any part of a circle

› arc(posX, posY, radius, startAngle, endAngle, anticlockwise)
     › Draws a line with given variables (angles are in radians)
›   arcTo(x1, y1, x2, y2, radius)
     › Draws a straight line to x1, y1, then an arc to x2, y2 with the radius
Clipping
Clipping allows masking of Canvas areas so anything drawn only appears in
clipped areas

› Save() and Restore()
    › Drawing on the Canvas makes use of a stack of drawing “states”
    › A state stores Canvas data of elements drawn
        › Transformations and clipping regions use data stored in states

    › Save()
        › Pushes the current state to the stack
    › Restore()
        › Restores the last state saved from the stack to the Canvas

    › Note: current paths and current bitmaps are not part of saved states
Compositing
Compositing is the control of transparency and layering of objects. This is
controlled by globalAlpha and globalCompositeOperation

› globalAlpha
    › Defaults to 1 (completely opaque)
    › Set before an object is drawn to Canvas

› globalCompositeOperation
    › copy
         › Where overlap, display source
    ›   destination-atop
         › Where overlap, display destination over source, transparent elsewhere
    ›   destination-in
         › Where overlap, show destination in the source, transparent elsewhere
    ›   destination-out
         › Where overlap, show destination if opaque and source transparent, transparent elsewhere
    ›   destination-over
         › Where overlap, show destination over source, source elsewhere
Canvas Rotations
Reference:
An object is said to be at 0 angle rotation when it is facing to the left.

Rotating the canvas steps:
› Set the current Canvas transformation to the “identity” matrix
      › context.setTransform(1,0,0,1,0,0);
›    Convert rotation angle to radians:
      › Canvas uses radians to specify its transformations.
›    Only objects drawn AFTER context.rotate() are affected
      › Canvas uses radians to specify its transformations.
›    In the absence of a defined origin for rotation

       Transformations are applied to shapes and paths drawn after the
    setTransform() and rotate() or other transformation function is called.
Canvas Rotations
The point of origin to the center of our shape must be translated to rotate it
                            around its own center

› What about rotating about the origin?
    › Change the origin of the canvas to be the centre of the square
    › context.translate(x+.5*width, y+.5*height);
    › Draw the object starting with the correct upper-left coordinates
    › context.fillRect(-.5*width,-.5*height , width, height);
Images on Canvas
Reference:
Canvas Image API can load in image data and apply directly to canvas
Image data can be cut and sized to desired portions


› Image object can be defined through HTML
    › <img src=“zelda.png” id=“zelda”>
› Or Javascript
    › var zelda = new Image();
    › zelda.src = “zelda.png”;
› Displaying an image
    › drawImage(image, posX, poxY);
    › drawImage(image, posX, posY, scaleW, scaleH);
    › drawImage(image, sourceX, sourceY, sourceW, sourceH, posX, posY, scaleW, scaleH);
HTML Sprite Animation
› Creating a Tile Sheet
   › One method of displaying multiple images in succession for an
     animation is to use a images in a grid and flip between each “tile”

   › Create an animation array to hold the tiles
   › The 2-dimensional array begins at 0
   › Store the tile IDs to make Zelda walk and
     an index to track which tile is displayed
var animationFrames = [0,1,2,3,4];
   › Calculate X to give us an integer using the
     remainder of the current tile divided by
     the number of tiles in the animation
sourceX = integer(current_frame_index modulo
the_number_columns_in_the_tilesheet) * tile_width
HTML Sprite Animation
› Creating a Tile Sheet
  › Calculate Y to give us an integer using the result of the current tile
      divided by the number of tiles in the animation
  sourceY = integer(current_frame_index divided by
  columns_in_the_tilesheet) *tile_height


› Creating a Timer Loop
  › A simple loop to call the move function once every 150 milliseconds
  function startLoop() {
      var intervalID = setInterval(moveZeldaRight, 150);
  }

› Changing the Image
  ›    To change the image being displayed, we have to set the
       current frame index to the desired tile
HTML Sprite Animation
› Changing the Image
  ›    Loop through the tiles accesses all frames in the animation and draw
       each tile with each iteration
  frameIndex++;
  if (frameIndex == animationFrames.length) {
      frameIndex = 0;
  }

› Moving the Image
  › Set the dx and dy variables during drawing to increase at every
      iteration
  context.drawImage(zelda, sourceX, sourceY+60,30,30,x,y,30,30);
Rocket Science
› Rocket will rotate when left and right arrows are pressed
› Rocket will accelerate when player presses up
› Animations are about creating intervals and updating
    graphics on Canvas for each frame
›   Transformations to Canvas to allow the rocket to rotate
    1. Save current state to stack
    2. Transform rocket
    3. Restore saved state
›       Variables in question:
    ›      Rotation
    ›      Position X
    ›      Position Y
Rocket Science
› Rocket can face one direction and move in a different
  direction
› Get rotation value based on key presses
   › Determine X and Y of rocket direction for throttle using
     Math.cos and Math.sin
› Get acceleration value based on up key press
   › Use acceleration and direction to increase speed in X and Y
     directions
 facingX = Math.cos(angleInRadians);
 movingX = movingX + thrustAcceleration * facingX;
› Control the rocket with the keyboard
› Respond appropriately with acceleration or rotation
  per key press.
Thank you!

Weitere ähnliche Inhalte

Andere mochten auch

uGUIのRectTransformをさわってみた
uGUIのRectTransformをさわってみたuGUIのRectTransformをさわってみた
uGUIのRectTransformをさわってみたKeizo Nagamine
 
Designing Teams for Emerging Challenges
Designing Teams for Emerging ChallengesDesigning Teams for Emerging Challenges
Designing Teams for Emerging ChallengesAaron Irizarry
 
UX, ethnography and possibilities: for Libraries, Museums and Archives
UX, ethnography and possibilities: for Libraries, Museums and ArchivesUX, ethnography and possibilities: for Libraries, Museums and Archives
UX, ethnography and possibilities: for Libraries, Museums and ArchivesNed Potter
 
Visual Design with Data
Visual Design with DataVisual Design with Data
Visual Design with DataSeth Familian
 
3 Things Every Sales Team Needs to Be Thinking About in 2017
3 Things Every Sales Team Needs to Be Thinking About in 20173 Things Every Sales Team Needs to Be Thinking About in 2017
3 Things Every Sales Team Needs to Be Thinking About in 2017Drift
 
How to Become a Thought Leader in Your Niche
How to Become a Thought Leader in Your NicheHow to Become a Thought Leader in Your Niche
How to Become a Thought Leader in Your NicheLeslie Samuel
 

Andere mochten auch (6)

uGUIのRectTransformをさわってみた
uGUIのRectTransformをさわってみたuGUIのRectTransformをさわってみた
uGUIのRectTransformをさわってみた
 
Designing Teams for Emerging Challenges
Designing Teams for Emerging ChallengesDesigning Teams for Emerging Challenges
Designing Teams for Emerging Challenges
 
UX, ethnography and possibilities: for Libraries, Museums and Archives
UX, ethnography and possibilities: for Libraries, Museums and ArchivesUX, ethnography and possibilities: for Libraries, Museums and Archives
UX, ethnography and possibilities: for Libraries, Museums and Archives
 
Visual Design with Data
Visual Design with DataVisual Design with Data
Visual Design with Data
 
3 Things Every Sales Team Needs to Be Thinking About in 2017
3 Things Every Sales Team Needs to Be Thinking About in 20173 Things Every Sales Team Needs to Be Thinking About in 2017
3 Things Every Sales Team Needs to Be Thinking About in 2017
 
How to Become a Thought Leader in Your Niche
How to Become a Thought Leader in Your NicheHow to Become a Thought Leader in Your Niche
How to Become a Thought Leader in Your Niche
 

Ähnlich wie Introduction to Canvas - Toronto HTML5 User Group

3D Math Primer: CocoaConf Chicago
3D Math Primer: CocoaConf Chicago3D Math Primer: CocoaConf Chicago
3D Math Primer: CocoaConf ChicagoJanie Clayton
 
The Day You Finally Use Algebra: A 3D Math Primer
The Day You Finally Use Algebra: A 3D Math PrimerThe Day You Finally Use Algebra: A 3D Math Primer
The Day You Finally Use Algebra: A 3D Math PrimerJanie Clayton
 
Computer Graphics - Lecture 03 - Virtual Cameras and the Transformation Pipeline
Computer Graphics - Lecture 03 - Virtual Cameras and the Transformation PipelineComputer Graphics - Lecture 03 - Virtual Cameras and the Transformation Pipeline
Computer Graphics - Lecture 03 - Virtual Cameras and the Transformation Pipeline💻 Anton Gerdelan
 
SwiftUI Animation - The basic overview
SwiftUI Animation - The basic overviewSwiftUI Animation - The basic overview
SwiftUI Animation - The basic overviewWannitaTolaema
 
Build Your Own VR Display Course - SIGGRAPH 2017: Part 2
Build Your Own VR Display Course - SIGGRAPH 2017: Part 2Build Your Own VR Display Course - SIGGRAPH 2017: Part 2
Build Your Own VR Display Course - SIGGRAPH 2017: Part 2StanfordComputationalImaging
 
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
 
Lecture 9-online
Lecture 9-onlineLecture 9-online
Lecture 9-onlinelifebreath
 
3 d graphics with opengl part 1
3 d graphics with opengl part 13 d graphics with opengl part 1
3 d graphics with opengl part 1Sardar Alam
 
Interactive Graphics
Interactive GraphicsInteractive Graphics
Interactive GraphicsBlazing Cloud
 
Computer Graphics in Java and Scala - Part 1b
Computer Graphics in Java and Scala - Part 1bComputer Graphics in Java and Scala - Part 1b
Computer Graphics in Java and Scala - Part 1bPhilip Schwarz
 
Animations avec Compose : rendez vos apps chat-oyantes
Animations avec Compose : rendez vos apps chat-oyantesAnimations avec Compose : rendez vos apps chat-oyantes
Animations avec Compose : rendez vos apps chat-oyantesAntoine Robiez
 
2 transformation computer graphics
2 transformation computer graphics2 transformation computer graphics
2 transformation computer graphicscairo university
 
Building a Visualization Language
Building a Visualization LanguageBuilding a Visualization Language
Building a Visualization Languagejeresig
 
Trident International Graphics Workshop 2014 4/5
Trident International Graphics Workshop 2014 4/5Trident International Graphics Workshop 2014 4/5
Trident International Graphics Workshop 2014 4/5Takao Wada
 

Ähnlich wie Introduction to Canvas - Toronto HTML5 User Group (20)

canvas_1.pptx
canvas_1.pptxcanvas_1.pptx
canvas_1.pptx
 
3D Math Primer: CocoaConf Chicago
3D Math Primer: CocoaConf Chicago3D Math Primer: CocoaConf Chicago
3D Math Primer: CocoaConf Chicago
 
The Day You Finally Use Algebra: A 3D Math Primer
The Day You Finally Use Algebra: A 3D Math PrimerThe Day You Finally Use Algebra: A 3D Math Primer
The Day You Finally Use Algebra: A 3D Math Primer
 
HTML5 Canvas
HTML5 CanvasHTML5 Canvas
HTML5 Canvas
 
Windows and viewport
Windows and viewportWindows and viewport
Windows and viewport
 
Computer Graphics - Lecture 03 - Virtual Cameras and the Transformation Pipeline
Computer Graphics - Lecture 03 - Virtual Cameras and the Transformation PipelineComputer Graphics - Lecture 03 - Virtual Cameras and the Transformation Pipeline
Computer Graphics - Lecture 03 - Virtual Cameras and the Transformation Pipeline
 
HTML 5_Canvas
HTML 5_CanvasHTML 5_Canvas
HTML 5_Canvas
 
SwiftUI Animation - The basic overview
SwiftUI Animation - The basic overviewSwiftUI Animation - The basic overview
SwiftUI Animation - The basic overview
 
Build Your Own VR Display Course - SIGGRAPH 2017: Part 2
Build Your Own VR Display Course - SIGGRAPH 2017: Part 2Build Your Own VR Display Course - SIGGRAPH 2017: Part 2
Build Your Own VR Display Course - SIGGRAPH 2017: Part 2
 
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
 
Lecture 9-online
Lecture 9-onlineLecture 9-online
Lecture 9-online
 
3 d graphics with opengl part 1
3 d graphics with opengl part 13 d graphics with opengl part 1
3 d graphics with opengl part 1
 
Interactive Graphics
Interactive GraphicsInteractive Graphics
Interactive Graphics
 
Computer Graphics in Java and Scala - Part 1b
Computer Graphics in Java and Scala - Part 1bComputer Graphics in Java and Scala - Part 1b
Computer Graphics in Java and Scala - Part 1b
 
Animations avec Compose : rendez vos apps chat-oyantes
Animations avec Compose : rendez vos apps chat-oyantesAnimations avec Compose : rendez vos apps chat-oyantes
Animations avec Compose : rendez vos apps chat-oyantes
 
Computer graphics
Computer graphicsComputer graphics
Computer graphics
 
2 transformation computer graphics
2 transformation computer graphics2 transformation computer graphics
2 transformation computer graphics
 
Building a Visualization Language
Building a Visualization LanguageBuilding a Visualization Language
Building a Visualization Language
 
Trident International Graphics Workshop 2014 4/5
Trident International Graphics Workshop 2014 4/5Trident International Graphics Workshop 2014 4/5
Trident International Graphics Workshop 2014 4/5
 
2D Transformation
2D Transformation2D Transformation
2D Transformation
 

Kürzlich hochgeladen

Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Hiroshi SHIBATA
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsNathaniel Shimoni
 
UiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPathCommunity
 
Scale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterScale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterMydbops
 
Top 10 Hubspot Development Companies in 2024
Top 10 Hubspot Development Companies in 2024Top 10 Hubspot Development Companies in 2024
Top 10 Hubspot Development Companies in 2024TopCSSGallery
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 
Glenn Lazarus- Why Your Observability Strategy Needs Security Observability
Glenn Lazarus- Why Your Observability Strategy Needs Security ObservabilityGlenn Lazarus- Why Your Observability Strategy Needs Security Observability
Glenn Lazarus- Why Your Observability Strategy Needs Security Observabilityitnewsafrica
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
Decarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityDecarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityIES VE
 
Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Farhan Tariq
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfLoriGlavin3
 
Testing tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesTesting tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesKari Kakkonen
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 
QCon London: Mastering long-running processes in modern architectures
QCon London: Mastering long-running processes in modern architecturesQCon London: Mastering long-running processes in modern architectures
QCon London: Mastering long-running processes in modern architecturesBernd Ruecker
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxLoriGlavin3
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxLoriGlavin3
 
Bridging Between CAD & GIS: 6 Ways to Automate Your Data Integration
Bridging Between CAD & GIS:  6 Ways to Automate Your Data IntegrationBridging Between CAD & GIS:  6 Ways to Automate Your Data Integration
Bridging Between CAD & GIS: 6 Ways to Automate Your Data Integrationmarketing932765
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxLoriGlavin3
 
Generative AI - Gitex v1Generative AI - Gitex v1.pptx
Generative AI - Gitex v1Generative AI - Gitex v1.pptxGenerative AI - Gitex v1Generative AI - Gitex v1.pptx
Generative AI - Gitex v1Generative AI - Gitex v1.pptxfnnc6jmgwh
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity PlanDatabarracks
 

Kürzlich hochgeladen (20)

Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directions
 
UiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to Hero
 
Scale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterScale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL Router
 
Top 10 Hubspot Development Companies in 2024
Top 10 Hubspot Development Companies in 2024Top 10 Hubspot Development Companies in 2024
Top 10 Hubspot Development Companies in 2024
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 
Glenn Lazarus- Why Your Observability Strategy Needs Security Observability
Glenn Lazarus- Why Your Observability Strategy Needs Security ObservabilityGlenn Lazarus- Why Your Observability Strategy Needs Security Observability
Glenn Lazarus- Why Your Observability Strategy Needs Security Observability
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
Decarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityDecarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a reality
 
Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdf
 
Testing tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesTesting tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examples
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 
QCon London: Mastering long-running processes in modern architectures
QCon London: Mastering long-running processes in modern architecturesQCon London: Mastering long-running processes in modern architectures
QCon London: Mastering long-running processes in modern architectures
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptx
 
Bridging Between CAD & GIS: 6 Ways to Automate Your Data Integration
Bridging Between CAD & GIS:  6 Ways to Automate Your Data IntegrationBridging Between CAD & GIS:  6 Ways to Automate Your Data Integration
Bridging Between CAD & GIS: 6 Ways to Automate Your Data Integration
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
 
Generative AI - Gitex v1Generative AI - Gitex v1.pptx
Generative AI - Gitex v1Generative AI - Gitex v1.pptxGenerative AI - Gitex v1Generative AI - Gitex v1.pptx
Generative AI - Gitex v1Generative AI - Gitex v1.pptx
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity Plan
 

Introduction to Canvas - Toronto HTML5 User Group

  • 2. On the Menu… 1. Introducing HTML5 Canvas 2. Drawing on the Canvas 3. Simple Compositing 4. Canvas Transformations 5. Sprite Animations 6. Rocket Science
  • 3. Understanding HTML5 Canvas Immediate Mode Canvas is an IMMEDIATE MODE bitmapped area of browser screen that can be manipulated by you through JavaScript. › Canvas completely redraws bitmapped screen on every frame using Canvas API › Flash, Silverlight, SVG use retained mode 2D Context The Canvas API includes a 2D context allowing you to draw shapes, render text, and display images onto the defined area of browser screen. › The 2D context is a display API used to render the Canvas graphics › The JavaScript applied to this API allows for keyboard and mouse inputs, timer intervals, events, objects, classes, sounds… etc
  • 4. Understanding HTML5 Canvas Canvas Effects Transformations are applied to the canvas (with exceptions) Objects can be drawn onto the surface discretely, but once on the canvas, they are a single collection of pixels in a single space Result: There is then only one object on the Canvas: the context The DOM cannot access individual graphical elements created on Canvas Browser Support Dummy Canvas Creation – by Mark Pilgrim (http://diveintohtml5.org) function canvasSupport () { return !!document.createElement('testcanvas').getContext; } function canvasApp() { if (!canvasSupport) { return; } }
  • 5. Simple Objects Basic objects can be placed on the canvas in three ways: › FillRect(posX, posY, width, height); › Draws a filled rectangle › StrokeRect(posX, posY, width, height); › Draws a rectangle outline › ClearRect(posX, posY, width, height); › Clears the specified area making it fully transparent Utilizing Style functions: › fillStyle › Takes a hexidecimal colour code › strokeStyle › Takes a hexidecimal colour code Text › fillText( message, posX, posY) › Takes a hexidecimal colour code › strokeStyle › Takes a hexidecimal colour code
  • 6. Simple Lines Paths can be used to draw any shape on Canvas › Paths are simply lists of points for lines to be drawn in-between Path drawing › beginPath() › Function call to start a path › moveTo(posX, posY) › Defines a point at position (x, y) › lineTo(posX, posY) › Creates a subpath between current point and position (x, y) › stroke() › Draws the line (stroke) on the path › closePath() › Function call to end a path
  • 7. Simple Lines Utilizing Style functions: › strokeStyle › Takes a hexadecimal colour code › lineWidth › Defines width of line to be drawn › lineJoin › Bevel, Round, Miter (default – edge drawn at the join) › lineCap › Butt, Round, Square Arcs and curves can be drawn on the canvas in four ways An arc can be a circle or any part of a circle › arc(posX, posY, radius, startAngle, endAngle, anticlockwise) › Draws a line with given variables (angles are in radians) › arcTo(x1, y1, x2, y2, radius) › Draws a straight line to x1, y1, then an arc to x2, y2 with the radius
  • 8. Clipping Clipping allows masking of Canvas areas so anything drawn only appears in clipped areas › Save() and Restore() › Drawing on the Canvas makes use of a stack of drawing “states” › A state stores Canvas data of elements drawn › Transformations and clipping regions use data stored in states › Save() › Pushes the current state to the stack › Restore() › Restores the last state saved from the stack to the Canvas › Note: current paths and current bitmaps are not part of saved states
  • 9. Compositing Compositing is the control of transparency and layering of objects. This is controlled by globalAlpha and globalCompositeOperation › globalAlpha › Defaults to 1 (completely opaque) › Set before an object is drawn to Canvas › globalCompositeOperation › copy › Where overlap, display source › destination-atop › Where overlap, display destination over source, transparent elsewhere › destination-in › Where overlap, show destination in the source, transparent elsewhere › destination-out › Where overlap, show destination if opaque and source transparent, transparent elsewhere › destination-over › Where overlap, show destination over source, source elsewhere
  • 10. Canvas Rotations Reference: An object is said to be at 0 angle rotation when it is facing to the left. Rotating the canvas steps: › Set the current Canvas transformation to the “identity” matrix › context.setTransform(1,0,0,1,0,0); › Convert rotation angle to radians: › Canvas uses radians to specify its transformations. › Only objects drawn AFTER context.rotate() are affected › Canvas uses radians to specify its transformations. › In the absence of a defined origin for rotation Transformations are applied to shapes and paths drawn after the setTransform() and rotate() or other transformation function is called.
  • 11. Canvas Rotations The point of origin to the center of our shape must be translated to rotate it around its own center › What about rotating about the origin? › Change the origin of the canvas to be the centre of the square › context.translate(x+.5*width, y+.5*height); › Draw the object starting with the correct upper-left coordinates › context.fillRect(-.5*width,-.5*height , width, height);
  • 12. Images on Canvas Reference: Canvas Image API can load in image data and apply directly to canvas Image data can be cut and sized to desired portions › Image object can be defined through HTML › <img src=“zelda.png” id=“zelda”> › Or Javascript › var zelda = new Image(); › zelda.src = “zelda.png”; › Displaying an image › drawImage(image, posX, poxY); › drawImage(image, posX, posY, scaleW, scaleH); › drawImage(image, sourceX, sourceY, sourceW, sourceH, posX, posY, scaleW, scaleH);
  • 13. HTML Sprite Animation › Creating a Tile Sheet › One method of displaying multiple images in succession for an animation is to use a images in a grid and flip between each “tile” › Create an animation array to hold the tiles › The 2-dimensional array begins at 0 › Store the tile IDs to make Zelda walk and an index to track which tile is displayed var animationFrames = [0,1,2,3,4]; › Calculate X to give us an integer using the remainder of the current tile divided by the number of tiles in the animation sourceX = integer(current_frame_index modulo the_number_columns_in_the_tilesheet) * tile_width
  • 14. HTML Sprite Animation › Creating a Tile Sheet › Calculate Y to give us an integer using the result of the current tile divided by the number of tiles in the animation sourceY = integer(current_frame_index divided by columns_in_the_tilesheet) *tile_height › Creating a Timer Loop › A simple loop to call the move function once every 150 milliseconds function startLoop() { var intervalID = setInterval(moveZeldaRight, 150); } › Changing the Image › To change the image being displayed, we have to set the current frame index to the desired tile
  • 15. HTML Sprite Animation › Changing the Image › Loop through the tiles accesses all frames in the animation and draw each tile with each iteration frameIndex++; if (frameIndex == animationFrames.length) { frameIndex = 0; } › Moving the Image › Set the dx and dy variables during drawing to increase at every iteration context.drawImage(zelda, sourceX, sourceY+60,30,30,x,y,30,30);
  • 16. Rocket Science › Rocket will rotate when left and right arrows are pressed › Rocket will accelerate when player presses up › Animations are about creating intervals and updating graphics on Canvas for each frame › Transformations to Canvas to allow the rocket to rotate 1. Save current state to stack 2. Transform rocket 3. Restore saved state › Variables in question: › Rotation › Position X › Position Y
  • 17. Rocket Science › Rocket can face one direction and move in a different direction › Get rotation value based on key presses › Determine X and Y of rocket direction for throttle using Math.cos and Math.sin › Get acceleration value based on up key press › Use acceleration and direction to increase speed in X and Y directions facingX = Math.cos(angleInRadians); movingX = movingX + thrustAcceleration * facingX; › Control the rocket with the keyboard › Respond appropriately with acceleration or rotation per key press.

Hinweis der Redaktion

  1. Current paths and bitmaps… useful for animation of individual objects and path manipulations