Get canvas context in JavaScript

Description

The following code shows how to get canvas context.

Example


<!--from www .  j  a va2  s .  co  m-->
<!DOCTYPE HTML>
<html>
<head>
</head>
<body>
<canvas id="canvas" width="500" height="100"></canvas>
<script>
var ctx = document.getElementById("canvas").getContext("2d");
ctx.fillRect(10, 10, 50, 50);
</script>
</body>
</html>

Click to view the demo

The code above generates the following result.

Get canvas context in JavaScript