canvas获取鼠标坐标

如题,废话不多说。

demo截图:

源代码:

<html>
<head>
    <title></title>
    <script>
    window.onload=function(){
        var canvas = document.getElementById("demoCanvas");
        var ctx = canvas.getContext("2d");
        var x,y;

        canvas.addEventListener("mousemove", function(e){
            var sw = (canvas.style.width.replace(/\px/g, ""))| 0,
                sh = (canvas.style.height.replace(/\px/g, ""))|0;

            if(e.pageX || e.pageY) {
                x = e.pageX;
                y = e.pageY;
            }else{
                x = e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;
                y = e.clientY + document.body.scrollTop + document.documentElement.scrollTop;
            }

            x -= canvas.offsetLeft;
            y -= canvas.offsetTop;

            if(sw) x *= canvas.width / sw;
            if(sh) y *= canvas.height / sh;
            x |= 0;
            y |= 0;

            ctx.clearRect(0,0,800,600);
            ctx.fillText("Mouse: X-"+x+",Y-"+y,100,100);
        },false);
    };
    </script>
</head>
<body>
    <canvas id="demoCanvas" width="800" height="600" style="background:#66ccdd;"></canvas>
</body>
</html>

 

posted @ 2014-02-21 11:12  Joy Ho  阅读(2765)  评论(0编辑  收藏  举报