・カーソルオンの取得
<!DOCTYPE html>
<html>
<head>
<title>CANVAS TEST</title>
<script>
window.onload = function() {
const canvas = document.getElementById('test'); // 要素を得る
const ctx = canvas.getContext('2d'); // 2D(平面)コンテキストを得る
//カーソルオンのイベントを取得
function m_over_out2() {
var w = canvas.width;
var h = canvas.height;
var targetFlag = false;
var rect = null;
function onMouseOver(e) {
rect = e.target.getBoundingClientRect();
canvas.addEventListener('mousemove', onMouseMove, false);
}
function onMouseOut() {
canvas.removeEventListener('mousemove', onMouseMove, false);
}
/* マウスが動く度に要素上にヒットしているかどうかをチェック */
/* 実行するinitは間引きを噛ませて実行する */
function onMouseMove(e) {
moveActions.updateTargetFlag(e);
if (targetFlag) {
moveActions.throttle(moveActions.over, 50);
} else {
moveActions.throttle(moveActions.out, 50);
}
}
/* mouseMoveで実行する関数 */
var moveActions = {
timer: null,
/* targetFlagの更新 */
updateTargetFlag: function(e) {
var x = e.clientX - rect.left;
var y = e.clientY - rect.top;
var a = (x > w / 2 - 50);
var b = (x < w / 2 + 50);
var c = (y > h / 2 - 50);
var d = (y < h / 2 + 50);
targetFlag = (a && b && c && d);
},
/* 連続イベントの間引き */
throttle: function(targetFunc, time) {
var _time = time || 100;
clearTimeout(this.timer);
this.timer = setTimeout(function () {
targetFunc();
}, _time);
},
out: function() {
drawRect();
},
over: function() {
drawRectIsHover();
}
};
function drawRect(color) {
var _col = color || 'black';
ctx.clearRect(0, 0, w, h);
ctx.beginPath();
ctx.fillStyle = _col;
ctx.fillRect(w / 2 - 50, h / 2 - 50, 100, 100);
}
function drawRectIsHover() {
drawRect('blue');
//ctx.font = "26px 'HG正楷書体-PRO'";
//ctx.fillText('Hello', 95, 60);
}
canvas.addEventListener('mouseover', onMouseOver, false);
canvas.addEventListener('mouseout', onMouseOut, false);
drawRect();
}
m_over_out2();
}
</script>
</head>
<body>
<canvas id="test" width="300" height="300"></canvas>
</body>
</html>