SlideShare une entreprise Scribd logo
1  sur  16
Télécharger pour lire hors ligne
HTML 5
Canvas
 Basic usage
 Drawing shapes
 Using images
 Applying styles and colors
 Transformations
 Compositing
 Basic animations
 Optimizing the canvas
supported in Firefox 1.5 and later, Opera 9 and later, newer
versions of Safari, Chrome, and Internet Explorer 9.
<canvas id="tutorial" width="150" height="150"></canvas>
This looks a lot like the <img> element, the only difference is that it doesn't have
the src and alt attributes. The <canvas> element has only two attributes -
width andheight. These are both optional and can also be set
using DOM properties. When no width and height attributes are specified, the
canvas will initially be 300 pixelswide and 150 pixels high.
Fallback content
<canvas id="stockGraph" width="150" height="150">
current stock price: $3.15 +0.15
</canvas>
<canvas id="clock" width="150" height="150">
<img src="images/clock.png" width="150" height="150" alt=""/>
</canvas>
The rendering context
 2D rendering context.
 3D context
 ("experimental-webgl") based on OpenGL ES.
var canvas = document.getElementById('tutorial');
var ctx = canvas.getContext('2d');
Checking for support
var canvas = document.getElementById('tutorial');
if (canvas.getContext){
var ctx = canvas.getContext('2d');
// drawing code here
} else {
// canvas-unsupported code here
}
A skeleton template
<html>
<head>
<title>Canvas tutorial</title>
<script type="text/javascript">
function draw(){
var canvas = document.getElementById('tutorial');
if (canvas.getContext){
var ctx = canvas.getContext('2d');
}
}
</script>
<style type="text/css">
canvas { border: 1px solid black; }
</style>
</head>
<body onload="draw();">
<canvas id="tutorial" width="150" height="150"></canvas>
</body>
</html>
Drawing shapes
 The grid Top left is 0,0
 canvas only supports one primitive shape - rectangles. All other shapes must be created by
combining one or more paths
 fillRect(x,y,width,height) : Draws a filled rectangle
strokeRect(x,y,width,height) : Draws a rectangular outline
clearRect(x,y,width,height) : Clears the specified area and makes it fully transparent
 Drawing paths
beginPath()
closePath()
stroke()
fill()
moveTo(x, y)
lineTo(x, y)
arc(x, y, radius, startAngle, endAngle, anticlockwise)
 Bezier and quadratic curves
quadraticCurveTo(cp1x, cp1y, x, y)
bezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y)
 Rectangles
rect(x, y, width, height)
Using images
 Importing images
 Importing images is basically a two step process:
 Firstly we need a reference to a JavaScript Image object or other
canvas element as a source. It isn't possible to use images by
simply providing a URL/path to them.
 Secondly we draw the image on the canvas using
the drawImage function.
 drawImage
 drawImage(image, x, y, width, height)
 var img = new Image(); // Create new img element
 img.src = 'myImage.png'; // Set source path
 Slicing
 drawImage(image, sx, sy, sWidth, sHeight, dx, dy, dWidth,
dHeight)
function draw() {
var ctx = document.getElementById('canvas').getContext('2d')
;
var img = new Image();
img.onload = function(){
ctx.drawImage(img,0,0);
ctx.beginPath();
ctx.moveTo(30,96);
ctx.lineTo(70,66);
ctx.lineTo(103,76);
ctx.lineTo(170,15);
ctx.stroke();
};
img.src = 'images/img.png';
}
Applying styles and colors
 fillStyle = color
strokeStyle = color
 ctx.fillStyle = "orange";
 ctx.fillStyle = "#FFA500";
 ctx.fillStyle = "rgb(255,165,0)";
 Transparency
 globalAlpha = transparency value
 ctx.fillStyle = "rgba(255,165,0,1)";
 ctx.globalAlpha = 0.2;
 Line styles
 lineWidth = value
lineCap = type ('butt','round','square')
lineJoin = type ['round','bevel','miter']
miterLimit = value
 Gradients
 createLinearGradient(x1,y1,x2,y2)
createRadialGradient(x1,y1,r1,x2,y2,r2)
 var lineargradient = ctx.createLinearGradient(0,0,150,150);
 var radialgradient = ctx.createRadialGradient(75,75,0,75,75,100);
 addColorStop(position, color)
 Patterns
 createPattern(image,type)
 Type [repeat, repeat-x, repeat-y and no-repeat.]
 var img = new Image();
 img.src = 'someimage.png';
 var ptrn = ctx.createPattern(img,'repeat');
 Shadows
 shadowOffsetX = float
shadowOffsetY = float
shadowBlur = float
shadowColor = color
Transformations
 save()
restore()
 Translating
 translate(x, y)
 Rotating
 rotate(angle)
 Scaling
 scale(x, y)
 Transforms
 transform(m11, m12, m21, m22, dx, dy)
Compositing
 globalCompositeOperation
 source-over (default)
 source-in
 source-out
 source-atop
 Lighter
 Xor
 destination-over
 destination-in
 destination-out
 destination-atop
 darker
 Copy
 Clipping paths
 Clip()
Basic animations
Basic animation steps
These are the steps you need to take to draw a frame:
 Clear the canvas
Unless the shapes you'll be drawing fill the complete canvas (for
instance a backdrop image), you need to clear any shapes that have
been drawn previously. The easiest way to do this is using
the clearRect method.
 Save the canvas state
If you're changing any setting (styles, transformations, etc) which
affect the canvas state and want to make sure the original state is
used each time a frame is drawn, you need to save it.
 Draw animated shapes
The step where you do the actual frame rendering.
 Restore the canvas state
If you've saved the state, restore it before drawing a new frame.
Basic animations
 setInterval(animateShape,500);
 setTimeout(animateShape,500);
 The new method
 requestAnimationFrame() allows modern browsers to stop
drawing graphics when a tab or window is not visible. Improving
overall performance and batteries on mobile devices.

Contenu connexe

Tendances

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
 
Advanced html5 diving into the canvas tag
Advanced html5 diving into the canvas tagAdvanced html5 diving into the canvas tag
Advanced html5 diving into the canvas tagDavid Voyles
 
Android Vector Drawable
 Android Vector Drawable Android Vector Drawable
Android Vector DrawablePhearum THANN
 
Interactive Graphics
Interactive GraphicsInteractive Graphics
Interactive GraphicsBlazing Cloud
 
Android 2D Drawing and Animation Framework
Android 2D Drawing and Animation FrameworkAndroid 2D Drawing and Animation Framework
Android 2D Drawing and Animation FrameworkJussi Pohjolainen
 
The Canvas Tag
The Canvas TagThe Canvas Tag
The Canvas TagDave Ross
 
Dynamic CSS: Transforms, Transitions, and Animation Basics
Dynamic CSS: Transforms, Transitions, and Animation BasicsDynamic CSS: Transforms, Transitions, and Animation Basics
Dynamic CSS: Transforms, Transitions, and Animation BasicsBeth Soderberg
 
Stupid Canvas Tricks
Stupid Canvas TricksStupid Canvas Tricks
Stupid Canvas Tricksdeanhudson
 
Mastering CSS Animations
Mastering CSS AnimationsMastering CSS Animations
Mastering CSS AnimationsGoodbytes
 
5 tips for your HTML5 games
5 tips for your HTML5 games5 tips for your HTML5 games
5 tips for your HTML5 gamesErnesto Jiménez
 
Interactive Graphics using Javascript, HTML5 and CSS3
Interactive Graphics using Javascript, HTML5 and CSS3Interactive Graphics using Javascript, HTML5 and CSS3
Interactive Graphics using Javascript, HTML5 and CSS3Lee Lundrigan
 
CSS3 : Animation ,Transitions, Gradients
CSS3 : Animation ,Transitions, GradientsCSS3 : Animation ,Transitions, Gradients
CSS3 : Animation ,Transitions, GradientsJatin_23
 
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 FlashThomas Fuchs
 
CSS Animations & Transitions
CSS Animations & TransitionsCSS Animations & Transitions
CSS Animations & TransitionsEdward Meehan
 
CSS Transitions, Transforms, Animations
CSS Transitions, Transforms, Animations CSS Transitions, Transforms, Animations
CSS Transitions, Transforms, Animations Rob LaPlaca
 
Kotlin Mullets
Kotlin MulletsKotlin Mullets
Kotlin MulletsJames Ward
 
Exploring Canvas
Exploring CanvasExploring Canvas
Exploring CanvasKevin Hoyt
 
How to build a html5 websites.v1
How to build a html5 websites.v1How to build a html5 websites.v1
How to build a html5 websites.v1Bitla Software
 

Tendances (20)

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
 
Advanced html5 diving into the canvas tag
Advanced html5 diving into the canvas tagAdvanced html5 diving into the canvas tag
Advanced html5 diving into the canvas tag
 
Html canvas
Html canvasHtml canvas
Html canvas
 
Android Vector Drawable
 Android Vector Drawable Android Vector Drawable
Android Vector Drawable
 
Interactive Graphics
Interactive GraphicsInteractive Graphics
Interactive Graphics
 
Android 2D Drawing and Animation Framework
Android 2D Drawing and Animation FrameworkAndroid 2D Drawing and Animation Framework
Android 2D Drawing and Animation Framework
 
The Canvas Tag
The Canvas TagThe Canvas Tag
The Canvas Tag
 
Dynamic CSS: Transforms, Transitions, and Animation Basics
Dynamic CSS: Transforms, Transitions, and Animation BasicsDynamic CSS: Transforms, Transitions, and Animation Basics
Dynamic CSS: Transforms, Transitions, and Animation Basics
 
Stupid Canvas Tricks
Stupid Canvas TricksStupid Canvas Tricks
Stupid Canvas Tricks
 
Css5 canvas
Css5 canvasCss5 canvas
Css5 canvas
 
Mastering CSS Animations
Mastering CSS AnimationsMastering CSS Animations
Mastering CSS Animations
 
5 tips for your HTML5 games
5 tips for your HTML5 games5 tips for your HTML5 games
5 tips for your HTML5 games
 
Interactive Graphics using Javascript, HTML5 and CSS3
Interactive Graphics using Javascript, HTML5 and CSS3Interactive Graphics using Javascript, HTML5 and CSS3
Interactive Graphics using Javascript, HTML5 and CSS3
 
CSS3 : Animation ,Transitions, Gradients
CSS3 : Animation ,Transitions, GradientsCSS3 : Animation ,Transitions, Gradients
CSS3 : Animation ,Transitions, Gradients
 
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
 
CSS Animations & Transitions
CSS Animations & TransitionsCSS Animations & Transitions
CSS Animations & Transitions
 
CSS Transitions, Transforms, Animations
CSS Transitions, Transforms, Animations CSS Transitions, Transforms, Animations
CSS Transitions, Transforms, Animations
 
Kotlin Mullets
Kotlin MulletsKotlin Mullets
Kotlin Mullets
 
Exploring Canvas
Exploring CanvasExploring Canvas
Exploring 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
 

En vedette

HTML5 and SVG
HTML5 and SVGHTML5 and SVG
HTML5 and SVGyarcub
 
Interactive Vector-Graphics in the Browser
Interactive Vector-Graphics in the BrowserInteractive Vector-Graphics in the Browser
Interactive Vector-Graphics in the Browsertec
 
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 RodychPivorak MeetUp
 
【J-SHIS】地震の発生確率と地震動の超過確率
【J-SHIS】地震の発生確率と地震動の超過確率【J-SHIS】地震の発生確率と地震動の超過確率
【J-SHIS】地震の発生確率と地震動の超過確率NIED
 
Getting Started with HTML5 in Tech Com (STC 2012)
Getting Started with HTML5 in Tech Com (STC 2012)Getting Started with HTML5 in Tech Com (STC 2012)
Getting Started with HTML5 in Tech Com (STC 2012)Peter Lubbers
 
Rucksack 裝滿神奇 css 的後背包
Rucksack 裝滿神奇 css 的後背包Rucksack 裝滿神奇 css 的後背包
Rucksack 裝滿神奇 css 的後背包Anna Su
 
從一個超簡單範例開始學習 Canvas
從一個超簡單範例開始學習 Canvas從一個超簡單範例開始學習 Canvas
從一個超簡單範例開始學習 CanvasAnna Su
 

En vedette (10)

ES6
ES6ES6
ES6
 
HTML5 and SVG
HTML5 and SVGHTML5 and SVG
HTML5 and SVG
 
Canvas & Charts
Canvas & ChartsCanvas & Charts
Canvas & Charts
 
Working With Canvas
Working With CanvasWorking With Canvas
Working With Canvas
 
Interactive Vector-Graphics in the Browser
Interactive Vector-Graphics in the BrowserInteractive Vector-Graphics in the Browser
Interactive Vector-Graphics in the Browser
 
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
 
【J-SHIS】地震の発生確率と地震動の超過確率
【J-SHIS】地震の発生確率と地震動の超過確率【J-SHIS】地震の発生確率と地震動の超過確率
【J-SHIS】地震の発生確率と地震動の超過確率
 
Getting Started with HTML5 in Tech Com (STC 2012)
Getting Started with HTML5 in Tech Com (STC 2012)Getting Started with HTML5 in Tech Com (STC 2012)
Getting Started with HTML5 in Tech Com (STC 2012)
 
Rucksack 裝滿神奇 css 的後背包
Rucksack 裝滿神奇 css 的後背包Rucksack 裝滿神奇 css 的後背包
Rucksack 裝滿神奇 css 的後背包
 
從一個超簡單範例開始學習 Canvas
從一個超簡單範例開始學習 Canvas從一個超簡單範例開始學習 Canvas
從一個超簡單範例開始學習 Canvas
 

Similaire à HTML 5_Canvas

Simple Matlab tutorial using matlab inbuilt commands
Simple Matlab tutorial using matlab inbuilt commandsSimple Matlab tutorial using matlab inbuilt commands
Simple Matlab tutorial using matlab inbuilt commandsLakshmi Sarvani Videla
 
Processing and Processing.js
Processing and Processing.jsProcessing and Processing.js
Processing and Processing.jsjeresig
 
Html5 Canvas Drawing and Animation
Html5 Canvas Drawing and AnimationHtml5 Canvas Drawing and Animation
Html5 Canvas Drawing and AnimationMindfire Solutions
 
Introduction to Canvas - Toronto HTML5 User Group
Introduction to Canvas - Toronto HTML5 User GroupIntroduction to Canvas - Toronto HTML5 User Group
Introduction to Canvas - Toronto HTML5 User Groupdreambreeze
 
Introduction to Canvas - Toronto HTML5 User Group
Introduction to Canvas - Toronto HTML5 User GroupIntroduction to Canvas - Toronto HTML5 User Group
Introduction to Canvas - Toronto HTML5 User Groupbernice-chan
 
Building a Visualization Language
Building a Visualization LanguageBuilding a Visualization Language
Building a Visualization Languagejeresig
 
Fabric.js @ Falsy Values
Fabric.js @ Falsy ValuesFabric.js @ Falsy Values
Fabric.js @ Falsy ValuesJuriy Zaytsev
 
Google I/O 2013 - Android Graphics Performance
Google I/O 2013 - Android Graphics PerformanceGoogle I/O 2013 - Android Graphics Performance
Google I/O 2013 - Android Graphics PerformanceDouO
 
Google I/O 2013 - Android Graphics Performance
Google I/O 2013 - Android Graphics PerformanceGoogle I/O 2013 - Android Graphics Performance
Google I/O 2013 - Android Graphics PerformanceDouO
 
Writeup advanced lane_lines_project
Writeup advanced lane_lines_projectWriteup advanced lane_lines_project
Writeup advanced lane_lines_projectManish Jauhari
 
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
 
Image_Processing_LECTURE_c#_programming.ppt
Image_Processing_LECTURE_c#_programming.pptImage_Processing_LECTURE_c#_programming.ppt
Image_Processing_LECTURE_c#_programming.pptLOUISSEVERINOROMANO
 
openFrameworks 007 - graphics
openFrameworks 007 - graphicsopenFrameworks 007 - graphics
openFrameworks 007 - graphicsroxlu
 
Computer vision image enhancement ppt prajwal deshmukh
Computer vision image enhancement ppt prajwal deshmukhComputer vision image enhancement ppt prajwal deshmukh
Computer vision image enhancement ppt prajwal deshmukhprajdesh26
 
HTML5 Canvas - Basics.pptx
HTML5 Canvas - Basics.pptxHTML5 Canvas - Basics.pptx
HTML5 Canvas - Basics.pptxAhmadAbba6
 

Similaire à HTML 5_Canvas (20)

canvas_1.pptx
canvas_1.pptxcanvas_1.pptx
canvas_1.pptx
 
Scmad Chapter06
Scmad Chapter06Scmad Chapter06
Scmad Chapter06
 
Simple Matlab tutorial using matlab inbuilt commands
Simple Matlab tutorial using matlab inbuilt commandsSimple Matlab tutorial using matlab inbuilt commands
Simple Matlab tutorial using matlab inbuilt commands
 
Processing and Processing.js
Processing and Processing.jsProcessing and Processing.js
Processing and Processing.js
 
Html5 Canvas Drawing and Animation
Html5 Canvas Drawing and AnimationHtml5 Canvas Drawing and Animation
Html5 Canvas Drawing and Animation
 
Intro to Canva
Intro to CanvaIntro to Canva
Intro to Canva
 
Introduction to Canvas - Toronto HTML5 User Group
Introduction to Canvas - Toronto HTML5 User GroupIntroduction to Canvas - Toronto HTML5 User Group
Introduction to Canvas - Toronto HTML5 User Group
 
Introduction to Canvas - Toronto HTML5 User Group
Introduction to Canvas - Toronto HTML5 User GroupIntroduction to Canvas - Toronto HTML5 User Group
Introduction to Canvas - Toronto HTML5 User Group
 
Building a Visualization Language
Building a Visualization LanguageBuilding a Visualization Language
Building a Visualization Language
 
Fabric.js @ Falsy Values
Fabric.js @ Falsy ValuesFabric.js @ Falsy Values
Fabric.js @ Falsy Values
 
Google I/O 2013 - Android Graphics Performance
Google I/O 2013 - Android Graphics PerformanceGoogle I/O 2013 - Android Graphics Performance
Google I/O 2013 - Android Graphics Performance
 
Google I/O 2013 - Android Graphics Performance
Google I/O 2013 - Android Graphics PerformanceGoogle I/O 2013 - Android Graphics Performance
Google I/O 2013 - Android Graphics Performance
 
Writeup advanced lane_lines_project
Writeup advanced lane_lines_projectWriteup advanced lane_lines_project
Writeup advanced lane_lines_project
 
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
 
Image_Processing_LECTURE_c#_programming.ppt
Image_Processing_LECTURE_c#_programming.pptImage_Processing_LECTURE_c#_programming.ppt
Image_Processing_LECTURE_c#_programming.ppt
 
openFrameworks 007 - graphics
openFrameworks 007 - graphicsopenFrameworks 007 - graphics
openFrameworks 007 - graphics
 
Peint talk
Peint talkPeint talk
Peint talk
 
Computer vision image enhancement ppt prajwal deshmukh
Computer vision image enhancement ppt prajwal deshmukhComputer vision image enhancement ppt prajwal deshmukh
Computer vision image enhancement ppt prajwal deshmukh
 
HTML5 Canvas - Basics.pptx
HTML5 Canvas - Basics.pptxHTML5 Canvas - Basics.pptx
HTML5 Canvas - Basics.pptx
 
Resize image vb.net
Resize image vb.netResize image vb.net
Resize image vb.net
 

HTML 5_Canvas

  • 2.  Basic usage  Drawing shapes  Using images  Applying styles and colors  Transformations  Compositing  Basic animations  Optimizing the canvas supported in Firefox 1.5 and later, Opera 9 and later, newer versions of Safari, Chrome, and Internet Explorer 9.
  • 3. <canvas id="tutorial" width="150" height="150"></canvas> This looks a lot like the <img> element, the only difference is that it doesn't have the src and alt attributes. The <canvas> element has only two attributes - width andheight. These are both optional and can also be set using DOM properties. When no width and height attributes are specified, the canvas will initially be 300 pixelswide and 150 pixels high. Fallback content <canvas id="stockGraph" width="150" height="150"> current stock price: $3.15 +0.15 </canvas> <canvas id="clock" width="150" height="150"> <img src="images/clock.png" width="150" height="150" alt=""/> </canvas>
  • 4. The rendering context  2D rendering context.  3D context  ("experimental-webgl") based on OpenGL ES. var canvas = document.getElementById('tutorial'); var ctx = canvas.getContext('2d');
  • 5. Checking for support var canvas = document.getElementById('tutorial'); if (canvas.getContext){ var ctx = canvas.getContext('2d'); // drawing code here } else { // canvas-unsupported code here }
  • 6. A skeleton template <html> <head> <title>Canvas tutorial</title> <script type="text/javascript"> function draw(){ var canvas = document.getElementById('tutorial'); if (canvas.getContext){ var ctx = canvas.getContext('2d'); } } </script> <style type="text/css"> canvas { border: 1px solid black; } </style> </head> <body onload="draw();"> <canvas id="tutorial" width="150" height="150"></canvas> </body> </html>
  • 7. Drawing shapes  The grid Top left is 0,0  canvas only supports one primitive shape - rectangles. All other shapes must be created by combining one or more paths  fillRect(x,y,width,height) : Draws a filled rectangle strokeRect(x,y,width,height) : Draws a rectangular outline clearRect(x,y,width,height) : Clears the specified area and makes it fully transparent  Drawing paths beginPath() closePath() stroke() fill() moveTo(x, y) lineTo(x, y) arc(x, y, radius, startAngle, endAngle, anticlockwise)  Bezier and quadratic curves quadraticCurveTo(cp1x, cp1y, x, y) bezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y)  Rectangles rect(x, y, width, height)
  • 8. Using images  Importing images  Importing images is basically a two step process:  Firstly we need a reference to a JavaScript Image object or other canvas element as a source. It isn't possible to use images by simply providing a URL/path to them.  Secondly we draw the image on the canvas using the drawImage function.  drawImage  drawImage(image, x, y, width, height)  var img = new Image(); // Create new img element  img.src = 'myImage.png'; // Set source path  Slicing  drawImage(image, sx, sy, sWidth, sHeight, dx, dy, dWidth, dHeight)
  • 9. function draw() { var ctx = document.getElementById('canvas').getContext('2d') ; var img = new Image(); img.onload = function(){ ctx.drawImage(img,0,0); ctx.beginPath(); ctx.moveTo(30,96); ctx.lineTo(70,66); ctx.lineTo(103,76); ctx.lineTo(170,15); ctx.stroke(); }; img.src = 'images/img.png'; }
  • 10. Applying styles and colors  fillStyle = color strokeStyle = color  ctx.fillStyle = "orange";  ctx.fillStyle = "#FFA500";  ctx.fillStyle = "rgb(255,165,0)";  Transparency  globalAlpha = transparency value  ctx.fillStyle = "rgba(255,165,0,1)";  ctx.globalAlpha = 0.2;  Line styles  lineWidth = value lineCap = type ('butt','round','square') lineJoin = type ['round','bevel','miter'] miterLimit = value
  • 11.  Gradients  createLinearGradient(x1,y1,x2,y2) createRadialGradient(x1,y1,r1,x2,y2,r2)  var lineargradient = ctx.createLinearGradient(0,0,150,150);  var radialgradient = ctx.createRadialGradient(75,75,0,75,75,100);  addColorStop(position, color)  Patterns  createPattern(image,type)  Type [repeat, repeat-x, repeat-y and no-repeat.]  var img = new Image();  img.src = 'someimage.png';  var ptrn = ctx.createPattern(img,'repeat');
  • 12.  Shadows  shadowOffsetX = float shadowOffsetY = float shadowBlur = float shadowColor = color
  • 13. Transformations  save() restore()  Translating  translate(x, y)  Rotating  rotate(angle)  Scaling  scale(x, y)  Transforms  transform(m11, m12, m21, m22, dx, dy)
  • 14. Compositing  globalCompositeOperation  source-over (default)  source-in  source-out  source-atop  Lighter  Xor  destination-over  destination-in  destination-out  destination-atop  darker  Copy  Clipping paths  Clip()
  • 15. Basic animations Basic animation steps These are the steps you need to take to draw a frame:  Clear the canvas Unless the shapes you'll be drawing fill the complete canvas (for instance a backdrop image), you need to clear any shapes that have been drawn previously. The easiest way to do this is using the clearRect method.  Save the canvas state If you're changing any setting (styles, transformations, etc) which affect the canvas state and want to make sure the original state is used each time a frame is drawn, you need to save it.  Draw animated shapes The step where you do the actual frame rendering.  Restore the canvas state If you've saved the state, restore it before drawing a new frame.
  • 16. Basic animations  setInterval(animateShape,500);  setTimeout(animateShape,500);  The new method  requestAnimationFrame() allows modern browsers to stop drawing graphics when a tab or window is not visible. Improving overall performance and batteries on mobile devices.

Notes de l'éditeur

  1. <canvas> creates a fixed size drawing surface that exposes one or more rendering contexts, which are used to create and manipulate the content shown. We'll focus on the 2D rendering context. Other contexts may provide different types of rendering; for example, there is a 3D context ("experimental-webgl") based on OpenGL ES. The <canvas> is initially blank, and to display something a script first needs to access the rendering context and draw on it. The canvas element has a DOM method called getContext, used to obtain the rendering context and its drawing functions. getContext() takes one parameter, the type of context.
  2. The fallback content is displayed in browsers which do not support <canvas>; scripts can also check for support when they execute. This can easily be done by testing for the getContext() method. Our code snippet from above becomes something like this:
  3. The fallback content is displayed in browsers which do not support <canvas>; scripts can also check for support when they execute. This can easily be done by testing for the getContext() method. Our code snippet from above becomes something like this:
  4. The fallback content is displayed in browsers which do not support <canvas>; scripts can also check for support when they execute. This can easily be done by testing for the getContext() method. Our code snippet from above becomes something like this:
  5. The fallback content is displayed in browsers which do not support <canvas>; scripts can also check for support when they execute. This can easily be done by testing for the getContext() method. Our code snippet from above becomes something like this:
  6. The canvas save and restore methods are used to save and retrieve the canvas state. The canvas drawing state is basically a snapshot of all the styles and transformations that have been applied. Both methods take no parameters. Canvas states are stored on a stack. Every time the save method is called, the current drawing state is pushed onto the stack. A drawing state consists of The transformations that have been applied (i.e. translate, rotate and scale - see below). The values of strokeStyle, fillStyle, globalAlpha, lineWidth, lineCap, lineJoin, miterLimit, shadowOffsetX,shadowOffsetY, shadowBlur, shadowColor, globalCompositeOperation properties. The current clipping path,
  7. We can not only draw new shapes behind existing shapes but we can also use it to mask off certain areas, clear sections from the canvas (not limited to rectangles like the clearRect method does) and more. A clipping path is like a normal canvas shape but it acts as a mask to hide unwanted parts of shapes. This is visualized in the image on the right. The red star shape is our clipping path. Everything that falls outside of this path won't get drawn on the canvas. If we compare clipping paths to the globalCompositeOperation property we've seen above; settings that achieve more or less the same effect are source-in and source-atop. The most important differences between the two are that clipping paths are never actually drawn to the canvas and the clipping path is never affected by adding new shapes. This makes clipping paths ideal for drawing multiple shapes in a restricted area. In the chapter about Drawing shapes I only mentioned the stroke and fill methods, but there's a third method we can use with paths, called clip. clip() We use the clip method to create a new clipping path. By default the canvas element has a clipping path that's the exact same size as the canvas itself (i.e. no clipping occurs).
  8. If you don't want any user interaction it's best to use the setInterval function which repeatedly executes the supplied code. In the example above the animateShapefunction is executed every 500 miliseconds (half a second). The setTimeout function only executes once after the set amount of time. The second method we can use to control an animation is user input. If we wanted to make a game we could use keyboard or mouse events to control the animation. By setting eventListeners we catch any user interaction and execute our animation functions.