javascript - 关于canvas中获取鼠标坐标的问题

查看:100
本文介绍了javascript - 关于canvas中获取鼠标坐标的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

我想做一个鼠标画线的效果 就是类似window自带的画图板那个画线的功能。这个需要获取鼠标的坐标值,但是我总感觉坐标获取得不准确,每次我在画布上画出线条的时候,线条总是在光标明显靠下的位置画出来的,而不是从光标的位置开始画线的。如果在画布的下边画线条 根本出不来,可能获取的实际坐标值超过了画布的大小了。难道是我获取坐标值的方法不对,想请教大家!

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>test</title>
    <style> body {
        background: #000;
    } </style>
    <script> window.onload = function () {
        var oC = document.getElementById('cav');
        var ctx = oC.getContext('2d');
        oC.onmousedown = function (evt) {
            var x = evt.pageX - oC.offsetLeft;
            var y = evt.pageY - oC.offsetTop;
            ctx.moveTo(x, y);
            oC.onmousemove = function (evt) {
                var x = evt.pageX - oC.offsetLeft;
                var y = evt.pageY - oC.offsetTop;
                ctx.lineTo(x, y);
                ctx.stroke();
            }
            oC.onmouseup = function () {
                oC.onmousemove = null
            }
        }
    } </script>
</head>
<body>
<canvas id="cav" style="width: 400px;height: 400px;background: white"></canvas>
</body>
</html>

解决方案

<canvas id="cav" style="width: 400px;height: 400px;background: white"></canvas>

换成

<canvas id="cav" width="400" height="400" style="background: white"></canvas>

canvas标签的width和height以及style.width和style.height的区别

这篇关于javascript - 关于canvas中获取鼠标坐标的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆