SlideShare a Scribd company logo
1 of 19
CANVAS
An exciting HTML5 element.
WHAT HTML5 CANVAS IS USED FOR
■ dynamic graphics
■ online and offline games
■ animations
■ interactive video and audio
Easy to turn a plain web page into a dynamic web application and then convert that
application into a mobile app for use on smartphones and tablets.
Skeleton
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<script type="application/javascript">
function draw() {
var canvas = document.getElementById('canvas');
if (canvas.getContext) {
var ctx = canvas.getContext('2d');
//Draw Here }
}else{
//Fall bac kContent Goes Here
}
</script>
</head>
<body>
<canvas id="canvas" width="150" height="150"></canvas> //Create a Canvas
</body>
</html>
Understanding the Canvas Coordinate
System
Curves
var x = canvas.width / 2;
var y = canvas.height / 2;
var radius = 75;
var startAngle = 0 * Math.PI;
var endAngle = 2 * Math.PI;
context.beginPath();
context.arc(x, y, radius, startAngle, endAngle);
context.lineWidth = 15;
// line color
context.strokeStyle = 'green';
context.stroke();
Arc
Curves
context.moveTo(188, 130);
context.bezierCurveTo(140, 10, 388, 10, 388, 170);
context.lineWidth = 10;
Quadratic Curve
context.moveTo(188, 150);
context.quadraticCurveTo(288, 0, 388, 150);
Bezier Curve
Paths
context.moveTo(100, 20);
// line 1
context.lineTo(200, 160);
// quadratic curve
context.quadraticCurveTo(230, 200, 250, 120);
// bezier curve
context.bezierCurveTo(290, -40, 300, 200, 400, 150);
// line 2
context.lineTo(500, 90)
context.lineJoin = 'bevel';
Shape
// begin custom shape
context.beginPath();
context.moveTo(170, 80);
context.bezierCurveTo(130, 100, 130, 150, 230, 150);
context.bezierCurveTo(250, 180, 320, 180, 340, 150);
context.bezierCurveTo(420, 150, 420, 120, 390, 100);
context.bezierCurveTo(430, 40, 370, 30, 340, 50);
context.bezierCurveTo(320, 5, 250, 20, 250, 50);
context.bezierCurveTo(200, 5, 150, 20, 170, 80);
Shape
context.beginPath();
context.rect(188, 50, 200, 100);
context.fillStyle = 'yellow';
context.fill();
context.lineWidth = 7;
context.strokeStyle = 'black';
context.stroke();
Fill Style
context.fillStyle = '#8ED6FF';
context.fill();
Color Fill
// add linear gradient
var grd = context.createLinearGradient(0, 0, canvas.width, canvas.height);
// light blue
grd.addColorStop(0, '#8ED6FF');
// dark blue
grd.addColorStop(1, '#004CB3');
context.fillStyle = grd;
context.fill();
Linear Gradient
Radial Gradient
// create radial gradient
var grd = context.createRadialGradient(238, 50, 10, 238,50, 300);
// light blue
grd.addColorStop(0, '#8ED6FF');
// dark blue
grd.addColorStop(1, '#004CB3');
context.fillStyle = grd;
context.fill();
Pattern
var imageObj = new Image();
imageObj.onload = function() {
var pattern = context.createPattern(imageObj, 'repeat');
context.rect(0, 0, canvas.width, canvas.height);
context.fillStyle = pattern;
context.fill();
};
imageObj.src =
'http://www.html5canvastutorials.com/demos/assets/wood-
pattern.png';
Text
context.textAlign = 'left';
ontext.strokeText('Hello World!', x, y);
Align
Stroke
context.fillStyle = 'blue';
Color
context.font = 'italic 40pt Calibri';
Font Size Style
context.measureText(text);
Metricies
wrapText(context, text, x, y, maxWidth, lineHeight);
WrapText
Transformations
// translate context to center of canvas
context.translate(canvas.width / 2, canvas.height / 2);
// scale y component
context.scale(1, 0.5);
// rotate 45 degrees clockwise
context.rotate(Math.PI / 4);
// apply custom transform
context.transform(1, 0, 0, 1, tx, ty);
// apply custom transform
context.setTransform(1, 0, 0, 1, 0, 0);
Transformation State Stack
context.save();
// save state 1
context.translate(canvas.width / 2, canvas.height / 2);
context.save();
// save state 2
context.rotate(Math.PI / 4);
context.save();
// save state 3
context.scale(2, 2);
context.fillStyle = 'blue';
context.fillRect(rectWidth / -2, rectHeight / -2, rectWidth, rectHeight);
context.restore();
// restore state 1
context.fillStyle = 'green';
context.fillRect(rectWidth / -2, rectHeight / -2, rectWidth, rectHeight);
Composites
//Shadows
context.shadowColor = '#999';
context.shadowBlur = 20;
context.shadowOffsetX = 15;
context.shadowOffsetY = 15;
//Global alpha
context.globalAlpha = 0.5;
//Cliping Region
context.clip();
Animation
animate(myRectangle, canvas, context, startTime);
• Acceleration
• Oscillation
• Linear Motion
• Animation Frame
Lets Look at an example………..
Mouse Position
function writeMessage(canvas, message) {
var context = canvas.getContext('2d');
context.clearRect(0, 0, canvas.width, canvas.height);
context.font = '18pt Calibri';
context.fillStyle = 'black';
context.fillText(message, 10, 25);}
function getMousePos(canvas, evt) {
var rect = canvas.getBoundingClientRect();
return {
x: evt.clientX - rect.left,
y: evt.clientY - rect.top };}
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
canvas.addEventListener('mousemove', function(evt) {
var mousePos = getMousePos(canvas, evt);
var message = 'Mouse position: ' + mousePos.x + ',' + mousePos.y;
writeMessage(canvas, message);
}, false);
Should Check Out
■ http://cheatsheetworld.com/programming/html5-canvas-cheat-sheet/
■ http://www.sinuousgame.com/
■ http://corehtml5canvas.com/code-live/
■ http://curran.github.io/HT
■ http://www.williammalone.com/articles/create-html5-canvas-javascript-game-
character/1/ML5Examples/
■ http://cssdeck.com/labs/ping-pong-game-tutorial-with-html5-canvas-and-sounds

More Related Content

What's hot

JS.Chi CSS Animations
JS.Chi CSS AnimationsJS.Chi CSS Animations
JS.Chi CSS Animations
Justin Meyer
 
Barcamp GoogleMaps - praktické ukázky kódu
Barcamp GoogleMaps - praktické ukázky kóduBarcamp GoogleMaps - praktické ukázky kódu
Barcamp GoogleMaps - praktické ukázky kódu
Milos Lenoch
 
Css sprite_maker-1
Css  sprite_maker-1Css  sprite_maker-1
Css sprite_maker-1
lokku
 
Webgl para JavaScripters
Webgl para JavaScriptersWebgl para JavaScripters
Webgl para JavaScripters
gerbille
 
Auto tools
Auto toolsAuto tools
Auto tools
祺 周
 

What's hot (13)

Build tons of multi-device JavaScript applications - Part 2 : (black) Magic S...
Build tons of multi-device JavaScript applications - Part 2 : (black) Magic S...Build tons of multi-device JavaScript applications - Part 2 : (black) Magic S...
Build tons of multi-device JavaScript applications - Part 2 : (black) Magic S...
 
JS.Chi CSS Animations
JS.Chi CSS AnimationsJS.Chi CSS Animations
JS.Chi CSS Animations
 
Interactive Vector-Graphics in the Browser
Interactive Vector-Graphics in the BrowserInteractive Vector-Graphics in the Browser
Interactive Vector-Graphics in the Browser
 
Mobile Web Development
Mobile Web DevelopmentMobile Web Development
Mobile Web Development
 
Barcamp GoogleMaps - praktické ukázky kódu
Barcamp GoogleMaps - praktické ukázky kóduBarcamp GoogleMaps - praktické ukázky kódu
Barcamp GoogleMaps - praktické ukázky kódu
 
6주 javaScript 시작하며
6주  javaScript 시작하며6주  javaScript 시작하며
6주 javaScript 시작하며
 
Css sprite_maker-1
Css  sprite_maker-1Css  sprite_maker-1
Css sprite_maker-1
 
Webgl para JavaScripters
Webgl para JavaScriptersWebgl para JavaScripters
Webgl para JavaScripters
 
Black-Scholes Calculator on Web
Black-Scholes Calculator on WebBlack-Scholes Calculator on Web
Black-Scholes Calculator on Web
 
Chrome presentation
Chrome presentationChrome presentation
Chrome presentation
 
Render to Texture with Three.js
Render to Texture with Three.jsRender to Texture with Three.js
Render to Texture with Three.js
 
Javascript is your (Auto)mate
Javascript is your (Auto)mateJavascript is your (Auto)mate
Javascript is your (Auto)mate
 
Auto tools
Auto toolsAuto tools
Auto tools
 

Viewers also liked

Viewers also liked (11)

The DATA RING - A canvas for DATA PROJECT
The DATA RING - A canvas for DATA PROJECTThe DATA RING - A canvas for DATA PROJECT
The DATA RING - A canvas for DATA PROJECT
 
Templates: Mapa da Empatia, Canvas da Proposta de Valor, Canvas do Modelo de ...
Templates: Mapa da Empatia, Canvas da Proposta de Valor, Canvas do Modelo de ...Templates: Mapa da Empatia, Canvas da Proposta de Valor, Canvas do Modelo de ...
Templates: Mapa da Empatia, Canvas da Proposta de Valor, Canvas do Modelo de ...
 
Feedback Canvas - Agile Portugal 2017
Feedback Canvas - Agile Portugal 2017Feedback Canvas - Agile Portugal 2017
Feedback Canvas - Agile Portugal 2017
 
Construindo Produtos Inovadores
Construindo Produtos InovadoresConstruindo Produtos Inovadores
Construindo Produtos Inovadores
 
Seminario Business Model Canvas
Seminario Business Model CanvasSeminario Business Model Canvas
Seminario Business Model Canvas
 
Memoria Seminario sobre Canvas Model com Alexander Osterwlader - by Luiz Rolim
Memoria Seminario sobre Canvas Model com Alexander Osterwlader - by Luiz RolimMemoria Seminario sobre Canvas Model com Alexander Osterwlader - by Luiz Rolim
Memoria Seminario sobre Canvas Model com Alexander Osterwlader - by Luiz Rolim
 
Inovação em modelos de negócios já estabelecidos o analista de modelos de n...
Inovação em modelos de negócios já estabelecidos   o analista de modelos de n...Inovação em modelos de negócios já estabelecidos   o analista de modelos de n...
Inovação em modelos de negócios já estabelecidos o analista de modelos de n...
 
Palestra Experiência do Cliente
Palestra Experiência do ClientePalestra Experiência do Cliente
Palestra Experiência do Cliente
 
From Data to Artificial Intelligence with the Machine Learning Canvas — ODSC ...
From Data to Artificial Intelligence with the Machine Learning Canvas — ODSC ...From Data to Artificial Intelligence with the Machine Learning Canvas — ODSC ...
From Data to Artificial Intelligence with the Machine Learning Canvas — ODSC ...
 
Strategic Business Model Canvas v3
Strategic Business Model Canvas v3Strategic Business Model Canvas v3
Strategic Business Model Canvas v3
 
Company Presentation: Canvas
Company Presentation: CanvasCompany Presentation: Canvas
Company Presentation: Canvas
 

Similar to Canvas

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
 
Rotoscope inthebrowserppt billy
Rotoscope inthebrowserppt billyRotoscope inthebrowserppt billy
Rotoscope inthebrowserppt billy
nimbleltd
 
Is HTML5 Ready? (workshop)
Is HTML5 Ready? (workshop)Is HTML5 Ready? (workshop)
Is HTML5 Ready? (workshop)
Remy Sharp
 
Is html5-ready-workshop-110727181512-phpapp02
Is html5-ready-workshop-110727181512-phpapp02Is html5-ready-workshop-110727181512-phpapp02
Is html5-ready-workshop-110727181512-phpapp02
PL dream
 
HTML5 & The Open Web - at Nackademin
HTML5 & The Open Web -  at NackademinHTML5 & The Open Web -  at Nackademin
HTML5 & The Open Web - at Nackademin
Robert Nyman
 

Similar to Canvas (20)

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
 
Drawing with the HTML5 Canvas
Drawing with the HTML5 CanvasDrawing with the HTML5 Canvas
Drawing with the HTML5 Canvas
 
Html5
Html5Html5
Html5
 
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
 
How to make a video game
How to make a video gameHow to make a video game
How to make a video game
 
Exploring Canvas
Exploring CanvasExploring Canvas
Exploring Canvas
 
HTML5 Canvas
HTML5 CanvasHTML5 Canvas
HTML5 Canvas
 
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 -...
 
The Future of CSS with Web components
The Future of CSS with Web componentsThe Future of CSS with Web components
The Future of CSS with Web components
 
The Future of CSS with Web Components
The Future of CSS with Web ComponentsThe Future of CSS with Web Components
The Future of CSS with Web Components
 
Rotoscope inthebrowserppt billy
Rotoscope inthebrowserppt billyRotoscope inthebrowserppt billy
Rotoscope inthebrowserppt billy
 
Intro to HTML5
Intro to HTML5Intro to HTML5
Intro to HTML5
 
Svcc 2013-d3
Svcc 2013-d3Svcc 2013-d3
Svcc 2013-d3
 
SVCC 2013 D3.js Presentation (10/05/2013)
SVCC 2013 D3.js Presentation (10/05/2013)SVCC 2013 D3.js Presentation (10/05/2013)
SVCC 2013 D3.js Presentation (10/05/2013)
 
Is HTML5 Ready? (workshop)
Is HTML5 Ready? (workshop)Is HTML5 Ready? (workshop)
Is HTML5 Ready? (workshop)
 
Is html5-ready-workshop-110727181512-phpapp02
Is html5-ready-workshop-110727181512-phpapp02Is html5-ready-workshop-110727181512-phpapp02
Is html5-ready-workshop-110727181512-phpapp02
 
HTML5 & The Open Web - at Nackademin
HTML5 & The Open Web -  at NackademinHTML5 & The Open Web -  at Nackademin
HTML5 & The Open Web - at Nackademin
 
Html canvas
Html canvasHtml canvas
Html canvas
 
HTML5 for Mobile
HTML5 for MobileHTML5 for Mobile
HTML5 for Mobile
 
Building mobile web apps with Mobello
Building mobile web apps with MobelloBuilding mobile web apps with Mobello
Building mobile web apps with Mobello
 

More from Rajon

Pillar's of Pixel's | Project report
Pillar's of Pixel's | Project reportPillar's of Pixel's | Project report
Pillar's of Pixel's | Project report
Rajon
 

More from Rajon (16)

Chat Application | RSD
Chat Application | RSDChat Application | RSD
Chat Application | RSD
 
AND | OR |XOR | Conditional | Bi-condtional
AND | OR |XOR | Conditional | Bi-condtionalAND | OR |XOR | Conditional | Bi-condtional
AND | OR |XOR | Conditional | Bi-condtional
 
Modern Elicitation Process
Modern Elicitation ProcessModern Elicitation Process
Modern Elicitation Process
 
Numerical Analysis lab 4
Numerical Analysis lab 4Numerical Analysis lab 4
Numerical Analysis lab 4
 
Pillar's of Pixel's | Project report
Pillar's of Pixel's | Project reportPillar's of Pixel's | Project report
Pillar's of Pixel's | Project report
 
Farm Manager | Project Proposal
Farm Manager | Project ProposalFarm Manager | Project Proposal
Farm Manager | Project Proposal
 
Pillar's of Pixel' | Project proposal
Pillar's of Pixel' | Project proposalPillar's of Pixel' | Project proposal
Pillar's of Pixel' | Project proposal
 
Displacement addressing
Displacement addressingDisplacement addressing
Displacement addressing
 
System Design Flow
System Design FlowSystem Design Flow
System Design Flow
 
Backup Photos- Project Proposal
Backup Photos- Project ProposalBackup Photos- Project Proposal
Backup Photos- Project Proposal
 
Chat Application - Requirements Analysis & Design
Chat Application - Requirements Analysis & DesignChat Application - Requirements Analysis & Design
Chat Application - Requirements Analysis & Design
 
Regular expression
Regular expressionRegular expression
Regular expression
 
Chat Application FAQ
Chat Application FAQChat Application FAQ
Chat Application FAQ
 
Presentation On Software Testing Bug Life Cycle
Presentation On Software Testing Bug Life CyclePresentation On Software Testing Bug Life Cycle
Presentation On Software Testing Bug Life Cycle
 
Chat Application [Full Documentation]
Chat Application [Full Documentation]Chat Application [Full Documentation]
Chat Application [Full Documentation]
 
Presentation On Online Airline Ticket Booking Project Planning
Presentation On Online Airline Ticket Booking Project PlanningPresentation On Online Airline Ticket Booking Project Planning
Presentation On Online Airline Ticket Booking Project Planning
 

Recently uploaded

Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 
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
 

Recently uploaded (20)

Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUKSpring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
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
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdf
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 

Canvas

  • 2. WHAT HTML5 CANVAS IS USED FOR ■ dynamic graphics ■ online and offline games ■ animations ■ interactive video and audio Easy to turn a plain web page into a dynamic web application and then convert that application into a mobile app for use on smartphones and tablets.
  • 3. Skeleton <!DOCTYPE html> <html> <head> <meta charset="utf-8"/> <script type="application/javascript"> function draw() { var canvas = document.getElementById('canvas'); if (canvas.getContext) { var ctx = canvas.getContext('2d'); //Draw Here } }else{ //Fall bac kContent Goes Here } </script> </head> <body> <canvas id="canvas" width="150" height="150"></canvas> //Create a Canvas </body> </html>
  • 4. Understanding the Canvas Coordinate System
  • 5. Curves var x = canvas.width / 2; var y = canvas.height / 2; var radius = 75; var startAngle = 0 * Math.PI; var endAngle = 2 * Math.PI; context.beginPath(); context.arc(x, y, radius, startAngle, endAngle); context.lineWidth = 15; // line color context.strokeStyle = 'green'; context.stroke(); Arc
  • 6. Curves context.moveTo(188, 130); context.bezierCurveTo(140, 10, 388, 10, 388, 170); context.lineWidth = 10; Quadratic Curve context.moveTo(188, 150); context.quadraticCurveTo(288, 0, 388, 150); Bezier Curve
  • 7. Paths context.moveTo(100, 20); // line 1 context.lineTo(200, 160); // quadratic curve context.quadraticCurveTo(230, 200, 250, 120); // bezier curve context.bezierCurveTo(290, -40, 300, 200, 400, 150); // line 2 context.lineTo(500, 90) context.lineJoin = 'bevel';
  • 8. Shape // begin custom shape context.beginPath(); context.moveTo(170, 80); context.bezierCurveTo(130, 100, 130, 150, 230, 150); context.bezierCurveTo(250, 180, 320, 180, 340, 150); context.bezierCurveTo(420, 150, 420, 120, 390, 100); context.bezierCurveTo(430, 40, 370, 30, 340, 50); context.bezierCurveTo(320, 5, 250, 20, 250, 50); context.bezierCurveTo(200, 5, 150, 20, 170, 80);
  • 9. Shape context.beginPath(); context.rect(188, 50, 200, 100); context.fillStyle = 'yellow'; context.fill(); context.lineWidth = 7; context.strokeStyle = 'black'; context.stroke();
  • 10. Fill Style context.fillStyle = '#8ED6FF'; context.fill(); Color Fill // add linear gradient var grd = context.createLinearGradient(0, 0, canvas.width, canvas.height); // light blue grd.addColorStop(0, '#8ED6FF'); // dark blue grd.addColorStop(1, '#004CB3'); context.fillStyle = grd; context.fill(); Linear Gradient
  • 11. Radial Gradient // create radial gradient var grd = context.createRadialGradient(238, 50, 10, 238,50, 300); // light blue grd.addColorStop(0, '#8ED6FF'); // dark blue grd.addColorStop(1, '#004CB3'); context.fillStyle = grd; context.fill();
  • 12. Pattern var imageObj = new Image(); imageObj.onload = function() { var pattern = context.createPattern(imageObj, 'repeat'); context.rect(0, 0, canvas.width, canvas.height); context.fillStyle = pattern; context.fill(); }; imageObj.src = 'http://www.html5canvastutorials.com/demos/assets/wood- pattern.png';
  • 13. Text context.textAlign = 'left'; ontext.strokeText('Hello World!', x, y); Align Stroke context.fillStyle = 'blue'; Color context.font = 'italic 40pt Calibri'; Font Size Style context.measureText(text); Metricies wrapText(context, text, x, y, maxWidth, lineHeight); WrapText
  • 14. Transformations // translate context to center of canvas context.translate(canvas.width / 2, canvas.height / 2); // scale y component context.scale(1, 0.5); // rotate 45 degrees clockwise context.rotate(Math.PI / 4); // apply custom transform context.transform(1, 0, 0, 1, tx, ty); // apply custom transform context.setTransform(1, 0, 0, 1, 0, 0);
  • 15. Transformation State Stack context.save(); // save state 1 context.translate(canvas.width / 2, canvas.height / 2); context.save(); // save state 2 context.rotate(Math.PI / 4); context.save(); // save state 3 context.scale(2, 2); context.fillStyle = 'blue'; context.fillRect(rectWidth / -2, rectHeight / -2, rectWidth, rectHeight); context.restore(); // restore state 1 context.fillStyle = 'green'; context.fillRect(rectWidth / -2, rectHeight / -2, rectWidth, rectHeight);
  • 16. Composites //Shadows context.shadowColor = '#999'; context.shadowBlur = 20; context.shadowOffsetX = 15; context.shadowOffsetY = 15; //Global alpha context.globalAlpha = 0.5; //Cliping Region context.clip();
  • 17. Animation animate(myRectangle, canvas, context, startTime); • Acceleration • Oscillation • Linear Motion • Animation Frame Lets Look at an example………..
  • 18. Mouse Position function writeMessage(canvas, message) { var context = canvas.getContext('2d'); context.clearRect(0, 0, canvas.width, canvas.height); context.font = '18pt Calibri'; context.fillStyle = 'black'; context.fillText(message, 10, 25);} function getMousePos(canvas, evt) { var rect = canvas.getBoundingClientRect(); return { x: evt.clientX - rect.left, y: evt.clientY - rect.top };} var canvas = document.getElementById('myCanvas'); var context = canvas.getContext('2d'); canvas.addEventListener('mousemove', function(evt) { var mousePos = getMousePos(canvas, evt); var message = 'Mouse position: ' + mousePos.x + ',' + mousePos.y; writeMessage(canvas, message); }, false);
  • 19. Should Check Out ■ http://cheatsheetworld.com/programming/html5-canvas-cheat-sheet/ ■ http://www.sinuousgame.com/ ■ http://corehtml5canvas.com/code-live/ ■ http://curran.github.io/HT ■ http://www.williammalone.com/articles/create-html5-canvas-javascript-game- character/1/ML5Examples/ ■ http://cssdeck.com/labs/ping-pong-game-tutorial-with-html5-canvas-and-sounds