Presentation is loading. Please wait.

Presentation is loading. Please wait.

Drawing Graphics in JavaScript

Similar presentations


Presentation on theme: "Drawing Graphics in JavaScript"— Presentation transcript:

1 Drawing Graphics in JavaScript

2 Topics <canvas> element The canvas context
The canvas coordinate system Basic Usage: Drawing Rectangles Drawing paths strokeStyle() and fillStyle

3 <canvas> element
Used to draw graphics on web pages via JavaScript. Added in HTML5 <canvas> was originally introduced by Apple for the OS X Dashboard and Safari. <canvas> element has only two attributes: width and height.

4 The canvas context The <canvas> element creates a fixed-size drawing surface. Other contexts may exist that provide different types of rendering, such OpenGL. To display something, a script first needs to access the canvas context. <body> <canvas id=“drawingBoard” width=“500” height=“600”> </canvas> </body> var canvas = document.getElementById('drawingBoard'); var canvasContext = canvas.getContext('2d'); HTML JavaScript

5 Canvas Coordinate System
The 0,0 coordinate is positioned in the top left corner.

6 Drawing Rectangles <canvas> only supports rectangles and lines
Non-rectangular shapes must be created using lines functions that draw rectangles on a canvas: fillRect(x, y, width, height) Draws a filled rectangle. strokeRect(x, y, width, height) Draws a rectangular outline. clearRect(x, y, width, height) Clears a rectangular area

7 Drawing Paths A path is a collection of line segments.
moveTo(), lineTo(), and arc() are used to create line segments. Example: canvasContext.beginPath(); canvasContext.moveTo(25, 25); canvasContext.lineTo(105, 25); canvasContext.lineTo(25, 105); canvasContext.fill(); canvasContext.closePath();

8 Drawing Paths Example 2 var startPt = 0; var endPt = 2 * Math.PI; canvasContext.beginPath(); canvasContext.arc(25, 25, beginPt, endPt); canvasContext.fill(); canvasContext.closePath();

9 fillStyle() and strokeStyle()
fillStyle = color Sets the style used when filling shapes. strokeStyle = color Sets the style for shapes' outlines. By default, the stroke and fill color are set to black (#000000). A newly set strokeStyle and/or fillStyle property becomes the default for all shapes. Example: canvasContext.fillStyle = “blue”; canvasContext.strokeStyle = “#034AAD”;

10 Exercise 1: Write the HTML and JavaScript to produce the image shown below.

11 Exercise 2: Write the HTML and JavaScript to produce the image shown below.


Download ppt "Drawing Graphics in JavaScript"

Similar presentations


Ads by Google