SlideShare uma empresa Scribd logo
1 de 52
A blank slate to draw graphs, game graphics, video, or
other visual images on the fly.”
• 2D drawing tool within all modern browsers
• No downloads (plugins) required!
• Openly developed by the WC3 (WWW consortium)
Introduced by Apple, as
part of WebKit in 2004, to
show the power of
desktop apps within their
Safari browser.
Now a standard!
<canvas id=“myCanvas" width="150" height="150"></canvas>
• Only 2 attributes: Width & Height
• Default values for width and height: 300px x 150px
Older browsers may not support the <canvas>
element
Therefore, we insert fallback text, just in case it won’t
display
<canvas id=“myChart" width="150" height="150">
Current version of IE: 11
</canvas>
var canvas = document.getElementById('tutorial');
if (canvas.getContext){
var ctx = canvas.getContext('2d');
// drawing code here
} else {
// canvas-unsupported code here:
Hey, you need to update your browser!
}
The canvas is a two-dimensional grid.
The coordinate (0, 0) is at the upper-
left corner of the canvas.
Along the X-axis, values increase from
left to right.
Along the Y-axis, values increase from
top to bottom.
var canvas = document.getElementById(‘myCanvas');
var ctx = canvas.getContext('2d');
var canvas = document.getElementById(“myCanvas");
var ctx = canvas.getContext("2d");
ctx.fillRect(50, 25, 150, 100);
Parameters:
X: The x-coordinate of the upper-left corner of the rectangle
Y The y-coordinate of the upper-left corner of the rectangle
Width: The width of the rectangle, in pixels
Height: The height of the rectangle, in pixels
•fillStyle: can be a CSS color, a pattern, or a gradient. (Default color is black)
•strokeStyle: like fillStyle, but used for lines
•fillRect( x, y, width, height) draws a rectangle filled with the current fill style.
•strokeRect(x, y, width, height) draws an rectangle w/ current stroke style. Only draws edges.
•clearRect( x, y, width, height) clears the pixels in the specified rectangle.
<canvas id="myCanvas" width=“300" height="150"></canvas>
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
ctx.fillStyle = "red";
ctx.fillRect (0, 0, 300, 150);
ctx.clearRect(20, 20, 100, 50);
<canvas id="myCanvas" width=200 height=120></canvas>
var canvas = document.getElementById('myCanvas');
var ctxt = canvas.getContext('2d');
ctx.fillStyle = '#000000'; // set color to black
ctx.fillRect(0, 0, 200, 40); // draw (200x40 pixel) rectangle at (0,0
ctx.fillStyle = '#FF0000'; // set color to red
ctx.fillRect(0, 40, 200, 40); // draw (200x40 pixel) rectangle at (0,40)
ctx.fillStyle = '#FFCC00'; // set color to gold
ctx.fillRect(0, 80, 200, 40); // draw (200x40 pixel) rectangle at (0,80)
• Scale(): Scales the current drawing, bigger or smaller
• Rotate(): Rotates current drawing
• Translate(): Moves the (0,0) position on the canvas
• Transform(): Replaces current transform matrix for current drawing
• setTransform(): Resets current transform matrix to the identity matrix, then runs
transform()
<canvas id="myCanvas" width="300" height="200"></canvas>
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
ctx.rotate(20 * Math.PI / 180);
ctx.fillRect(50, 20, 100, 50);
Save & Restore context
Save & Restore context (cont’d)
To calculate from degrees to radians: degrees * Math.PI/180
<canvas id="myCanvas" width=“300" height=“300"></canvas>
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
ctx.strokeRect(5, 5, 100, 30); // draw first rectangle
ctx.scale(2,2); // 2x width, 2x height
ctx.strokeRect(5, 5, 100, 30); // draw second triangle
http://www.w3schools.com/tags/playcanvas.asp?filename=playcanvas_transformb&preval=1,0,0,1,0,0
A – Scales the drawing horizontally
B – Skew the drawing horizontally
C- Skew the drawing vertically
D - Scale the drawing vertically
E – Moves the drawing horizontally
F – Moves the drawing vertically
<canvas id="myCanvas" width=“300" height=“300"></canvas>
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
ctx.fillRect (10, 10, 100, 50);
ctx.translate(70, 70);
ctx.fillRect (10, 10, 100, 50);
Three steps are required:
1. Begin the path – beginPath()
2. Move the points – moveTo() or lineTo()
3. Stroke (outline) / Fill the path – stroke() or fill()
4. *Close the path – closePath()
*Note: When you call fill(), any open shapes are closed automatically, so you
don’t need to call closePath(). This is not true when you use stroke(), though.
Moves the “pencil” to the x, y coordinates
Doesn’t draw anything, but becomes part of the path
Think of it as lifting a pencil, then places it at this spot
Drags the “pencil” to the x, y coordinates
var canvas = document.getElementById(‘myCanvas');
if (canvas.getContext){
var ctx = canvas.getContext('2d');
ctx.beginPath(); // starts drawing
ctx.moveTo(75,50); // First point (left)
ctx.lineTo(100,75); // Bottom point
ctx.lineTo(100,25); // Top point
ctx.fill(); // black is default
}
Unlike text on a webpage, there is no box model, so CSS layout
techniques are not available, such as:
- float, margin, padding, word wrap
Available attributes:
• font (style, font variant, weight, size, line height, family)
• textAlign (start, end, left, right, center)
• TextBaseline (top, hanging, middle, alphabetic, ideographic, bottom)
<canvas id=“myCanvas" width=“150” height=“100”></canvas>
var canvas = document.getElementById ('myCanvas'); // access the canvas object
var ctx = canvas.getContext ('2d'); // access the canvas context
ctx.fillRect (5,5,140,50); // fill rectangle with black color
ctx.fillStyle = 'red'; // set text color to 'red'
ctx.font = '40pt Arial'; // define the CSS font for writing text
ctx.fillText ('Text',1 0,50); // write the text 'Text‘
var canvas =document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
var grd = ctx.createLinearGradient(0,0,170,0);
grd.addColorStop(0,"black");
grd.addColorStop(1,"white");
ctx.fillStyle=grd;
ctx.fillRect(0,0,150,100);
Smooth transition between two colors
CSS Gradients
Canvas gradients aren’t widely used
Instead, most developers prefer
#grad
{
background: -webkit-linear-gradient(left, white, black); /* For Safari 5.1 to 6.0 */
background: -o-linear-gradient(right, white, black); /* For Opera 11.1 to 12.0 */
background: -moz-linear-gradient(right white, black); /* For Firefox 3.6 to 15 */
background: linear-gradient(to right, white, black); /* Standard syntax */
}
Impact.js
Turbulenz
Paper.js
Canvas.js
Processing.js
EaselJS
HTML5 Canvas Tutorials
Link to HTML5 cheat sheet
Advanced html5 diving into the canvas tag
Advanced html5 diving into the canvas tag
Advanced html5 diving into the canvas tag
Advanced html5 diving into the canvas tag

Mais conteúdo relacionado

Mais procurados

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
Bitla Software
 
Interactive Graphics
Interactive GraphicsInteractive Graphics
Interactive Graphics
Blazing Cloud
 
Using jQuery to Extend CSS
Using jQuery to Extend CSSUsing jQuery to Extend CSS
Using jQuery to Extend CSS
Chris Coyier
 

Mais procurados (20)

Html5 canvas
Html5 canvasHtml5 canvas
Html5 canvas
 
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
 
Svg
SvgSvg
Svg
 
Css5 canvas
Css5 canvasCss5 canvas
Css5 canvas
 
I Can't Believe It's Not Flash
I Can't Believe It's Not FlashI Can't Believe It's Not Flash
I Can't Believe It's Not Flash
 
Stupid Canvas Tricks
Stupid Canvas TricksStupid Canvas Tricks
Stupid Canvas Tricks
 
SenchaCon 2016: Improve Workflow Driven Applications with Ext JS Draw Package...
SenchaCon 2016: Improve Workflow Driven Applications with Ext JS Draw Package...SenchaCon 2016: Improve Workflow Driven Applications with Ext JS Draw Package...
SenchaCon 2016: Improve Workflow Driven Applications with Ext JS Draw Package...
 
Work shop css3
Work shop css3Work shop css3
Work shop css3
 
Massimo Artizzu - The tricks of Houdini: a magic wand for the future of CSS -...
Massimo Artizzu - The tricks of Houdini: a magic wand for the future of CSS -...Massimo Artizzu - The tricks of Houdini: a magic wand for the future of CSS -...
Massimo Artizzu - The tricks of Houdini: a magic wand for the future of CSS -...
 
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
 
Mastering CSS Animations
Mastering CSS AnimationsMastering CSS Animations
Mastering CSS Animations
 
Canvas
CanvasCanvas
Canvas
 
CSS Animations & Transitions
CSS Animations & TransitionsCSS Animations & Transitions
CSS Animations & Transitions
 
Exploring Canvas
Exploring CanvasExploring Canvas
Exploring Canvas
 
Joan Leon | Houdini, programando en CSS | Codemotion Madrid 2018
Joan Leon | Houdini, programando en CSS | Codemotion Madrid 2018Joan Leon | Houdini, programando en CSS | Codemotion Madrid 2018
Joan Leon | Houdini, programando en CSS | Codemotion Madrid 2018
 
Ember.js Tokyo event 2014/09/22 (English)
Ember.js Tokyo event 2014/09/22 (English)Ember.js Tokyo event 2014/09/22 (English)
Ember.js Tokyo event 2014/09/22 (English)
 
Interactive Graphics
Interactive GraphicsInteractive Graphics
Interactive Graphics
 
SVG overview
SVG overviewSVG overview
SVG overview
 
CDAT - graphics - vcs - xmgrace - Introduction
CDAT - graphics - vcs - xmgrace - Introduction CDAT - graphics - vcs - xmgrace - Introduction
CDAT - graphics - vcs - xmgrace - Introduction
 
Using jQuery to Extend CSS
Using jQuery to Extend CSSUsing jQuery to Extend CSS
Using jQuery to Extend CSS
 

Semelhante a Advanced html5 diving into the canvas tag

An Impromptu Introduction to HTML5 Canvas
An Impromptu Introduction to HTML5 CanvasAn Impromptu Introduction to HTML5 Canvas
An Impromptu Introduction to HTML5 Canvas
Ben Hodgson
 
5 tips for your HTML5 games
5 tips for your HTML5 games5 tips for your HTML5 games
5 tips for your HTML5 games
Ernesto Jiménez
 
Exploring Canvas
Exploring CanvasExploring Canvas
Exploring Canvas
Kevin Hoyt
 
Rotoscope inthebrowserppt billy
Rotoscope inthebrowserppt billyRotoscope inthebrowserppt billy
Rotoscope inthebrowserppt billy
nimbleltd
 

Semelhante a Advanced html5 diving into the canvas tag (20)

How to make a video game
How to make a video gameHow to make a video game
How to make a video game
 
SVG vs Canvas - Showdown of the Painters
SVG vs Canvas - Showdown of the PaintersSVG vs Canvas - Showdown of the Painters
SVG vs Canvas - Showdown of the Painters
 
Html5 canvas
Html5 canvasHtml5 canvas
Html5 canvas
 
HTML5 Canvas - Basics.pptx
HTML5 Canvas - Basics.pptxHTML5 Canvas - Basics.pptx
HTML5 Canvas - Basics.pptx
 
Canvas
CanvasCanvas
Canvas
 
Plunge into HTML5 Canvas – Let’s begin
Plunge into HTML5 Canvas – Let’s beginPlunge into HTML5 Canvas – Let’s begin
Plunge into HTML5 Canvas – Let’s begin
 
Html canvas
Html canvasHtml canvas
Html canvas
 
HTML Canvas tips & tricks - Lightning Talk by Roman Rodych
 HTML Canvas tips & tricks - Lightning Talk by Roman Rodych HTML Canvas tips & tricks - Lightning Talk by Roman Rodych
HTML Canvas tips & tricks - Lightning Talk by Roman Rodych
 
An Impromptu Introduction to HTML5 Canvas
An Impromptu Introduction to HTML5 CanvasAn Impromptu Introduction to HTML5 Canvas
An Impromptu Introduction to HTML5 Canvas
 
Drawing a Circle Three Ways: Generating Graphics for the Web
Drawing a Circle Three Ways: Generating Graphics for the WebDrawing a Circle Three Ways: Generating Graphics for the Web
Drawing a Circle Three Ways: Generating Graphics for the Web
 
Javascript #10 : canvas
Javascript #10 : canvasJavascript #10 : canvas
Javascript #10 : canvas
 
5 tips for your HTML5 games
5 tips for your HTML5 games5 tips for your HTML5 games
5 tips for your HTML5 games
 
An introduction to the create js suite
An introduction to the create js suiteAn introduction to the create js suite
An introduction to the create js suite
 
IE9에서 HTML5 개발하기
IE9에서 HTML5 개발하기IE9에서 HTML5 개발하기
IE9에서 HTML5 개발하기
 
CANVAS, SVG, WebGL, CSS3, WebEvent
CANVAS, SVG, WebGL, CSS3, WebEventCANVAS, SVG, WebGL, CSS3, WebEvent
CANVAS, SVG, WebGL, CSS3, WebEvent
 
Exploring Canvas
Exploring CanvasExploring Canvas
Exploring Canvas
 
Rotoscope inthebrowserppt billy
Rotoscope inthebrowserppt billyRotoscope inthebrowserppt billy
Rotoscope inthebrowserppt billy
 
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
 
Canvas examples
Canvas examplesCanvas examples
Canvas examples
 
Professional reports with SVG
Professional reports with SVGProfessional reports with SVG
Professional reports with SVG
 

Mais de David Voyles

Build and deploy an ASP.NET applicaton
Build and deploy an ASP.NET applicatonBuild and deploy an ASP.NET applicaton
Build and deploy an ASP.NET applicaton
David Voyles
 
Cluster puck99 postmortem
Cluster puck99 postmortemCluster puck99 postmortem
Cluster puck99 postmortem
David Voyles
 
Joe Healy - Students as App Publishers
Joe Healy - Students as App PublishersJoe Healy - Students as App Publishers
Joe Healy - Students as App Publishers
David Voyles
 

Mais de David Voyles (20)

Developing games for consoles as an indie in 2019
Developing games for consoles as an indie in 2019Developing games for consoles as an indie in 2019
Developing games for consoles as an indie in 2019
 
Developing for consoles as an indie in 2019
Developing for consoles as an indie in 2019Developing for consoles as an indie in 2019
Developing for consoles as an indie in 2019
 
Overview Microsoft's ML & AI tools
Overview Microsoft's ML & AI toolsOverview Microsoft's ML & AI tools
Overview Microsoft's ML & AI tools
 
Intro to deep learning
Intro to deep learning Intro to deep learning
Intro to deep learning
 
What is a Tech Evangelist?
What is a Tech Evangelist?What is a Tech Evangelist?
What is a Tech Evangelist?
 
Microsoft on open source and security
Microsoft on open source and securityMicrosoft on open source and security
Microsoft on open source and security
 
Students: How to get started in the tech world
Students: How to get started in the tech worldStudents: How to get started in the tech world
Students: How to get started in the tech world
 
Students -- How to get started in the tech world
Students -- How to get started in the tech worldStudents -- How to get started in the tech world
Students -- How to get started in the tech world
 
Getting started with Emscripten – Transpiling C / C++ to JavaScript / HTML5
Getting started with Emscripten – Transpiling C / C++ to JavaScript / HTML5Getting started with Emscripten – Transpiling C / C++ to JavaScript / HTML5
Getting started with Emscripten – Transpiling C / C++ to JavaScript / HTML5
 
How to win a hackathon - Penn APps 2015
How to win a hackathon - Penn APps 2015How to win a hackathon - Penn APps 2015
How to win a hackathon - Penn APps 2015
 
ASP.NET 5
ASP.NET 5ASP.NET 5
ASP.NET 5
 
Running, improving & maintaining a site in the real world
Running, improving & maintaining a site in the real worldRunning, improving & maintaining a site in the real world
Running, improving & maintaining a site in the real world
 
Building web front ends using single page applications
Building web front ends using single page applicationsBuilding web front ends using single page applications
Building web front ends using single page applications
 
Web standards and Visual Studio web tools
Web standards and Visual Studio web toolsWeb standards and Visual Studio web tools
Web standards and Visual Studio web tools
 
Build and deploy an ASP.NET applicaton
Build and deploy an ASP.NET applicatonBuild and deploy an ASP.NET applicaton
Build and deploy an ASP.NET applicaton
 
Cluster puck99 postmortem
Cluster puck99 postmortemCluster puck99 postmortem
Cluster puck99 postmortem
 
Joe Healy - How to set up your DreamSpark account
Joe Healy - How to set up your DreamSpark accountJoe Healy - How to set up your DreamSpark account
Joe Healy - How to set up your DreamSpark account
 
Joe Healy - Students as App Publishers
Joe Healy - Students as App PublishersJoe Healy - Students as App Publishers
Joe Healy - Students as App Publishers
 
Using prime[31] to connect your unity game to azure mobile services
Using prime[31] to connect your unity game to azure mobile servicesUsing prime[31] to connect your unity game to azure mobile services
Using prime[31] to connect your unity game to azure mobile services
 
An Introdouction to Venture Capital and Microsoft Ventures
An Introdouction to Venture Capital and Microsoft VenturesAn Introdouction to Venture Capital and Microsoft Ventures
An Introdouction to Venture Capital and Microsoft Ventures
 

Último

Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 

Último (20)

Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 

Advanced html5 diving into the canvas tag

  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7. A blank slate to draw graphs, game graphics, video, or other visual images on the fly.”
  • 8. • 2D drawing tool within all modern browsers • No downloads (plugins) required! • Openly developed by the WC3 (WWW consortium)
  • 9. Introduced by Apple, as part of WebKit in 2004, to show the power of desktop apps within their Safari browser. Now a standard!
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16. <canvas id=“myCanvas" width="150" height="150"></canvas> • Only 2 attributes: Width & Height • Default values for width and height: 300px x 150px
  • 17. Older browsers may not support the <canvas> element Therefore, we insert fallback text, just in case it won’t display <canvas id=“myChart" width="150" height="150"> Current version of IE: 11 </canvas>
  • 18. var canvas = document.getElementById('tutorial'); if (canvas.getContext){ var ctx = canvas.getContext('2d'); // drawing code here } else { // canvas-unsupported code here: Hey, you need to update your browser! }
  • 19. The canvas is a two-dimensional grid. The coordinate (0, 0) is at the upper- left corner of the canvas. Along the X-axis, values increase from left to right. Along the Y-axis, values increase from top to bottom.
  • 20. var canvas = document.getElementById(‘myCanvas'); var ctx = canvas.getContext('2d');
  • 21.
  • 22. var canvas = document.getElementById(“myCanvas"); var ctx = canvas.getContext("2d"); ctx.fillRect(50, 25, 150, 100); Parameters: X: The x-coordinate of the upper-left corner of the rectangle Y The y-coordinate of the upper-left corner of the rectangle Width: The width of the rectangle, in pixels Height: The height of the rectangle, in pixels
  • 23.
  • 24. •fillStyle: can be a CSS color, a pattern, or a gradient. (Default color is black) •strokeStyle: like fillStyle, but used for lines •fillRect( x, y, width, height) draws a rectangle filled with the current fill style. •strokeRect(x, y, width, height) draws an rectangle w/ current stroke style. Only draws edges. •clearRect( x, y, width, height) clears the pixels in the specified rectangle.
  • 25. <canvas id="myCanvas" width=“300" height="150"></canvas> var canvas = document.getElementById("myCanvas"); var ctx = canvas.getContext("2d"); ctx.fillStyle = "red"; ctx.fillRect (0, 0, 300, 150); ctx.clearRect(20, 20, 100, 50);
  • 26. <canvas id="myCanvas" width=200 height=120></canvas> var canvas = document.getElementById('myCanvas'); var ctxt = canvas.getContext('2d'); ctx.fillStyle = '#000000'; // set color to black ctx.fillRect(0, 0, 200, 40); // draw (200x40 pixel) rectangle at (0,0 ctx.fillStyle = '#FF0000'; // set color to red ctx.fillRect(0, 40, 200, 40); // draw (200x40 pixel) rectangle at (0,40) ctx.fillStyle = '#FFCC00'; // set color to gold ctx.fillRect(0, 80, 200, 40); // draw (200x40 pixel) rectangle at (0,80)
  • 27.
  • 28. • Scale(): Scales the current drawing, bigger or smaller • Rotate(): Rotates current drawing • Translate(): Moves the (0,0) position on the canvas • Transform(): Replaces current transform matrix for current drawing • setTransform(): Resets current transform matrix to the identity matrix, then runs transform()
  • 29.
  • 30. <canvas id="myCanvas" width="300" height="200"></canvas> var canvas = document.getElementById("myCanvas"); var ctx = canvas.getContext("2d"); ctx.rotate(20 * Math.PI / 180); ctx.fillRect(50, 20, 100, 50); Save & Restore context Save & Restore context (cont’d) To calculate from degrees to radians: degrees * Math.PI/180
  • 31. <canvas id="myCanvas" width=“300" height=“300"></canvas> var canvas = document.getElementById("myCanvas"); var ctx = canvas.getContext("2d"); ctx.strokeRect(5, 5, 100, 30); // draw first rectangle ctx.scale(2,2); // 2x width, 2x height ctx.strokeRect(5, 5, 100, 30); // draw second triangle
  • 32. http://www.w3schools.com/tags/playcanvas.asp?filename=playcanvas_transformb&preval=1,0,0,1,0,0 A – Scales the drawing horizontally B – Skew the drawing horizontally C- Skew the drawing vertically D - Scale the drawing vertically E – Moves the drawing horizontally F – Moves the drawing vertically
  • 33. <canvas id="myCanvas" width=“300" height=“300"></canvas> var canvas = document.getElementById("myCanvas"); var ctx = canvas.getContext("2d"); ctx.fillRect (10, 10, 100, 50); ctx.translate(70, 70); ctx.fillRect (10, 10, 100, 50);
  • 34.
  • 35. Three steps are required: 1. Begin the path – beginPath() 2. Move the points – moveTo() or lineTo() 3. Stroke (outline) / Fill the path – stroke() or fill() 4. *Close the path – closePath() *Note: When you call fill(), any open shapes are closed automatically, so you don’t need to call closePath(). This is not true when you use stroke(), though.
  • 36. Moves the “pencil” to the x, y coordinates Doesn’t draw anything, but becomes part of the path Think of it as lifting a pencil, then places it at this spot
  • 37. Drags the “pencil” to the x, y coordinates
  • 38. var canvas = document.getElementById(‘myCanvas'); if (canvas.getContext){ var ctx = canvas.getContext('2d'); ctx.beginPath(); // starts drawing ctx.moveTo(75,50); // First point (left) ctx.lineTo(100,75); // Bottom point ctx.lineTo(100,25); // Top point ctx.fill(); // black is default }
  • 39.
  • 40. Unlike text on a webpage, there is no box model, so CSS layout techniques are not available, such as: - float, margin, padding, word wrap Available attributes: • font (style, font variant, weight, size, line height, family) • textAlign (start, end, left, right, center) • TextBaseline (top, hanging, middle, alphabetic, ideographic, bottom)
  • 41. <canvas id=“myCanvas" width=“150” height=“100”></canvas> var canvas = document.getElementById ('myCanvas'); // access the canvas object var ctx = canvas.getContext ('2d'); // access the canvas context ctx.fillRect (5,5,140,50); // fill rectangle with black color ctx.fillStyle = 'red'; // set text color to 'red' ctx.font = '40pt Arial'; // define the CSS font for writing text ctx.fillText ('Text',1 0,50); // write the text 'Text‘
  • 42.
  • 43. var canvas =document.getElementById("myCanvas"); var ctx = canvas.getContext("2d"); var grd = ctx.createLinearGradient(0,0,170,0); grd.addColorStop(0,"black"); grd.addColorStop(1,"white"); ctx.fillStyle=grd; ctx.fillRect(0,0,150,100); Smooth transition between two colors
  • 44. CSS Gradients Canvas gradients aren’t widely used Instead, most developers prefer
  • 45. #grad { background: -webkit-linear-gradient(left, white, black); /* For Safari 5.1 to 6.0 */ background: -o-linear-gradient(right, white, black); /* For Opera 11.1 to 12.0 */ background: -moz-linear-gradient(right white, black); /* For Firefox 3.6 to 15 */ background: linear-gradient(to right, white, black); /* Standard syntax */ }
  • 46.
  • 48. Link to HTML5 cheat sheet

Notas do Editor

  1. You can have more than one <canvas> element on the same page. Each canvas will show up in the DOM, and each canvas maintains its own state. If you give each canvas an id attribute, you can access them just like any other element.
  2. Scripts can also check for support programatically by simply testing for the presence of the getContext() method.
  3. Default color is black
  4. The first line retrieves the DOM node for the <canvas> element by calling the document.getElementById() method. Once you have the element node, you can access the drawing context using its getContext() method.
  5. Visual Studio https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Canvas_tutorial/Basic_usage
  6. Default color is black http://jsfiddle.net/
  7. Default color is black
  8. http://jsfiddle.net/