SlideShare a Scribd company logo
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!
Ad

More Related Content

Similar to Introduction to Canvas - Toronto HTML5 User Group (20)

canvas_1.pptx
canvas_1.pptxcanvas_1.pptx
canvas_1.pptx
RutujRunwal1
 
3D Math Primer: CocoaConf Chicago
3D Math Primer: CocoaConf Chicago3D Math Primer: CocoaConf Chicago
3D Math Primer: CocoaConf Chicago
Janie 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 Primer
Janie Clayton
 
HTML5 Canvas
HTML5 CanvasHTML5 Canvas
HTML5 Canvas
Robyn Overstreet
 
Windows and viewport
Windows and viewportWindows and viewport
Windows and viewport
Technology & Education
 
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
 
2D-Transformations-Transformations are the operations applied to geometrical ...
2D-Transformations-Transformations are the operations applied to geometrical ...2D-Transformations-Transformations are the operations applied to geometrical ...
2D-Transformations-Transformations are the operations applied to geometrical ...
BINJAD1
 
HTML 5_Canvas
HTML 5_CanvasHTML 5_Canvas
HTML 5_Canvas
Vishakha Vaidya
 
SwiftUI Animation - The basic overview
SwiftUI Animation - The basic overviewSwiftUI Animation - The basic overview
SwiftUI Animation - The basic overview
WannitaTolaema
 
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
StanfordComputationalImaging
 
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
Robin Hawkes
 
Lecture 9-online
Lecture 9-onlineLecture 9-online
Lecture 9-online
lifebreath
 
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
Sardar Alam
 
Interactive Graphics
Interactive GraphicsInteractive Graphics
Interactive Graphics
Blazing 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 1b
Philip 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-oyantes
Antoine Robiez
 
Scenes Graphs and Modelling Transformation
Scenes Graphs and Modelling TransformationScenes Graphs and Modelling Transformation
Scenes Graphs and Modelling Transformation
keychelzz
 
Computer graphics
Computer graphicsComputer graphics
Computer graphics
Diksha Trivedi
 
2 transformation computer graphics
2 transformation computer graphics2 transformation computer graphics
2 transformation computer graphics
cairo university
 
Building a Visualization Language
Building a Visualization LanguageBuilding a Visualization Language
Building a Visualization Language
jeresig
 
canvas_1.pptx
canvas_1.pptxcanvas_1.pptx
canvas_1.pptx
RutujRunwal1
 
3D Math Primer: CocoaConf Chicago
3D Math Primer: CocoaConf Chicago3D Math Primer: CocoaConf Chicago
3D Math Primer: CocoaConf Chicago
Janie 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 Primer
Janie 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
 
2D-Transformations-Transformations are the operations applied to geometrical ...
2D-Transformations-Transformations are the operations applied to geometrical ...2D-Transformations-Transformations are the operations applied to geometrical ...
2D-Transformations-Transformations are the operations applied to geometrical ...
BINJAD1
 
SwiftUI Animation - The basic overview
SwiftUI Animation - The basic overviewSwiftUI Animation - The basic overview
SwiftUI Animation - The basic overview
WannitaTolaema
 
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
StanfordComputationalImaging
 
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
Robin Hawkes
 
Lecture 9-online
Lecture 9-onlineLecture 9-online
Lecture 9-online
lifebreath
 
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
Sardar Alam
 
Interactive Graphics
Interactive GraphicsInteractive Graphics
Interactive Graphics
Blazing 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 1b
Philip 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-oyantes
Antoine Robiez
 
Scenes Graphs and Modelling Transformation
Scenes Graphs and Modelling TransformationScenes Graphs and Modelling Transformation
Scenes Graphs and Modelling Transformation
keychelzz
 
Computer graphics
Computer graphicsComputer graphics
Computer graphics
Diksha Trivedi
 
2 transformation computer graphics
2 transformation computer graphics2 transformation computer graphics
2 transformation computer graphics
cairo university
 
Building a Visualization Language
Building a Visualization LanguageBuilding a Visualization Language
Building a Visualization Language
jeresig
 

Recently uploaded (20)

DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptxDevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
Justin Reock
 
IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
organizerofv
 
Special Meetup Edition - TDX Bengaluru Meetup #52.pptx
Special Meetup Edition - TDX Bengaluru Meetup #52.pptxSpecial Meetup Edition - TDX Bengaluru Meetup #52.pptx
Special Meetup Edition - TDX Bengaluru Meetup #52.pptx
shyamraj55
 
Cyber Awareness overview for 2025 month of security
Cyber Awareness overview for 2025 month of securityCyber Awareness overview for 2025 month of security
Cyber Awareness overview for 2025 month of security
riccardosl1
 
Electronic_Mail_Attacks-1-35.pdf by xploit
Electronic_Mail_Attacks-1-35.pdf by xploitElectronic_Mail_Attacks-1-35.pdf by xploit
Electronic_Mail_Attacks-1-35.pdf by xploit
niftliyevhuseyn
 
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdfThe Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
Abi john
 
Mobile App Development Company in Saudi Arabia
Mobile App Development Company in Saudi ArabiaMobile App Development Company in Saudi Arabia
Mobile App Development Company in Saudi Arabia
Steve Jonas
 
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-UmgebungenHCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
panagenda
 
TrsLabs - Fintech Product & Business Consulting
TrsLabs - Fintech Product & Business ConsultingTrsLabs - Fintech Product & Business Consulting
TrsLabs - Fintech Product & Business Consulting
Trs Labs
 
Big Data Analytics Quick Research Guide by Arthur Morgan
Big Data Analytics Quick Research Guide by Arthur MorganBig Data Analytics Quick Research Guide by Arthur Morgan
Big Data Analytics Quick Research Guide by Arthur Morgan
Arthur Morgan
 
Greenhouse_Monitoring_Presentation.pptx.
Greenhouse_Monitoring_Presentation.pptx.Greenhouse_Monitoring_Presentation.pptx.
Greenhouse_Monitoring_Presentation.pptx.
hpbmnnxrvb
 
Increasing Retail Store Efficiency How can Planograms Save Time and Money.pptx
Increasing Retail Store Efficiency How can Planograms Save Time and Money.pptxIncreasing Retail Store Efficiency How can Planograms Save Time and Money.pptx
Increasing Retail Store Efficiency How can Planograms Save Time and Money.pptx
Anoop Ashok
 
Role of Data Annotation Services in AI-Powered Manufacturing
Role of Data Annotation Services in AI-Powered ManufacturingRole of Data Annotation Services in AI-Powered Manufacturing
Role of Data Annotation Services in AI-Powered Manufacturing
Andrew Leo
 
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep DiveDesigning Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
ScyllaDB
 
Linux Professional Institute LPIC-1 Exam.pdf
Linux Professional Institute LPIC-1 Exam.pdfLinux Professional Institute LPIC-1 Exam.pdf
Linux Professional Institute LPIC-1 Exam.pdf
RHCSA Guru
 
How analogue intelligence complements AI
How analogue intelligence complements AIHow analogue intelligence complements AI
How analogue intelligence complements AI
Paul Rowe
 
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager APIUiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPathCommunity
 
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdfSAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
Precisely
 
Dev Dives: Automate and orchestrate your processes with UiPath Maestro
Dev Dives: Automate and orchestrate your processes with UiPath MaestroDev Dives: Automate and orchestrate your processes with UiPath Maestro
Dev Dives: Automate and orchestrate your processes with UiPath Maestro
UiPathCommunity
 
Semantic Cultivators : The Critical Future Role to Enable AI
Semantic Cultivators : The Critical Future Role to Enable AISemantic Cultivators : The Critical Future Role to Enable AI
Semantic Cultivators : The Critical Future Role to Enable AI
artmondano
 
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptxDevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
Justin Reock
 
IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
organizerofv
 
Special Meetup Edition - TDX Bengaluru Meetup #52.pptx
Special Meetup Edition - TDX Bengaluru Meetup #52.pptxSpecial Meetup Edition - TDX Bengaluru Meetup #52.pptx
Special Meetup Edition - TDX Bengaluru Meetup #52.pptx
shyamraj55
 
Cyber Awareness overview for 2025 month of security
Cyber Awareness overview for 2025 month of securityCyber Awareness overview for 2025 month of security
Cyber Awareness overview for 2025 month of security
riccardosl1
 
Electronic_Mail_Attacks-1-35.pdf by xploit
Electronic_Mail_Attacks-1-35.pdf by xploitElectronic_Mail_Attacks-1-35.pdf by xploit
Electronic_Mail_Attacks-1-35.pdf by xploit
niftliyevhuseyn
 
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdfThe Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
Abi john
 
Mobile App Development Company in Saudi Arabia
Mobile App Development Company in Saudi ArabiaMobile App Development Company in Saudi Arabia
Mobile App Development Company in Saudi Arabia
Steve Jonas
 
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-UmgebungenHCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
panagenda
 
TrsLabs - Fintech Product & Business Consulting
TrsLabs - Fintech Product & Business ConsultingTrsLabs - Fintech Product & Business Consulting
TrsLabs - Fintech Product & Business Consulting
Trs Labs
 
Big Data Analytics Quick Research Guide by Arthur Morgan
Big Data Analytics Quick Research Guide by Arthur MorganBig Data Analytics Quick Research Guide by Arthur Morgan
Big Data Analytics Quick Research Guide by Arthur Morgan
Arthur Morgan
 
Greenhouse_Monitoring_Presentation.pptx.
Greenhouse_Monitoring_Presentation.pptx.Greenhouse_Monitoring_Presentation.pptx.
Greenhouse_Monitoring_Presentation.pptx.
hpbmnnxrvb
 
Increasing Retail Store Efficiency How can Planograms Save Time and Money.pptx
Increasing Retail Store Efficiency How can Planograms Save Time and Money.pptxIncreasing Retail Store Efficiency How can Planograms Save Time and Money.pptx
Increasing Retail Store Efficiency How can Planograms Save Time and Money.pptx
Anoop Ashok
 
Role of Data Annotation Services in AI-Powered Manufacturing
Role of Data Annotation Services in AI-Powered ManufacturingRole of Data Annotation Services in AI-Powered Manufacturing
Role of Data Annotation Services in AI-Powered Manufacturing
Andrew Leo
 
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep DiveDesigning Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
ScyllaDB
 
Linux Professional Institute LPIC-1 Exam.pdf
Linux Professional Institute LPIC-1 Exam.pdfLinux Professional Institute LPIC-1 Exam.pdf
Linux Professional Institute LPIC-1 Exam.pdf
RHCSA Guru
 
How analogue intelligence complements AI
How analogue intelligence complements AIHow analogue intelligence complements AI
How analogue intelligence complements AI
Paul Rowe
 
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager APIUiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPathCommunity
 
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdfSAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
Precisely
 
Dev Dives: Automate and orchestrate your processes with UiPath Maestro
Dev Dives: Automate and orchestrate your processes with UiPath MaestroDev Dives: Automate and orchestrate your processes with UiPath Maestro
Dev Dives: Automate and orchestrate your processes with UiPath Maestro
UiPathCommunity
 
Semantic Cultivators : The Critical Future Role to Enable AI
Semantic Cultivators : The Critical Future Role to Enable AISemantic Cultivators : The Critical Future Role to Enable AI
Semantic Cultivators : The Critical Future Role to Enable AI
artmondano
 
Ad

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.

Editor's Notes

  • #9: Current paths and bitmaps
 useful for animation of individual objects and path manipulations