canvas坐标拾取器

时间:2022-06-03 17:10:54
<script type="text/javascript">
    window.onload = function () {
        var canvas = document.getElementById("myCanvas");
        canvas.onclick = function (event) {
            var loc = windowTocanvas(canvas, event.clientX, event.clientY)
            var x = parseInt(loc.x);
            var y = parseInt(loc.y);
            alert('clientX:'+event.clientX+',clientY:'+event.clientY+'\n\r'+'x:'+x+',y:'+y);
        }
    }

    function windowTocanvas(canvas, x, y) {
        var bbox = canvas.getBoundingClientRect();
        return {
            x: x - bbox.left * (canvas.width / bbox.width),
            y: y - bbox.top * (canvas.height / bbox.height)
        };
    }
</script>