SlideShare uma empresa Scribd logo
1 de 37
Introduction to HTML5 canvas
Drawing and Animation
in the Browser
The <canvas> tag
• This is a paired tag, similar to a <div> tag in
many ways.
<div> </div>
<canvas> </canvas>
• However, the area enclosed by the <canvas>
tags can be used for drawing and animation
The <canvas> tag’s attributes
<canvas id="myCanvas" width="600"
height="400"> </canvas>
• Before the canvas can be used for drawing and
animation, it must have an ID, width, and
height assigned to it.
• These may appear in the HTML, or they may
be created with JavaScript/jQuery.
Default content for <canvas>
<canvas id="myCanvas" width="600"
height="400">
<p>Some default content can appear
here.</p>
</canvas>
• In Web browsers that do not support HTML5, the
canvas will not appear.
• You may put default content between the canvas
tags. Only people without HTML5 support will see it.
Doing things with <canvas>
<canvas id="myCanvas" width="600"
height="400">
<p>Some default content can appear
here.</p>
</canvas>
• This is all you’ll see in the HTML document.
Everything else will need JavaScript.
Exercises
Download ZIP here:
http://bit.ly/mm_canvas
http://bit.ly/mm_canvas
More on GitHub: https://github.com/macloo/canvas
What’s in the .js file?
• The JavaScript must not run until after the
HTML has finished loading.
• Therefore, we must use window.onload
in the .js file
• We must wrap all the code for the canvas in a
function that will wait to run until the page
has loaded.
OPEN:
canvas0.html
scripts/canvas0.js
Function to wrap JS code for canvas (1)
window.onload = draw;
// calls function named "draw" – see it below
function draw() {
// put your drawing code here, as many
// lines as needed
} // close draw() function
This is one way to wrap the drawing code.
scripts/canvas0.js
Function to wrap JS code for canvas (2)
window.onload = function () {
// calls an unnamed function
// put your drawing code here, as many
// lines as needed
} // close the unnamed function
This is another way to wrap the drawing code.
scripts/canvas0.js
Target the canvas using its ID (in your HTML)
window.onload = draw;
// calls function named "draw"
function draw() {
var canvas = document.getElementById('myCanvas');
// canvas with id="myCanvas"
// put your drawing code here, as many
//lines as needed
} // close draw() function
var canvas = document.getElementById('myCanvas');
// canvas with id="myCanvas"
canvas0.html
scripts/canvas0.js
Add context, wrap this in an ‘if’ statement
window.onload = draw;
function draw() {
var canvas = document.getElementById('myCanvas');
// canvas with id="myCanvas"
if (canvas.getContext) {
var ctx = canvas.getContext('2d');
// put your drawing code here, as many
//lines as needed
} // close if
} // close draw() function
canvas0.html
scripts/canvas0.js
if (canvas.getContext) {
var ctx = canvas.getContext('2d');
} // close if
The “if” prevents JavaScript from throwing an error if
canvas is not present or not working.
Now let’s do some exercises!
OPEN:
canvas1.html
scripts/canvas1.js
CLOSE:
canvas0.html
scripts/canvas0.js
Draw a square or a rectangle
if (canvas.getContext) {
var ctx = canvas.getContext('2d');
ctx.fillRect(0,0,600,400);
// draw a filled rectangle
} // close if
scripts/canvas1.js
Draw a square or a rectangle
// change both starting points from 0 to 100
ctx.fillRect(100,100,600,400);
// draw a filled rectangle
// reload the HTML and see what happens
scripts/canvas1.js
Change the color (fillStyle)
// add a color first, then draw
ctx.fillStyle = "#E01B6A";
ctx.fillRect(100,100,600,400);
// reload the HTML and see what happens
scripts/canvas1.js
Find a nice color quickly at http://www.colorpicker.com/
Hexadecimal or RGB or rgba codes are all okay.
Change the color (fillStyle) again
// add a color first, then draw
ctx.fillStyle = "#E01B6A";
ctx.fillRect(100,100,600,400);
ctx.fillStyle = "#F7AF05";
// don’t reload the HTML: nothing will happen
scripts/canvas1.js
Hexadecimal or RGB or rgba codes are all okay.
Draw a new rectangle
// add a color first, then draw
ctx.fillStyle = "#E01B6A";
ctx.fillRect(100,100,600,400);
ctx.fillStyle = "#F7AF05";
ctx.fillRect(0,200,500,100);
// reload the HTML and see what happens
scripts/canvas1.js
Interact with this code: http://bit.ly/mm_codepen1
A new exercise …
OPEN:
triangles.html
scripts/triangles.js
CLOSE:
canvas1.html
scripts/canvas1.js
View the HTML file – triangles.html
Draw a new triangle
1. Open triangles.js
2. Do not delete any of the existing triangles
3. To write your own code, first copy the code
for triangle 3 (lines 25–31)
4. Paste the code at line 51
5. Change the color
6. Change all three points of the triangle
7. Save and reload the HTML
A new triangle – triangles.html
Draw another new triangle
1. Still in triangles.js
2. Copy and paste the code you just edited
3. Paste it below the code ctx.fill();
4. Change all three points of the triangle to
make this one “flipped” from your first new
one (remember the grid)
5. Save and reload the HTML
Another new triangle, flipped – triangles.html
A new exercise …
OPEN:
images.html
scripts/images.js
CLOSE:
triangles.html
scripts/triangles.js
The motorcycle image is 600 x 300. Look at images.js —
figure out how to move it so we see the full photo on the canvas.
Again, images.js — can you make the image HALF its real size
— without distorting it in any way?
Shrink the motorcycle
// matches the previous slide
var img = new Image();
img.onload = function() {
ctx.drawImage( img, 300, 50, 300, 150 );
} // close img.onload function
img.src = 'images/motorcycle.png';
scripts/images.js
One last exercise …
OPEN:
animate.html
scripts/animate.js
CLOSE:
images.html
scripts/images.js
Basic animation — animate.html and animate.js
window.onload = init; // calls the function named "init"
// used in timer, below
var newInterval;
// set up the images and call the main function, "draw"
var bgImage = new Image();
var motoImage = new Image();
function init() {
bgImage.src = "images/sketch.jpg";
motoImage.src = "images/motorcycle.png";
draw();
}
function draw() {
var ctx =
document.getElementById('motoCanvas').getContext('2d');
ctx.drawImage(bgImage, 0, 0, 600, 450); // show the background
// make an Object with properties
// be careful with the punctuation!
var moto = {
factor: 0.991,
x: -600, // places it offstage, left
y: 400,
w: motoImage.width,
h: motoImage.height
} “draw” function
begins …
var render = function () {
if (moto.x < 650) {
ctx.drawImage(bgImage, 0, 0);
// must redraw bgImage each time
ctx.drawImage(motoImage, moto.x, moto.y, moto.w, moto.h);
// the next four lines will be changing the values each time
// this function runs -- this is the ENGINE of the animation!
moto.x += 10; // move 10 px to right
moto.y -= 2.5; // move 3 px closer to top
moto.w = moto.w * moto.factor; // decrease size
moto.h = moto.h * moto.factor; // decrease size
} else {
clearInterval(newInterval); // kills the timer
// reset everything so we can replay it:
moto.x = -600;
moto.y = 400;
moto.w = motoImage.width;
moto.h = motoImage.height;
}
}
“draw” function
continued …
// press the Return/Enter key to play the animation
document.body.onkeydown = function(e) { // listen for a key
e = event || window.event; // any kind of event
var keycode = e.charCode || e.keyCode; // any kind of key
if(keycode === 13) { // only the Return or Enter key
// call the "render" function on a timer that will repeat it
// larger numbers are slower (in milliseconds)
newInterval = setInterval(render, 10);
}
}
} // close draw()
“draw” function
continued … and
ends.
Best canvas tutorial (thorough!):
https://developer.mozilla.org/en-
US/docs/Web/Guide/HTML/Canvas_tutorial
More examples with simple code:
http://www.macloo.com/examples/canvas/
GitHub repo:
https://github.com/macloo/canvas
Introduction to HTML5 canvas
Presentation by Mindy McAdams
University of Florida
April 2014

Mais conteúdo relacionado

Mais procurados (20)

JavaScript - Chapter 12 - Document Object Model
  JavaScript - Chapter 12 - Document Object Model  JavaScript - Chapter 12 - Document Object Model
JavaScript - Chapter 12 - Document Object Model
 
Introduction to CSS
Introduction to CSSIntroduction to CSS
Introduction to CSS
 
Advanced Cascading Style Sheets
Advanced Cascading Style SheetsAdvanced Cascading Style Sheets
Advanced Cascading Style Sheets
 
Css box-model
Css box-modelCss box-model
Css box-model
 
Html frames
Html framesHtml frames
Html frames
 
Javascript arrays
Javascript arraysJavascript arrays
Javascript arrays
 
Css
CssCss
Css
 
Images and Tables in HTML
Images and Tables in HTMLImages and Tables in HTML
Images and Tables in HTML
 
Introduction to HTML5
Introduction to HTML5Introduction to HTML5
Introduction to HTML5
 
Bootstrap PPT Part - 2
Bootstrap PPT Part - 2Bootstrap PPT Part - 2
Bootstrap PPT Part - 2
 
CSS Basics
CSS BasicsCSS Basics
CSS Basics
 
Html media
Html mediaHtml media
Html media
 
Web design - Working with forms in HTML
Web design - Working with forms in HTMLWeb design - Working with forms in HTML
Web design - Working with forms in HTML
 
Introduction of Html/css/js
Introduction of Html/css/jsIntroduction of Html/css/js
Introduction of Html/css/js
 
Php mysql ppt
Php mysql pptPhp mysql ppt
Php mysql ppt
 
Bootstrap 4 ppt
Bootstrap 4 pptBootstrap 4 ppt
Bootstrap 4 ppt
 
jQuery
jQueryjQuery
jQuery
 
PHP FUNCTIONS
PHP FUNCTIONSPHP FUNCTIONS
PHP FUNCTIONS
 
Html links
Html linksHtml links
Html links
 
Html5 SVG
Html5 SVGHtml5 SVG
Html5 SVG
 

Semelhante a Introduction to 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 -...Codemotion
 
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
 
Drawing with the HTML5 Canvas
Drawing with the HTML5 CanvasDrawing with the HTML5 Canvas
Drawing with the HTML5 CanvasHenry Osborne
 
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
 
CSS3 Takes on the World
CSS3 Takes on the WorldCSS3 Takes on the World
CSS3 Takes on the WorldJonathan Snook
 
Canvas in html5 - TungVD
Canvas in html5 - TungVDCanvas in html5 - TungVD
Canvas in html5 - TungVDFramgia Vietnam
 
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
 
How to make a video game
How to make a video gameHow to make a video game
How to make a video gamedandylion13
 
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 2018Codemotion
 
Canvas
CanvasCanvas
CanvasRajon
 
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 componentsdevObjective
 
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 ComponentsColdFusionConference
 
Is HTML5 Ready? (workshop)
Is HTML5 Ready? (workshop)Is HTML5 Ready? (workshop)
Is HTML5 Ready? (workshop)Remy Sharp
 

Semelhante a Introduction to HTML5 Canvas (20)

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 -...
 
Html canvas
Html canvasHtml canvas
Html 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
 
JavaScript Canvas
JavaScript CanvasJavaScript Canvas
JavaScript Canvas
 
Drawing with the HTML5 Canvas
Drawing with the HTML5 CanvasDrawing with the HTML5 Canvas
Drawing with the HTML5 Canvas
 
Css5 canvas
Css5 canvasCss5 canvas
Css5 canvas
 
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
 
CSS3 Takes on the World
CSS3 Takes on the WorldCSS3 Takes on the World
CSS3 Takes on the World
 
Canvas in html5 - TungVD
Canvas in html5 - TungVDCanvas in html5 - TungVD
Canvas in html5 - TungVD
 
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
 
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
 
Intro to HTML5
Intro to HTML5Intro to HTML5
Intro to HTML5
 
How to make a video game
How to make a video gameHow to make a video game
How to make a video game
 
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
 
Canvas in html5
Canvas in html5Canvas in html5
Canvas in html5
 
Canvas
CanvasCanvas
Canvas
 
Knockout.js
Knockout.jsKnockout.js
Knockout.js
 
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
 
Is HTML5 Ready? (workshop)
Is HTML5 Ready? (workshop)Is HTML5 Ready? (workshop)
Is HTML5 Ready? (workshop)
 

Mais de Mindy McAdams

Multimedia Journalism Innovations in the Classroom
Multimedia Journalism Innovations in the ClassroomMultimedia Journalism Innovations in the Classroom
Multimedia Journalism Innovations in the ClassroomMindy McAdams
 
Summary of journalism faculty curriculum workshop
Summary of journalism faculty curriculum workshopSummary of journalism faculty curriculum workshop
Summary of journalism faculty curriculum workshopMindy McAdams
 
U.S. j-schools and digital skills
U.S. j-schools and digital skills U.S. j-schools and digital skills
U.S. j-schools and digital skills Mindy McAdams
 
New skill sets for journalism
New skill sets for journalismNew skill sets for journalism
New skill sets for journalismMindy McAdams
 
Journalism blogs: An introduction
Journalism blogs: An introduction Journalism blogs: An introduction
Journalism blogs: An introduction Mindy McAdams
 
Why Your Newsroom Should Be Using WordPress - ONA13
Why Your Newsroom Should Be Using WordPress - ONA13Why Your Newsroom Should Be Using WordPress - ONA13
Why Your Newsroom Should Be Using WordPress - ONA13Mindy McAdams
 
Journalism's Future: Journalism, Not Newspapers
Journalism's Future: Journalism, Not NewspapersJournalism's Future: Journalism, Not Newspapers
Journalism's Future: Journalism, Not NewspapersMindy McAdams
 
An Introduction to the DOM
An Introduction to the DOMAn Introduction to the DOM
An Introduction to the DOMMindy McAdams
 
HTML and Responsive Design
HTML and Responsive Design HTML and Responsive Design
HTML and Responsive Design Mindy McAdams
 
Design Concepts and Web Design
Design Concepts and Web DesignDesign Concepts and Web Design
Design Concepts and Web DesignMindy McAdams
 
Learning Python - Week 4
Learning Python - Week 4 Learning Python - Week 4
Learning Python - Week 4 Mindy McAdams
 
Learning Python - Week 2
Learning Python - Week 2Learning Python - Week 2
Learning Python - Week 2Mindy McAdams
 
Learning Python - Week 1
Learning Python - Week 1Learning Python - Week 1
Learning Python - Week 1Mindy McAdams
 
Freedom of Speech - Louis Brandeis
Freedom of Speech - Louis BrandeisFreedom of Speech - Louis Brandeis
Freedom of Speech - Louis BrandeisMindy McAdams
 
Networked Information Economy / Benkler
Networked Information Economy / BenklerNetworked Information Economy / Benkler
Networked Information Economy / BenklerMindy McAdams
 

Mais de Mindy McAdams (20)

Just Enough Code
Just Enough CodeJust Enough Code
Just Enough Code
 
Multimedia Journalism Innovations in the Classroom
Multimedia Journalism Innovations in the ClassroomMultimedia Journalism Innovations in the Classroom
Multimedia Journalism Innovations in the Classroom
 
Summary of journalism faculty curriculum workshop
Summary of journalism faculty curriculum workshopSummary of journalism faculty curriculum workshop
Summary of journalism faculty curriculum workshop
 
Crowdsourcing
CrowdsourcingCrowdsourcing
Crowdsourcing
 
U.S. j-schools and digital skills
U.S. j-schools and digital skills U.S. j-schools and digital skills
U.S. j-schools and digital skills
 
New skill sets for journalism
New skill sets for journalismNew skill sets for journalism
New skill sets for journalism
 
Journalism blogs: An introduction
Journalism blogs: An introduction Journalism blogs: An introduction
Journalism blogs: An introduction
 
Why Your Newsroom Should Be Using WordPress - ONA13
Why Your Newsroom Should Be Using WordPress - ONA13Why Your Newsroom Should Be Using WordPress - ONA13
Why Your Newsroom Should Be Using WordPress - ONA13
 
Journalism's Future: Journalism, Not Newspapers
Journalism's Future: Journalism, Not NewspapersJournalism's Future: Journalism, Not Newspapers
Journalism's Future: Journalism, Not Newspapers
 
Beginning jQuery
Beginning jQueryBeginning jQuery
Beginning jQuery
 
An Introduction to the DOM
An Introduction to the DOMAn Introduction to the DOM
An Introduction to the DOM
 
JavaScript 101
JavaScript 101JavaScript 101
JavaScript 101
 
HTML and Responsive Design
HTML and Responsive Design HTML and Responsive Design
HTML and Responsive Design
 
Design Concepts and Web Design
Design Concepts and Web DesignDesign Concepts and Web Design
Design Concepts and Web Design
 
Learning Python - Week 4
Learning Python - Week 4 Learning Python - Week 4
Learning Python - Week 4
 
Learning Python - Week 2
Learning Python - Week 2Learning Python - Week 2
Learning Python - Week 2
 
Learning Python - Week 1
Learning Python - Week 1Learning Python - Week 1
Learning Python - Week 1
 
Learning Python
Learning PythonLearning Python
Learning Python
 
Freedom of Speech - Louis Brandeis
Freedom of Speech - Louis BrandeisFreedom of Speech - Louis Brandeis
Freedom of Speech - Louis Brandeis
 
Networked Information Economy / Benkler
Networked Information Economy / BenklerNetworked Information Economy / Benkler
Networked Information Economy / Benkler
 

Último

Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesFatimaKhan178732
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdfQucHHunhnh
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdfSoniaTolstoy
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Disha Kariya
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Krashi Coaching
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
The byproduct of sericulture in different industries.pptx
The byproduct of sericulture in different industries.pptxThe byproduct of sericulture in different industries.pptx
The byproduct of sericulture in different industries.pptxShobhayan Kirtania
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationnomboosow
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxGaneshChakor2
 
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...anjaliyadav012327
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformChameera Dedduwage
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfJayanti Pande
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactdawncurless
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactPECB
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeThiyagu K
 
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...Sapna Thakur
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphThiyagu K
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 

Último (20)

Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and Actinides
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
The byproduct of sericulture in different industries.pptx
The byproduct of sericulture in different industries.pptxThe byproduct of sericulture in different industries.pptx
The byproduct of sericulture in different industries.pptx
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communication
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptx
 
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy Reform
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdf
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptxINDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
 
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot Graph
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 

Introduction to HTML5 Canvas

  • 1. Introduction to HTML5 canvas Drawing and Animation in the Browser
  • 2. The <canvas> tag • This is a paired tag, similar to a <div> tag in many ways. <div> </div> <canvas> </canvas> • However, the area enclosed by the <canvas> tags can be used for drawing and animation
  • 3. The <canvas> tag’s attributes <canvas id="myCanvas" width="600" height="400"> </canvas> • Before the canvas can be used for drawing and animation, it must have an ID, width, and height assigned to it. • These may appear in the HTML, or they may be created with JavaScript/jQuery.
  • 4. Default content for <canvas> <canvas id="myCanvas" width="600" height="400"> <p>Some default content can appear here.</p> </canvas> • In Web browsers that do not support HTML5, the canvas will not appear. • You may put default content between the canvas tags. Only people without HTML5 support will see it.
  • 5. Doing things with <canvas> <canvas id="myCanvas" width="600" height="400"> <p>Some default content can appear here.</p> </canvas> • This is all you’ll see in the HTML document. Everything else will need JavaScript.
  • 7. What’s in the .js file? • The JavaScript must not run until after the HTML has finished loading. • Therefore, we must use window.onload in the .js file • We must wrap all the code for the canvas in a function that will wait to run until the page has loaded. OPEN: canvas0.html scripts/canvas0.js
  • 8. Function to wrap JS code for canvas (1) window.onload = draw; // calls function named "draw" – see it below function draw() { // put your drawing code here, as many // lines as needed } // close draw() function This is one way to wrap the drawing code. scripts/canvas0.js
  • 9. Function to wrap JS code for canvas (2) window.onload = function () { // calls an unnamed function // put your drawing code here, as many // lines as needed } // close the unnamed function This is another way to wrap the drawing code. scripts/canvas0.js
  • 10. Target the canvas using its ID (in your HTML) window.onload = draw; // calls function named "draw" function draw() { var canvas = document.getElementById('myCanvas'); // canvas with id="myCanvas" // put your drawing code here, as many //lines as needed } // close draw() function var canvas = document.getElementById('myCanvas'); // canvas with id="myCanvas" canvas0.html scripts/canvas0.js
  • 11. Add context, wrap this in an ‘if’ statement window.onload = draw; function draw() { var canvas = document.getElementById('myCanvas'); // canvas with id="myCanvas" if (canvas.getContext) { var ctx = canvas.getContext('2d'); // put your drawing code here, as many //lines as needed } // close if } // close draw() function canvas0.html scripts/canvas0.js if (canvas.getContext) { var ctx = canvas.getContext('2d'); } // close if The “if” prevents JavaScript from throwing an error if canvas is not present or not working.
  • 12. Now let’s do some exercises! OPEN: canvas1.html scripts/canvas1.js CLOSE: canvas0.html scripts/canvas0.js
  • 13. Draw a square or a rectangle if (canvas.getContext) { var ctx = canvas.getContext('2d'); ctx.fillRect(0,0,600,400); // draw a filled rectangle } // close if scripts/canvas1.js
  • 14. Draw a square or a rectangle // change both starting points from 0 to 100 ctx.fillRect(100,100,600,400); // draw a filled rectangle // reload the HTML and see what happens scripts/canvas1.js
  • 15. Change the color (fillStyle) // add a color first, then draw ctx.fillStyle = "#E01B6A"; ctx.fillRect(100,100,600,400); // reload the HTML and see what happens scripts/canvas1.js Find a nice color quickly at http://www.colorpicker.com/ Hexadecimal or RGB or rgba codes are all okay.
  • 16. Change the color (fillStyle) again // add a color first, then draw ctx.fillStyle = "#E01B6A"; ctx.fillRect(100,100,600,400); ctx.fillStyle = "#F7AF05"; // don’t reload the HTML: nothing will happen scripts/canvas1.js Hexadecimal or RGB or rgba codes are all okay.
  • 17. Draw a new rectangle // add a color first, then draw ctx.fillStyle = "#E01B6A"; ctx.fillRect(100,100,600,400); ctx.fillStyle = "#F7AF05"; ctx.fillRect(0,200,500,100); // reload the HTML and see what happens scripts/canvas1.js
  • 18.
  • 19. Interact with this code: http://bit.ly/mm_codepen1
  • 20. A new exercise … OPEN: triangles.html scripts/triangles.js CLOSE: canvas1.html scripts/canvas1.js
  • 21. View the HTML file – triangles.html
  • 22. Draw a new triangle 1. Open triangles.js 2. Do not delete any of the existing triangles 3. To write your own code, first copy the code for triangle 3 (lines 25–31) 4. Paste the code at line 51 5. Change the color 6. Change all three points of the triangle 7. Save and reload the HTML
  • 23. A new triangle – triangles.html
  • 24. Draw another new triangle 1. Still in triangles.js 2. Copy and paste the code you just edited 3. Paste it below the code ctx.fill(); 4. Change all three points of the triangle to make this one “flipped” from your first new one (remember the grid) 5. Save and reload the HTML
  • 25. Another new triangle, flipped – triangles.html
  • 26. A new exercise … OPEN: images.html scripts/images.js CLOSE: triangles.html scripts/triangles.js
  • 27. The motorcycle image is 600 x 300. Look at images.js — figure out how to move it so we see the full photo on the canvas.
  • 28. Again, images.js — can you make the image HALF its real size — without distorting it in any way?
  • 29. Shrink the motorcycle // matches the previous slide var img = new Image(); img.onload = function() { ctx.drawImage( img, 300, 50, 300, 150 ); } // close img.onload function img.src = 'images/motorcycle.png'; scripts/images.js
  • 30. One last exercise … OPEN: animate.html scripts/animate.js CLOSE: images.html scripts/images.js
  • 31. Basic animation — animate.html and animate.js
  • 32. window.onload = init; // calls the function named "init" // used in timer, below var newInterval; // set up the images and call the main function, "draw" var bgImage = new Image(); var motoImage = new Image(); function init() { bgImage.src = "images/sketch.jpg"; motoImage.src = "images/motorcycle.png"; draw(); }
  • 33. function draw() { var ctx = document.getElementById('motoCanvas').getContext('2d'); ctx.drawImage(bgImage, 0, 0, 600, 450); // show the background // make an Object with properties // be careful with the punctuation! var moto = { factor: 0.991, x: -600, // places it offstage, left y: 400, w: motoImage.width, h: motoImage.height } “draw” function begins …
  • 34. var render = function () { if (moto.x < 650) { ctx.drawImage(bgImage, 0, 0); // must redraw bgImage each time ctx.drawImage(motoImage, moto.x, moto.y, moto.w, moto.h); // the next four lines will be changing the values each time // this function runs -- this is the ENGINE of the animation! moto.x += 10; // move 10 px to right moto.y -= 2.5; // move 3 px closer to top moto.w = moto.w * moto.factor; // decrease size moto.h = moto.h * moto.factor; // decrease size } else { clearInterval(newInterval); // kills the timer // reset everything so we can replay it: moto.x = -600; moto.y = 400; moto.w = motoImage.width; moto.h = motoImage.height; } } “draw” function continued …
  • 35. // press the Return/Enter key to play the animation document.body.onkeydown = function(e) { // listen for a key e = event || window.event; // any kind of event var keycode = e.charCode || e.keyCode; // any kind of key if(keycode === 13) { // only the Return or Enter key // call the "render" function on a timer that will repeat it // larger numbers are slower (in milliseconds) newInterval = setInterval(render, 10); } } } // close draw() “draw” function continued … and ends.
  • 36. Best canvas tutorial (thorough!): https://developer.mozilla.org/en- US/docs/Web/Guide/HTML/Canvas_tutorial More examples with simple code: http://www.macloo.com/examples/canvas/ GitHub repo: https://github.com/macloo/canvas
  • 37. Introduction to HTML5 canvas Presentation by Mindy McAdams University of Florida April 2014

Notas do Editor

  1. CONTACT ----- http://mindymcadams.com/ ----- Lecture by Mindy McAdams, University of Florida, April 2013.
  2. http://bit.ly/mm_canvas
  3. This is one way to wrap the drawing code.
  4. This is another way to wrap the drawing code.
  5. This draws a rectangle starting at x = 0 (horizontal = left edge) and y = 0 (vertical = top). Then it goes right to the 600-pixel mark and down to the 400-pixel mark – and fills that with the default color, which is black. Open canvas1.html and LOOK AT IT.
  6. This draws a rectangle starting at x = 100 (horizontal = left edge) and y = 100 (vertical = top). Then it goes right to the 600-pixel mark and down to the 400-pixel mark.
  7. This draws a rectangle starting at x = 100 (horizontal = left edge) and y = 100 (vertical = top). Then it goes right to the 600-pixel mark and down to the 400-pixel mark.
  8. This draws a rectangle starting at x = 100 (horizontal = left edge) and y = 100 (vertical = top). Then it goes right to the 600-pixel mark and down to the 400-pixel mark.
  9. This draws a rectangle starting at x = 100 (horizontal = left edge) and y = 100 (vertical = top). Then it goes right to the 600-pixel mark and down to the 400-pixel mark.
  10. The x axis is horizontal. The y axis is vertical. The numbers represent pixels. The top left corner is 0,0. This canvas is 600 x 400. The lines of the grid are 20 pixels apart. http://www.macloo.com/examples/canvas/canvas8.html
  11. View the HTML file – triangles.html
  12. View the HTML file – triangles.html
  13. View the HTML file – triangles.html
  14. View the HTML file – images.html
  15. View the HTML file – images.html
  16. View the HTML file – animate.html
  17. From animate.js
  18. From animate.js
  19. From animate.js
  20. From animate.js
  21. https://developer.mozilla.org/en-US/docs/HTML/Canvas/Tutorial http://www.macloo.com/examples/canvas/
  22. CONTACT ----- http://mindymcadams.com/ ----- Lecture by Mindy McAdams, University of Florida, April 2013.