What is getContext in HTML5 Canvas?

JavascriptWeb DevelopmentFront End Scripts

The canvas element has a DOM method called getContext, used to obtain the rendering context and its drawing functions. This function takes one parameter, the type of context 2d.

Following is the code to get required context along with a check if your browser supports <canvas> element:

var canvas = document.getElementById("mycanvas");
if (canvas.getContext){
   var ctx = canvas.getContext('2d');

   // drawing code here
   } else {

   // canvas-unsupported code here
Updated on 28-Jan-2020 08:30:13