- HTML Canvas - Home
- HTML Canvas - Introduction
- Environmental Setup
- HTML Canvas - First Application
- HTML Canvas - Drawing 2D Shapes
- HTML Canvas - Path Elements
- 2D Shapes Using Path Elements
- HTML Canvas - Colors
- HTML Canvas - Adding Styles
- HTML Canvas - Adding Text
- HTML Canvas - Adding Images
- HTML Canvas - Canvas Clock
- HTML Canvas - Transformations
- Composting and Clipping
- HTML Canvas - Basic Animations
- Advanced Animations
- HTML Canvas API Functions
- HTML Canvas - Element
- HTML Canvas - Rectangles
- HTML Canvas - Lines
- HTML Canvas - Paths
- HTML Canvas - Text
- HTML Canvas - Colors and Styles
- HTML Canvas - Images
- HTML Canvas - Shadows and Transformations
- HTML Canvas Useful Resources
- HTML Canvas - Quick Guide
- HTML Canvas - Useful Resources
- HTML Canvas - Discussion
HTML Canvas - getContext() Method
The HTML Canvas getContext() method is used to get/retrieve the context object. This method accepts a string variable as a parameter specifying the desired context.
In case of failure this method returns NULL (If the specified context is not supported). This method belongs to the HTMLCanvasElement interface. We cannot draw a shape of different context as mentioned by the method.
Syntax
Following is the syntax of the HTML Canvas getContext() method −
HTMLCanvasElement.getContext(context_type);
Parameters
Following is the parameter of this method −
| S.No | Parameter & Description |
|---|---|
| 1 |
context_type It takes a string containing context identifier of the Canvas element. The values accepted by the parameter are −
|
Example
The following code sets the context of the Canvas element to 2D using the HTML Canvas getContext() method and is returned by the window alert.
<!DOCTYPE html>
<html lang="en">
<head>
<title>Reference API</title>
<style>
body {
margin: 10px;
padding: 10px;
}
</style>
</head>
<body>
<canvas id="canvas" height="300" style="border: 1px solid black;"></canvas>
<script>
var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');
window.alert("The selected context for the Canvas is - " + context);
</script>
</body>
</html>
Output
The canvas formed by the above code on the webpage is −
The window alert request for the code is −
Example
The following code sets the context of the Canvas element by giving a random string and the object context is returned by the window alert.
<!DOCTYPE html>
<html lang="en">
<head>
<title>Reference API</title>
<style>
body {
margin: 10px;
padding: 10px;
}
</style>
</head>
<body>
<canvas id="canvas" height="200" style="border: 1px solid black;"></canvas>
<script>
var canvas = document.getElementById('canvas');
var context = canvas.getContext('shapes');
window.alert("The selected context for the Canvas is - " + context);
</script>
</body>
</html>
Output
The canvas formed by the above code on the webpage is −
The window alert request for the code is −