IDIA 618185 Spring 2013 Bridget M Blodgett Canvas HTML5 added the canvas element to the current line up of tags Unlike previous elements the canvas actually allows users to engage with presentation through a drawing or paint like presentation ID: 181320
Download Presentation The PPT/PDF document "Getting Started with Canvas" is the property of its rightful owner. Permission is granted to download and print the materials on this web site for personal, non-commercial use only, and to display it on your personal computer provided you do not modify the materials and that you retain all copyright notices contained in the materials. By downloading content from our website, you accept the terms of this agreement.
Slide1
Getting Started with Canvas
IDIA 618.185
Spring 2013
Bridget M. BlodgettSlide2
Canvas
HTML5 added the canvas element to the current line up of tags
Unlike previous elements the canvas actually allows users to engage with presentation through a drawing or paint like presentationSlide3
Inserting Canvas
Since canvas is supported by HTML5 it has its own element you can use
<canvas id=“
mycanvas
” width=“600” height=“200”> </canvas>
Once you have added this code the browser will automatically reserve this space on the page
The top left corner is the most important since it is where everything will be measured fromSlide4
Simple Canvas
Without using CSS to create a border or JavaScript to create some interactivity the canvas is just a big blank spot on your page
By default the canvas you create is transparent and will fill in with colored pixels once you enable drawing
This allows it to be positioned on top of other elements like an image or a paragraph
Be careful assigning a size to the canvas using CSS, it causes the default 300x150 pixel canvas to scale to that sizeSlide5
Filling in Canvas
JavaScript is used to make content on the canvas
You can make a variable and assign the output of your canvas page to it for manipulation
The book shows .
getContext
as one function usable in canvas. What are some others?
Try altering the following code to make different sized rectanglesSlide6
<script>
window.onload
= function() {
var
canvas =
document.getElementById
("
tshirtCanvas
");
var
context =
canvas.getContext
("2d");
context.fillRect
(10, 10, 100, 100);
};
</script>Slide7
Checking For Support
Not all browsers support canvas yet and you should always check to make sure that it is supported before trying anything
By using this code you can run this check:
if (
canvas.getContext
) {
// you have canvas
} else {
// sorry no canvas
aPI
support
}
By placing text between the canvas tags you can alert users who don’t have canvas that they are missing a feature on the site
This text is conveniently ignored by browsers that support canvasSlide8
Including Forms
You can use forms on your HTML page to allow a user to make changes to the canvas
Instead of submitting JS will handle the values when the user clicks a button
The JS for pulling information from an option menu is a bit different than what we’ve encountered beforeSlide9
var
selectObj
=
document.getElementById
("
backgroundColor
");
var
index =
selectObj.selectedIndex
;
var
bgColor
=
selectObj
[index].value;
var
selectObj
=
document.getElementById
("shape");
var
index =
selectObj.selectedIndex
;
var
shape =
selectObj
[index].value;
var
selectObj
=
document.getElementById
("
foregroundColor
");
var
index =
selectObj.selectedIndex
;
var
fgColor
=
selectObj
[index].value;Slide10
Creating Random Elements
By using custom functions we can make and add random elements to the canvas
The important step is making sure that any custom functions you create are passed the canvas and the context variables
If you forget this they won’t be able to add their random items to the canvas!Slide11
function
drawSquare
(canvas, context) {
var
w =
Math.floor
(
Math.random
() * 40);
var
x =
Math.floor
(
Math.random
() *
canvas.width
);
var
y =
Math.floor
(
Math.random
() *
canvas.height
);
context.fillStyle
= "
lightblue
";
context.fillRect
(x, y, w, w);
}Slide12
Replacing Canvas Items
If you want users to be able to “reset” their canvas you should make a function the sends the canvas back to its starting state
The easiest way to do this is often to just fill in the background with a rectangle that is the same color and size as your default canvas elementSlide13
function
previewHandler
() {
//stuff
fillBackgroundColor
(canvas, context);
//other stuff
}
function
fillBackgroundColor
(canvas, context) {
var
selectObj
=
document.getElementById
("
backgroundColor
");
var
index =
selectObj.selectedIndex
;
var
bgColor
=
selectObj
[index].value;
context.fillStyle
=
bgColor
;
context.fillRect
(0, 0,
canvas.width
,
canvas.height
);
}Slide14
Paths and Strokes
Shapes besides rectangles can be more difficult
We need to determine a path that the shape follows and then stroke (copy over) that path with a color
The
beginPath
(),
moveTo
(), an
lineTo
() methods set up the initial outline
closePath
() will end the shape we’re drawing by connecting the current point with the starting pointSlide15
function
fillTriangle
(canvas, context) {
context.beginPath
();
context.moveTo
(100, 150);
context.lineTo
(250, 75);
context.lineTo
(125, 30);
context.closePath
();
context.lineWidth
= 5;
context.stroke
();
context.fillStyle
= "red";
context.fill
();
}Slide16
Arcs
Circles are more difficult because they do not go in a straight line
JS needs to compute the arc or degree of the curve between two points
Like other shapes begin with
beingPath
() but then use arc()
context.arc(x, y, radius,
startangle
,
endangle
, direction)Slide17Slide18
Radians
Canvas does not compute circles in degrees (like we are used to doing)
Instead it uses radians which are equal to 180 divided by
π
A function can do this conversion for you automatically
function
degreesToRadians
(degrees) {
return (degrees *
Math.PI
)/180;
}Slide19
Combining Sources
You can integrate information from other web services into the canvas
Using the callback function from last week we can get a user’s twitter information to display on the canvas
It simply requires a small script on the HTML page and a function in our JS code
<script
src
="https://twitter.com/statuses/
user_timeline
/
wickedsmartly.json
?
callback=
updateTweets
"></script>Slide20
function
updateTweets
(tweets) {
var
tweetsSelection
=
document.getElementById
("tweets");
for (
var
i
= 0;
i
<
tweets.length
;
i
++) {
tweet = tweets[
i
];
var
option =
document.createElement
("option");
option.text
=
tweet.text
;
option.value
=
tweet.text.replace
("\"", "'");
tweetsSelection.options.add
(option);
}
tweetsSelection.selectedIndex
= 0;
}Slide21
Adding Text
There is a method called
fillText
() which will take some input text and a starting area and write it to your canvas
You can then use the font,
textBasline
,
textAlign
properties to style your text on the screen
They accept strings similar to CSS inside quotesSlide22
function
drawText
(canvas, context) {
var
selectObj
=
document.getElementById
("
foregroundColor
");
var
index =
selectObj.selectedIndex
;
var
fgColor
=
selectObj
[index].value;
context.fillStyle
=
fgColor
;
context.font
= "bold 1em sans-serif";
context.textAlign
= "left";
context.fillText
("I saw this tweet", 20, 40);
selectObj
=
document.getElementById
("tweets");
index =
selectObj.selectedIndex
;
var
tweet =
selectObj
[index].value;
context.font
= "italic 1.2em serif";
context.fillText
(tweet, 30, 100);
context.font
= "bold 1em sans-serif";
context.textAlign
= "right";
context.fillText
("and all I got was this lousy t-shirt!",
canvas.width-20, canvas.height-40);
}Slide23
Adding Images
Images require a bit of prep work
The image must be in a folder accessible to your JS
In the JS code you will need to make a new image variable and set its .
src
property to the location of the image file
Then once the image has loaded you can draw it on the screen at a selected locationSlide24
function
drawBird
(canvas, context) {
var
twitterBird
= new Image();
twitterBird.src
= "twitterBird.png";
twitterBird.onload
= function() {
context.drawImage
(
twitterBird
, 20, 120, 70, 70);
};
}Slide25