Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save utano320/586cfba6003c439aa022 to your computer and use it in GitHub Desktop.
Save utano320/586cfba6003c439aa022 to your computer and use it in GitHub Desktop.
canvasでクリックされた位置の座標を取得・表示する
<html>
<head>
<meta charset="utf-8">
<title>canvasでクリックされた位置の座標を取得・表示する</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<div id="axisCanvasRapper">
<canvas id="axisCanvas"></canvas>
</div>
<script src="script.js"></script>
</body>
</html>
var canvas; // canvas要素(HTMLCanvasElement)
var ctx; // 2Dコンテキスト(CanvasRenderingContext2D)
var canvasW = 400; // canvas要素の横幅(px)
var canvasH = 400; // canvas要素の縦幅(px)
var mouseX; // 最後にクリックされた位置のx座標
var mouseY; // 最後にクリックされた位置のy座標
window.onload = function() {
// canvas要素を取得し、サイズ設定
canvas = document.getElementById('axisCanvas');
canvas.width = canvasW;
canvas.height = canvasH;
// 描画のために2Dコンテキスト取得
ctx = canvas.getContext('2d');
// クリックイベントの登録
canvas.onclick = function(e) {
// 一度描画をクリア
ctx.clearRect(0, 0, canvasW, canvasH);
// クリック位置の座標計算(canvasの左上を基準。-2ずつしているのはborderの分)
var rect = e.target.getBoundingClientRect();
mouseX = e.clientX - Math.floor(rect.left) - 2;
mouseY = e.clientY - Math.floor(rect.top) - 2;
// クリック位置を中心に円を描画
ctx.beginPath();
ctx.arc(mouseX, mouseY, 5, 0, Math.PI * 2, false);
ctx.fill();
// 座標の表示テキストを描画
var maxWidth = 100;
ctx.textAlign = 'right';
ctx.fillText('( ' + mouseX + ', ' + mouseY + ' )', canvasW - 20, canvasH - 20, maxWidth);
}
};
#axisCanvasRapper {
margin: 30px auto;
text-align: center;
}
#axisCanvas {
border: 1px solid #CCC;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment