CanvasRenderingContext2D: drawFocusIfNeeded() 方法

Baseline 廣泛可用 *

此功能已相當成熟,可在多種裝置和瀏覽器版本上執行。自 ⁨2016 年 8 月⁩ 起,所有瀏覽器均已提供此功能。

* 此特性的某些部分可能存在不同級別的支援。

CanvasRenderingContext2D.drawFocusIfNeeded() 方法是 Canvas 2D API 的一部分,它會在當前路徑或指定路徑周圍繪製一個焦點環,前提是指定的元素處於焦點狀態。

語法

js
drawFocusIfNeeded(element)
drawFocusIfNeeded(path, element)

引數

element

需要檢查其焦點狀態的元素。

路徑

用於繪製的 Path2D 路徑。

返回值

無(undefined)。

示例

管理按鈕焦點

此示例在畫布上繪製兩個按鈕。drawFocusIfNeeded() 方法用於在適當時繪製焦點環。

HTML

html
<canvas id="canvas">
  <button id="button1">Continue</button>
  <button id="button2">Quit</button>
</canvas>

JavaScript

js
const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");
const button1 = document.getElementById("button1");
const button2 = document.getElementById("button2");

document.addEventListener("focus", redraw, true);
document.addEventListener("blur", redraw, true);
canvas.addEventListener("click", handleClick);
redraw();

function redraw() {
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  drawButton(button1, 20, 20);
  drawButton(button2, 20, 80);
}

function handleClick(e) {
  // Calculate click coordinates
  const x = e.clientX - canvas.offsetLeft;
  const y = e.clientY - canvas.offsetTop;

  // Focus button1, if appropriate
  drawButton(button1, 20, 20);
  if (ctx.isPointInPath(x, y)) {
    button1.focus();
  }

  // Focus button2, if appropriate
  drawButton(button2, 20, 80);
  if (ctx.isPointInPath(x, y)) {
    button2.focus();
  }
}

function drawButton(el, x, y) {
  const active = document.activeElement === el;
  const width = 150;
  const height = 40;

  // Button background
  ctx.fillStyle = active ? "pink" : "lightgray";
  ctx.fillRect(x, y, width, height);

  // Button text
  ctx.font = "15px sans-serif";
  ctx.textAlign = "center";
  ctx.textBaseline = "middle";
  ctx.fillStyle = active ? "blue" : "black";
  ctx.fillText(el.textContent, x + width / 2, y + height / 2);

  // Define clickable area
  ctx.beginPath();
  ctx.rect(x, y, width, height);

  // Draw focus ring, if appropriate
  ctx.drawFocusIfNeeded(el);
}

結果

規範

規範
HTML
# dom-context-2d-drawfocusifneeded-dev

瀏覽器相容性

另見