CS7026 – HTML5 Canvas. What is the element 2  HTML5 defines the element as “a resolution-dependent bitmap canvas which can be used for rendering graphs,

Slides:



Advertisements
Similar presentations
HTML Basics Customizing your site using the basics of HTML.
Advertisements

HTML5 CANVAS.  Rectangles  Arcs  Lines  Features we won’t look at  Images  Drag and drop  Animation  Widely supported DRAWING PICTURES IN HTML.
Cascading Style Sheets (CSS). Cascading Style Sheets With the explosive growth of the World Wide Web, designers and programmers quickly explored and reached.
CSCI 3100 Tutorial 6 Web Development Tools 1 Cuiyun GAO 1.
Cascading Style Sheets
Chapter 3 – Designing your web pages Dr. Stephanos Mavromoustakos.
Neal Stublen Why Use a Canvas?  Flexibility… Use of drawing primitives (lines, arcs, text) Direct access to element display pixels.
Programming Club IIT Kanpur
HTML 5 Previous version: HTML4.01, 1999 Still work in progress, most browsers support some of it.
1 Canvas Tag In JavaScript Amy Luong Yan Ge Hon Yee Regneel Prahalad Michael Leggio.
Creating a Web Page with Tables. Objectives Create a text table with preformatted text Create the basic structure of a graphical table Organize table.
Tutorial 8 Designing a Web Site with Frames. XP Objectives Explore the uses of frames in a Web site Create a frameset consisting of rows and columns of.
4.01 Cascading Style Sheets
Create a Web Site with Frames
1 Using jQuery JavaScript & jQuery the missing manual (Second Edition)
CHAPTER 21 INTRODUCING THE HTML 5 CANVAS. LEARNING OBJECTIVES How to create a canvas using the and tag pair How to test if a browser supports canvas operations.
Canvas, SVG, Workers Doncho Minkov Telerik Corporation
Web Programming Language Week 13 Ken Cosh HTML 5.
CSS Box Model. What is the CSS Box Model? The “Box Model” is a tool we use to lay out our web pages in a number of individual "boxes" or "containers".
IT Engineering I Instructor: Rezvan Shiravi
INT222 – Internet Fundamentals Weekly Notes: AJAX and Canvas 1.
HTML Essentials Frames and Frame Tags. Introduction A frame used to be an effective design tool Utilized space effectively by subdividing screen One idea:
ITP 104.  While you can do things like this:  Better to use styles instead:
XP Using Frames in a Web Site Ali Alfayly. XP Tutorial Objectives Create frames for a Web site Control the appearance and placement of frames Control.
CSS The Definitive Guide Chapter 8.  Allows one to define borders for  paragraphs  headings  divs  anchors  images  and more.
 This presentation introduces the following: › 3 types of CSS › CSS syntax › CSS comments › CSS and color › The box model.
10/4/2015Tables1 Spring, 2008 Modified by Linda Kenney 4/2/08.
Getting Started with Canvas IDIA Spring 2013 Bridget M. Blodgett.
HTML 5 Tutorial Chapter 5 Canvas. Canvas The tag is used to display graphics. The Canvas is a rectangular area we control each and every pixel of it.
HTML5 CANVAS. SAVING INFORMATION BETWEEN FUNCTION CALLS.
Session: 17. © Aptech Ltd. 2Canvas and JavaScript / Session 17  Describe Canvas in HTML5  Explain the procedure to draw lines  Explain the procedure.
INTRODUCTION TO JAVASCRIPT AND DOM Internet Engineering Spring 2012.
Designing a Web Page with Tables. A text table: contains only text, evenly spaced on the Web page in rows and columns uses only standard word processing.
Element. The element Used to dynamically draw graphics using javascript. Capable of drawing paths, circles, rectangles, text, and images.
Addison Wesley is an imprint of © 2010 Pearson Addison-Wesley. All rights reserved. Chapter 7 The Game Loop and Animation Starting Out with Games & Graphics.
به نام خدا تنظیم کننده : فرانه حدادی استاد : مهندس زمانیان تابستان 92.
CIS234A- Lecture 7 Instructor Greg D’Andrea. Tables A table can be displayed on a Web page either in a text or graphical format. A text table: – contains.
Graphic Basics in C ATS 315. The Graphics Window Will look something like this.
CS 174: Web Programming October 5 Class Meeting Department of Computer Science San Jose State University Fall 2015 Instructor: Ron Mak
Intro to the Canvas Canvas is an HTML5 element If you see this, your browser doesn't support the canvas Canvas is manipulated with javascript c = document.getElementById("mycanvas");
CHAPTER 22 ADVANCED CANVAS PROGRAMMING. LEARNING OBJECTIVES How the HTML 5 canvas supports linear and radial gradients How to fill a shape with a pattern.
Graphics Concepts CS 2302, Fall /17/20142 Drawing in Android.
INT222 - Internet Fundamentals Shi, Yue (Sunny) Office: T2095 SENECA COLLEGE.
Positioning Objects with CSS and Tables
Presented By Nanda Kumar(972789) P. Trinesh (982816) Sk. Salma (982824) K. Madhuri (982814) HTML5.
Can SAS Do Canvas? Creating Graphs Using HTML 5 Canvas Elements Edwin J. van Stein Astellas Pharma Global Development.
07 – HTML5 Canvas (1) Informatics Department Parahyangan Catholic University.
1 Using jQuery JavaScript & jQuery the missing manual (Second Edition)
Lecture 9: Extra Features and Web Design Tarik Booker CS 120 California State University, Los Angeles.
HTML 5 (Part 1) – Start from SCRATCH. HTML 5 – Start from SCRATCH.
CHAP 2. CANVAS API.  Dynamically generate and render graphics, charts, images and animations  SVG (Scalable Vector Graphics) vs. Canvas  Bitmap canvas.
XHTML. What Is XHTML? XHTML stands for EXtensible HyperText Markup Language XHTML is almost identical to HTML XHTML is stricter than HTML XHTML is HTML.
What is a Function Expression?
SVG & DOM Manipulation via Javascript
Internet of the Past.
4.01 Cascading Style Sheets
CSS Layouts: Grouping Elements
Chapter 5 Introduction to Cascading Style Sheets (CSS): Part 2
CMPE 280 Web UI Design and Development September 12 Class Meeting
Inserting and Working with Images
Canvas Notes
CIIT-Human Computer Interaction-CSC456-Fall-2015-Mr
Advanced CSS BIS1523 – Lecture 20.
Web Programming Language
Creating a Baseline Grid
ISC440: Web Programming II Ch14: HTML5 Canvas
The Canvas.
Responsive Framework.
4.01 Cascading Style Sheets
JavaScript – Let’s Draw!
Presentation transcript:

CS7026 – HTML5 Canvas

What is the element 2  HTML5 defines the element as “a resolution-dependent bitmap canvas which can be used for rendering graphs, game graphics, or other visual images on the fly.”  A canvas is a rectangle on your page in which you can use JavaScript to draw anything you want. You control every pixel of it.  Browser support is good.

HTML5 Canvas 3  To add a canvas element to the HTML5 page specify the id, width, and height of the element:  Similar to the element, has a width and height set in the markup to give it an actual size.  And because canvas requires scripting for its full capabilities, we add an id attribute that will allow us to target it using either JavaScript or a JavaScript web development library like jQuery or MooTools.

HTML5 Canvas and CSS 4  Once you have this basic markup, you can use CSS to make the canvas visible or, using CSS3 transition properties (more anon…), move it around - the same as you would do with any other HTML element.  You can add a border, padding, background colour, margins, you can float the canvas, and assign CSS properties to it just like any HTML5 element.

Draw With JavaScript 5  The canvas element has no drawing abilities of its own. All drawing must be done using JavaScript.  To start drawing on a canvas, you need to first target it using the Document Object Model (DOM).  Since you can include more than one canvas element on any given page, this is where an ID attribute comes into play (in this case, our ID is myCanvas ). var canvas = document.getElementById("myCanvas");

Some Basic Scripting to Make It Work 6  Once the canvas is targeted, the getContext() JavaScript method needs to be called. var context = canvas.getContext("2d");  The getContext("2d") object is a built-in HTML5 object, with many methods to draw paths, boxes, circles, characters, images and more.  Essentially this means you will have access to the canvas drawing API.

Some Basic Scripting to Make It Work 7  Here’s an example of code that draws an object on the canvas: var canvas = document.getElementById("myCanvas"); var context = canvas.getContext("2d"); context.fillStyle = "rgba(0, 0, 255,.5)"; context.fillRect(25, 25, 125, 125);  After defining the canvas element via the DOM (line 1), the context is defined (line 2), then a shape is coloured and drawn (lines 3 and 4).

Some Basic Scripting to Make It Work 8  The first two lines are more or less standard stuff, whereas the third and fourth lines consist of a few examples of custom code using the properties and methods available in the drawing API.  The four values given above in the fillRect() method represent the distance from the x axis, the distance from the y axis, the width, and the height (in that order).

Some Points of Note 9  Every canvas element starts out blank, so it will not appear on the page until something is drawn on it or if it’s styled via CSS (e.g. giving it a border or giving it a background colour).  Each canvas element appears in the DOM  The getContext() method “returns an object that exposes an API for drawing” (definition straight from the spec)

Some Points of Note 10  There are currently two kinds of contexts available: 2d and webgl (2d is currently the more commonly used context)  The canvas element is “resolution-dependent,” which means (unlike SVG) it will not always scale cleanly after rendering.  The default colour for any shape drawn is black  Canvas-drawn objects are given colours using RGBA or Hex values

Drawing Rectangles and Paths 11  The 2D context allows for the use of a number of different drawing methods and properties, each utilizing syntaxes familiar to CSS and JavaScript developers.

Drawing Rectangles and Paths 12  Some of the JavaScript methods associated with drawing rectangles:  fillStyle(color|pattern|gradient): Sets a fill style for the shape  fillRect(x,y,w,h): Draws a rectangle according to the given size and coordinate values and fills the object with whatever is defined in the fill style  clearRect(x,y,w,h): Clears the pixels inside the space defined by the given size and coordinate values  strokeStyle(color|pattern|gradient): Sets a stroke style for the shape  strokeRect(x,y,w,h): Draws the rectangle using strokes or borders (apart from the fill) according to the given size and coordinate values; this is done using the determined stroke style.

Drawing Rectangles and Paths 13  Similar to the concept behind drawing rectangles, you can draw straight lines using the moveTo() and lineTo() methods.  These methods define, by means of x and y coordinates, the start and end points of the lines, or paths, that will be drawn.  These methods, however, do not actually draw the visible lines; they prepare the canvas for the actual stroking of the lines that will occur when you call the stroke() method.

Drawing Rectangles and Paths 14  Here’s a simple example: var canvas = document.getElementById("myCanvas"); var context = canvas.getContext("2d"); context.moveTo(0, 0); context.lineTo(400, 400); context.strokeStyle = "#ff0000"; context.stroke();

Drawing Rectangles and Paths 15  This code (lines 2-6) draws a diagonal line from the top left corner of the canvas (0, 0) to the bottom right corner (400, 400).  The last line of code uses the previously mentioned stroke() method to stroke the path that was prepared on lines 3 and 4.  Line 5 has the optional strokeStyle method that can give the line a colour, gradient, or pattern. If a stroke style is not declared, the line will be black by default.

Further Points to note  Coordinates that define paths and shapes can have decimal values, and this is encouraged to ensure line widths in certain circumstances are represented accurately  To draw multiple paths in multiple stroke styles, you use the beginPath() method for each line.

Arcs 17  For drawing arcs or circles we use the arc method: arc(x, y, radius, startAngle, endAngle, anticlockwise)  This method takes five parameters:  x and y are the coordinates of the circle's centre.  Radius is self explanatory.  The startAngle and endAngle parameters define the start and end points of the arc in radians. The starting and closing angle are measured from the x axis.  The anticlockwise parameter is a Boolean value which when true draws the arc anticlockwise, otherwise in a clockwise direction.

An Aside -Radians 18  A radian is a unit of angular measure such that the arc that subtends it is exactly equal to the length of the radius.  So since the circumference of a circle is 2r*PI, the number of radians in a circle is equal to 2*PI and a semicircle is made up of PI radians.  It's equal to about degrees, but since it doesn't use an arbitrary index (1->360) and uses PI instead, it is a lot more useful in maths.

An Aside -Radians 19  Here it is visually:

Drawing Circles 20  Draw a circle by specifying the size, colour, and position: Your browser does not support the canvas element. var canvas=document.getElementById("myCanvas"); var context=canvas.getContext("2d"); context.fillStyle="#FF0000"; context.beginPath(); context.arc(70,18,15,0,Math.PI*2,true); context.closePath(); context.fill();

moveTo() 21  One very useful function, which doesn't actually draw anything, is the moveTo() function. You can probably best think of this as lifting a pen or pencil from one spot on a piece of paper and placing it on the next: moveTo(x,y)  The moveTo() function takes two arguments, x and y, which are the coordinates of the new starting point.  When the canvas is initialized or the beginPath() method is called, you typically will want to use the moveTo() method to place the starting point somewhere else. We could also use the moveTo() method to draw unconnected paths.

Smiley Face! 22 context.beginPath(); context.arc(75,75,50,0,Math.PI*2,true); // Outer circle context.moveTo(110,75); context.arc(75,75,35,0,Math.PI,false);// Mouth(clockwise) context.moveTo(65,65); context.arc(60,65,5,0,Math.PI*2,true); // Left eye context.moveTo(95,65); context.arc(90,65,5,0,Math.PI*2,true); // Right eye context.stroke();

Image 23  The canvas drawing context defines several methods for drawing an image on a canvas:  drawImage(image, dx, dy) takes an image and draws it on the canvas. The given coordinates (dx, dy) will be the upper-left corner of the image. Coordinates (0, 0) would draw the image at the upper-left corner of the canvas.  drawImage(image, dx, dy, dw, dh) takes an image, scales it to a width of dw and a height of dh, and draws it on the canvas at coordinates (dx, dy).  drawImage(image, sx, sy, sw, sh, dx, dy, dw, dh) takes an image, clips it to the rectangle (sx, sy, sw, sh), scales it to dimensions (dw, dh), and draws it on the canvas at coordinates (dx, dy)

Image 24  To draw an image on a canvas, you need an image.  The image can be an existing element, or you can create an Image object with JavaScript.  Either way, you need to ensure that the image is fully loaded before you can draw it on the canvas.

Example - Image 25  Put an image on the canvas: Your browser does not support the canvas element. var canvas = document.getElementById("myCanvas"); var context = canvas.getContext("2d"); var lily = new Image(); lily.src = "pink_lily.png"; lily.onload = function() { context.drawImage(lily, 0, 0); };

Canvas Text 26  You can draw any Unicode character onto a canvas element.  If you don’t use the typographic attributes on text, the text will display using CSS styles applied to the canvas element.  The magic words for printing text in canvas are "fillStyle","strokeStyle", "font“,"textBaseline" and lastly "fillText" and "strokeText".

Canvas Text 27 var canvas = document.getElementById("myCanvas"); var context = canvas.getContext("2d"); context.fillStyle = '#f00'; context.font = 'italic bold 30px sans-serif'; context.textBaseline = 'bottom'; context.fillText('HTML5 is cool!', 50, 100); context.strokeStyle = "#003300"; context.font = '40px san-serif'; context.textBaseline = 'bottom'; context.strokeText('HTML5 is cool?', 300, 100);

Canvas Text 28

Canvas Text - Baseline 29  From WHATWG:

Canvas Text - Baseline 30 context.textBaseline = "top"; context.fillText('Top', 5, 100); context.textBaseline = "bottom"; context.fillText('Bottom', 80, 100); context.textBaseline = "middle"; context.fillText('Middle', 200, 100); context.textBaseline = "alphabetic"; context.fillText('Alphabetic', 300, 100); context.textBaseline = "hanging"; context.fillText('Hanging', 400, 100);

Linear and Radial Gradients 31  In step with what is now possible in CSS3 in most modern browsers, the canvas drawing API allows you to fill your shapes and paths with two types of gradients.  Here is an example showing a rectangle being filled with a linear gradient: 1. var canvas=document.getElementById("myCanvas"); 2. var context= canvas.getContext("2d"); 3. var myGradient= context.createLinearGradient(0,0,100,0); 4. myGradient.addColorStop(0, "#cccccc"); 5. myGradient.addColorStop(1, "#ffffff"); 6. context.fillStyle = myGradient; 7. context.fillRect(25, 25, 125, 125);

Linear and Radial Gradients 32  On line 3, the gradient is stored in memory and is given 4 arguments.  The first two arguments are the x and y coordinates that determine the starting point of the gradient; the second two arguments are the x and y coordinates that determine the end point of the gradient.  After the gradient is created (but not drawn yet), colour stops are added (lines 4-5).  Then the fill style is defined on the canvas context, and the gradient that is created on line 3 is added as the value of the fill (line 5).  After line 5, everything is just stored in memory, waiting to be used on a shape or path. The last line makes the gradient visible by creating a shape on which to place the gradient.

Some Notes on Gradients  The position of the gradient is relative to the canvas, not the shape (which seems a little odd at first)  To make a diagonal gradient across an entire shape, the coordinates of the gradient would be identical to the coordinates and size of the shape  The first and last colour stops in a linear gradient are represented by 0 and 1, respectively; any additional colour stops are represented by decimal values in between 0 and 1. Putting a colour stop at 50% of the object, then, would be.5.  Radial gradients are created using the createRadialGradients() method, which takes 6 arguments; the first 3 arguments create a circle for the starting point, and the last 3 create a circle for the end point

Other Methods and Properties Available 34  What I’ve discussed so far are some of the methods and properties that are easier to deal with and understand. Canvas, however, has a much broader set of tools available in its drawing API. Here’s some of what’s available, with links to appropriate parts of the spec:  Transformations, including scale and rotate Transformations  Compositing Compositing  Shadows Shadows  Complex shapes, including Bezier curves and arcs Complex shapes

Fallback Content 35  Fallback content should be used for non-supporting devices.  Fallback content is included by putting them between the opening and closing tags. E.g.:  If, for whatever reason, canvas is unavailable, the user will see the fallback.jpg image instead.  That image will not display if canvas is supported.

A Basic Code Template for Canvas 36  Mozilla’s Developer Center has a "skeleton" template for drawing canvas elements: "skeleton" template Canvas // When the window has loaded, DOM is ready. Run the draw() function. window.onload = draw; function draw(){ var canvas = document.getElementById('myCanvas'); if (canvas.getContext){ var context = canvas.getContext('2d'); // Put canvas drawing stuff here, e.g. context.fillStyle } else{ // Put code to execute if browser doesn't have canvas support here } canvas { border: 1px solid black; }

A Basic Code Template for Canvas 37  First the Javascript checks when the window has fully loaded, which means the DOM is ready to be worked on.  Secondly, it uses feature detection instead of browser sniffing to see if canvas is supported. It does this with an if/else control structure.  If canvas.getContext is not null, then we can assume canvas is supported and that it is ready to be worked on.  Otherwise (else) we can run some code in the event that canvas is not supported (such as telling the user that the page requires a browser with canvas support).

Browser and Mobile Device Support 38  If you’re going to spend the time to create some sort of fallback content, then it would be good to know the extent of browser support for the canvas element and its associated scripting.  Canvas is supported in the following browsers and devices:  Internet Explorer 9  Firefox 3.0+  Safari 3.0+  Chrome 3.0+  Opera  iPhone 1.0+  Android 1.0+

What About Internet Explorer 6-8? 39  Using a third-party library called ExplorerCanvas, canvas support is available in Internet Explorer 6 and up.ExplorerCanvas  All that’s required is to include a single JavaScript file on any page that uses the canvas element.  From my limited experience in running some example pages included with the ExploreCanvas library, IE’s rendering of canvas elements is very slow and resource- heavy, so unfortunately this workaround is not very inviting.

Why Use Canvas? 40  You might think that it’s a little counterproductive and counterintuitive to create simple objects using such complex means.  Canvas, however, should not be utilized for static object creation.  Canvas is best used for drawing objects dynamically according to user input, or for updating the display of objects that are dependent on some kind of a dynamic feed of information (such as real-time stock market fluctuations visualized through a line graph).

HTML5 Canvas Examples 41  Canvas Aquarium : A virtual fish tank in your browser using attractive fish built without any graphic files. It has realistic fish movements and bubbles. Click on the tank to add as many fish as you want! ( Canvas Aquariumhttp://10k.aneventapart.com/1/Uploads/397/  HTML5 Canvas and Audio Experiment : A little experiment that loads 100 tweets related to HTML5 and displays them using a JavaScript-based particle engine. Each particle represents a tweet click on one of them and it will appear on the screen. ( HTML5 Canvas and Audio Experiment

HTML5 Canvas Examples 42  Agent 008 Ball: The international Billiards Tournament is being infiltrated by the terrorist organization CHALK. Do not let them win! Sink as many balls as possible before the timer runs out. ( Agent 008 Ballhttp://agent8ball.com/  Canvas Cycle: This demo is an implementation of a full 8-bit colour cycling engine, rendered into a 32-bit HTML5 canvas in real-time. There are many colour cycling scenes to choose from, with some ambient environmental soundtracks to match. ( Canvas Cyclehttp://