マウスクリックした画像の座標を表示しクリップボードにするJavaScript

プログラム

<!DOCTYPE html>
<html lang="ja">
<head>
    <meta charset="UTF-8">
    <title>画像クリック座標取得</title>
    <style>
        #coordinates {
            position: fixed;
            top: 10px;
            left: 50%;
            transform: translateX(-50%);
            background-color: white;
            border: 1px solid black;
            padding: 5px;
            z-index: 1000;
        }
    </style>
</head>
<body>
    <input type="file" id="fileInput">
    <br>
    <img id="uploadedImage" style="max-width: 100%; display: none;">
    <p id="coordinates" style="display: none;"></p>
    <button id="copyButton" style="display: none;">座標をコピー</button>
    <audio id="clickSound" src="click-sound.mp3"></audio> <!-- クリック音のファイルを指定 -->

    <script>
        const fileInput = document.getElementById('fileInput');
        const uploadedImage = document.getElementById('uploadedImage');
        const coordinates = document.getElementById('coordinates');
        const copyButton = document.getElementById('copyButton');
        const clickSound = document.getElementById('clickSound');

        fileInput.addEventListener('change', function(event) {
            const file = event.target.files[0];
            const reader = new FileReader();
            reader.onload = function(e) {
                uploadedImage.src = e.target.result;
                uploadedImage.style.display = 'block';
            };
            reader.readAsDataURL(file);
        });

        uploadedImage.addEventListener('click', function(event) {
            const rect = uploadedImage.getBoundingClientRect();
            const x = event.clientX - rect.left;
            const y = event.clientY - rect.top;
            const coordinatesText = `X: ${x}, Y: ${y}`;
            coordinates.textContent = coordinatesText;
            coordinates.style.display = 'block';
            copyButton.style.display = 'block';

            // クリック音を再生
            clickSound.play();

            // 座標をクリップボードにコピー
            navigator.clipboard.writeText(coordinatesText).then(function() {
                console.log('座標がクリップボードにコピーされました。');
            }, function(err) {
                console.error('座標のクリップボードへのコピーに失敗しました: ', err);
            });
        });

        copyButton.addEventListener('click', function() {
            // クリップボードにコピー
            const text = coordinates.textContent;
            navigator.clipboard.writeText(text).then(function() {
                console.log('座標がクリップボードにコピーされました。');
            }, function(err) {
                console.error('座標のクリップボードへのコピーに失敗しました: ', err);
            });
        });
    </script>
</body>
</html>
画像クリック座標取得

JavaScript

Posted by eightban