Skip to content

Commit 1833dc9

Browse files
committed
Add snippets for mouse canvas events
1 parent 25dc12b commit 1833dc9

File tree

2 files changed

+89
-0
lines changed

2 files changed

+89
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
---
2+
title: "Canvas mouse event"
3+
weight: 80
4+
ie_support: true
5+
---
6+
7+
Use this snippet to click on an area within a canvas element.
8+
9+
Replace the values in the code as needed.
10+
11+
```js
12+
// Replace this with your desired CSS selector
13+
var selector = "Selector here";
14+
15+
// Find the element
16+
var element = document.querySelector(selector);
17+
18+
if (!element) {
19+
throw new Error("Error: cannot find the element with selector (" + selector + ").");
20+
}
21+
22+
// Get the element's position and size
23+
var rect = element.getBoundingClientRect();
24+
25+
// Change this to the xy click coordinates you need to target
26+
var clickX = rect.left + rect.width / 4;
27+
var clickY = rect.top + rect.height / 4;
28+
29+
// List of mouse events to dispatch
30+
// Remove the mouse events that are not relevant
31+
var mouseEvents = ['mouseover', 'mouseenter', 'mousedown', 'mouseup', 'click', 'dblclick', 'mouseout'];
32+
33+
// Dispatch each event
34+
mouseEvents.forEach(function(eventType) {
35+
var event = new MouseEvent(eventType, {
36+
bubbles: true,
37+
cancelable: true,
38+
clientX: clickX,
39+
clientY: clickY
40+
});
41+
42+
element.dispatchEvent(event);
43+
});
44+
```
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
---
2+
title: "キャンバスのマウスイベント"
3+
weight: 80
4+
ie_support: true
5+
---
6+
7+
このスニペットを使用して、`canvas` 要素内の特定の領域をクリックできます。
8+
9+
必要に応じてコード内の値を変更してください。
10+
11+
12+
```js
13+
// 使用したい CSS セレクターをここに指定します
14+
var selector = "Selector here";
15+
16+
// 要素を取得
17+
var element = document.querySelector(selector);
18+
19+
if (!element) {
20+
throw new Error("Error: cannot find the element with selector (" + selector + ").");
21+
}
22+
23+
// 要素の位置とサイズを取得
24+
var rect = element.getBoundingClientRect();
25+
26+
// 対象としたいクリック位置の座標を指定(ここでは要素の1/4の位置)
27+
var clickX = rect.left + rect.width / 4;
28+
var clickY = rect.top + rect.height / 4;
29+
30+
// 発火させるマウスイベントの一覧
31+
// 不要なマウスイベントは削除してください
32+
var mouseEvents = ['mouseover', 'mouseenter', 'mousedown', 'mouseup', 'click', 'dblclick', 'mouseout'];
33+
34+
// 各イベントを順に発火させる
35+
mouseEvents.forEach(function(eventType) {
36+
var event = new MouseEvent(eventType, {
37+
bubbles: true,
38+
cancelable: true,
39+
clientX: clickX,
40+
clientY: clickY
41+
});
42+
43+
element.dispatchEvent(event);
44+
});
45+
```

0 commit comments

Comments
 (0)