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 −

  • 2d
  • webgl
  • bitmaprenderer

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 −

Html Canvas Width Property

The window alert request for the code is −

Html Canvas Width Property

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 −

Html Canvas Width Property

The window alert request for the code is −

Html Canvas Width Property
html_canvas_element.htm
Advertisements