CanvasRenderingContext2D.drawFocusIfNeeded()

The CanvasRenderingContext2D.drawFocusIfNeeded() method of the Canvas 2D API draws a focus ring around the current path or given path, If a given element is focused.

Syntax

void ctx.drawFocusIfNeeded(element);
void ctx.drawFocusIfNeeded(path, element);

Parameters

element
The element to check whether it is focused or not.
path
A Path2D path to use.

Examples

Using the drawFocusIfNeeded method

This is just a simple code snippet which uses the drawFocusIfNeeded method.

HTML

<canvas id="canvas">
  <input id="button" type="range" min="1" max="12">
</canvas>

JavaScript

var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
var button = document.getElementById('button');

button.focus();

ctx.beginPath();
ctx.rect(10, 10, 30, 30);
ctx.drawFocusIfNeeded(button);

Edit the code below and see your changes update live in the canvas:

Playable code
<canvas id="canvas" width="400" height="200" class="playable-canvas">
<input id="button" type="range" min="1" max="12">
</canvas>
<div class="playable-buttons">
  <input id="edit" type="button" value="Edit" />
  <input id="reset" type="button" value="Reset" />
</div>
<textarea id="code" class="playable-code">
ctx.beginPath();
ctx.rect(10, 10, 30, 30);
ctx.drawFocusIfNeeded(button);</textarea>
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var textarea = document.getElementById("code");
var button = document.getElementById("button");
var reset = document.getElementById("reset");
var edit = document.getElementById("edit");
var code = textarea.value;
button.focus();

function drawCanvas() {
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  eval(textarea.value);
}

reset.addEventListener("click", function() {
  textarea.value = code;
  drawCanvas();
});

edit.addEventListener("click", function() {
  textarea.focus();
})

textarea.addEventListener("input", drawCanvas);
window.addEventListener("load", drawCanvas);

Specifications

Specification Status Comment
HTML Living Standard
The definition of 'CanvasRenderingContext2D.drawFocusIfNeeded' in that specification.
Living Standard Initial definition

Browser compatibility

FeatureChromeEdgeFirefoxInternet ExplorerOperaSafari
Basic support Yes ?

32

291

282

No Yes Yes
Path parameter Yes ? No No Yes Yes
FeatureAndroid webviewChrome for AndroidEdge mobileFirefox for AndroidOpera AndroidiOS SafariSamsung Internet
Basic support Yes Yes ?

32

291

282

Yes Yes Yes
Path parameter Yes Yes ? No Yes Yes Yes

1. From version 29: this feature is behind the canvas.focusring.enabled preference. To change preferences in Firefox, visit about:config.

2. Supported as drawSystemFocusRing.

See also

Document Tags and Contributors

Contributors to this page: fscholz, nmve, Sebastianz
Last updated by: fscholz,