Working with Images, Shapes, and Other Graphics - HTML5 APPLICATIONS DEVELOPMENT MANUAL (2016)

HTML5 APPLICATIONS DEVELOPMENT MANUAL (2016)

28 - Working with Images, Shapes, and Other Graphics

JavaScript can display different types of graphics, from JPG and PNG files to shapes like

boxes and circles. One method is to use thecreateElement()method as shown in chapter 26.

Manipulating the Canvas with JavaScript

Recall that the canvas element is used to create a container for graphics.

With JavaScript, you can manipulate the container and draw graphics dynamically.

To draw a canvas object, you use the getElementById() function to access the canvas and the canvas.getContext to create the object.

<!DOCTYPE html>

<html>

<head>

<title></title>

</head>

<body>

<canvas id="myCanvas" width="400" height="100" style="border:3px solid #c3c3c3;">

Your browser does not support the canvas element.

</canvas>

<script type="text/javascript">

var c = document.getElementById("myCanvas");

var ctx = c.getContext("2d");

ctx.fillStyle = "Blue";

ctx.fillRect(5, 5, 150, 75);

</script>

</body>

</html>