CanvasRenderingContext2D: drawFocusIfNeeded() 方法
基线 广泛可用
此功能已十分成熟,可在许多设备和浏览器版本中使用。它自 2015 年 7 月.
反馈
语法
CanvasRenderingContext2D.drawFocusIfNeeded()
方法是 Canvas 2D API 的方法,如果指定元素获得焦点,则会在当前或给定的路径周围绘制焦点环。drawFocusIfNeeded(element)
drawFocusIfNeeded(path, element)
js
参数
-
element
要检查其是否获得焦点的元素。
-
path
要使用的 Path2D
路径。
返回值
示例
无 (undefined
).
管理按钮焦点
HTML
此示例在画布上绘制两个按钮。
drawFocusIfNeeded()
方法用于在适当的时候绘制焦点环。<canvas id="canvas">
<button id="button1">Continue</button>
<button id="button2">Quit</button>
</canvas>
JavaScript
CanvasRenderingContext2D.drawFocusIfNeeded()
方法是 Canvas 2D API 的方法,如果指定元素获得焦点,则会在当前或给定的路径周围绘制焦点环。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, false);
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
规范
结果 |
---|
规范 # HTML 标准 |
浏览器兼容性
dom-context-2d-drawfocusifneeded-dev
另请参阅
- 定义此方法的接口:
CanvasRenderingContext2D