HTML Canvas - drawFocusIfNeeded() Method



The HTML Canvas drawFocusIfNeeded() method of CanvasRenderingContext2D interface from the Canvas 2D API adds focus to the existing path or a given path when provided.

Syntax

Following is the syntax of HTML Canvas drawFocusIfNeeded() method −

CanvasRenderingContext2D.drawFocusIfNeeded(given_path, element);

Parameters

Following is the list of parameters of this method −

S.No Parameters and Description
1 given_path

The available path in the canvas to use.

2 element

The current element in canvas to check if it is focused or not.

Return Value

For an existing path or a new path, its elements are focused and returned by using the above method.

Example

The following example adds focus to the rectangular button when needed using HTML Canvas drawFocusIfNeeded() method.

<!DOCTYPE html>
<html lang="en">
<head>
   <title>Reference API</title>
   <style>
      body {
         margin: 10px;
         padding: 10px;
      }
   </style>
</head>
<body onload="Context();">
   <canvas id="canvas" width="300" height="200" style="border: 1px solid black;">
      <input id="button" type="range" min="1" max="10">
   </canvas>
   <script>
      function Context() {
         var canvas = document.getElementById("canvas");
         var context = canvas.getContext("2d");
         var button = document.getElementById("button");
         button.focus();
         context.beginPath();
         context.rect(20, 20, 100, 75);
         context.drawFocusIfNeeded(button);
      }
   </script>
</body>
</html>

Output

The output returned by the above code on the webpage as −

HTML Canvas DrawFocusIfNeeded method

Example

The following example adds focus to the circle button when needed.

<!DOCTYPE html>
<html lang="en">
<head>
   <title>Reference API</title>
   <style>
      body {
         margin: 10px;
         padding: 10px;
      }
   </style>
</head>
<body onload="Context();">
   <canvas id="canvas" width="300" height="200" style="border: 1px solid black;">
      <input id="button" type="range" min="1" max="10">
   </canvas>
   <script>
      function Context() {
         var canvas = document.getElementById("canvas");
         var context = canvas.getContext("2d");
         var button = document.getElementById("button");
         button.focus();
         context.beginPath();
         context.arc(100, 100, 75, 0, 2 * Math.PI);
         context.drawFocusIfNeeded(button);
      }
   </script>
</body>
</html>

Output

The output returned by the above code on the webpage as −

HTML Canvas DrawFocusIfNeeded method
html_canvas_paths.htm
Advertisements