当页面向下滚动时,鼠标位置在画布中不正确

时间:2017-08-22 10:03:45

标签: javascript jquery html canvas

我有一个页面,我添加了一个画布,技术人员或客户将使用它来签名。我已经设法让它工作,并能够在画布内绘制。但是,当页面向下滚动一点时,绘图开始的位置高于鼠标点。当我再次将页面滚动回顶部时,绘图开始位置的位置再次直接在鼠标点上。

无论页面是否滚动,我如何获得正确的X和Y位置?

这就是我所做的:

HTML:

    <body onload="init();">
    <div id="dialogSignature" runat="server" style="padding-top:10px; display:none; ">
    <canvas id="myCanvas" width="400" height="200" style="border:2px solid;"></canvas>
        <img id="canvasimg" style="position:absolute;top:10%;left:52%;" style="display:none;">
    </body>


        <table>
            <tr>
                <td>
                    <input type="button" value="Clear" id="clr" size="23" onclick="erase()" class="myButton" >
                </td>
                <td>
                    <button class="myButton" onclick="javascript:UploadPic();return false;">Sumbit</button>
                </td>
            </tr>
        </table>
        <asp:Label ID="lblText" runat="server" Text="Label" Visible="false"></asp:Label>
        <asp:Label ID="lblScopeIdentity" runat="server" Text="sss" Visible="false"></asp:Label>
   </div>

使用Javascript:

    <script type="text/javascript">

    var canvas, ctx, flag = false,
        prevX = 0,
        currX = 0,
        prevY = 0,
        currY = 0,
        dot_flag = false;

    var x = "black",
        y = 2;

    function init() {
        canvas = document.getElementById('myCanvas');
        ctx = canvas.getContext("2d");
        w = canvas.width;
        h = canvas.height;

        canvas.addEventListener("mousemove", function (e) {
            findxy('move', e)
        }, false);
        canvas.addEventListener("mousedown", function (e) {
            findxy('down', e)
        }, false);
        canvas.addEventListener("mouseup", function (e) {
            findxy('up', e)
        }, false);
        canvas.addEventListener("mouseout", function (e) {
            findxy('out', e)
        }, false);

        canvas.addEventListener("touchstart", function (e) {
            mousePos = getTouchPos(canvas, e);
            var touch = e.touches[0];
            var mouseEvent = new MouseEvent("mousedown", {
                clientX: touch.clientX,
                clientY: touch.clientY
            });
            canvas.dispatchEvent(mouseEvent);
        }, false);
        canvas.addEventListener("touchend", function (e) {
            var mouseEvent = new MouseEvent("mouseup", {});
            canvas.dispatchEvent(mouseEvent);
        }, false);
        canvas.addEventListener("touchmove", function (e) {
            var touch = e.touches[0];
            var mouseEvent = new MouseEvent("mousemove", {
                clientX: touch.clientX,
                clientY: touch.clientY
            });
            canvas.dispatchEvent(mouseEvent);
        }, false);

        // Prevent scrolling when touching the canvas
        document.body.addEventListener("touchstart", function (e) {
            if (e.target == canvas) {
                e.preventDefault();
            }
        }, false);
        document.body.addEventListener("touchend", function (e) {
            if (e.target == canvas) {
                e.preventDefault();
            }
        }, false);
        document.body.addEventListener("touchmove", function (e) {
            if (e.target == canvas) {
                e.preventDefault();
            }
        }, false);
    }

    function getTouchPos(canvasDom, touchEvent) {
        var rect = canvasDom.getBoundingClientRect();
        return {
            x: touchEvent.touches[0].clientX - rect.left,
            y: touchEvent.touches[0].clientY - rect.top
        };
    }

    function color(obj) {
        switch (obj.id) {
            case "green":
                x = "green";
                break;
            case "blue":
                x = "blue";
                break;
            case "red":
                x = "red";
                break;
            case "yellow":
                x = "yellow";
                break;
            case "orange":
                x = "orange";
                break;
            case "black":
                x = "black";
                break;
            case "white":
                x = "white";
                break;
        }
        if (x == "white") y = 14;
        else y = 2;

    }

    function draw() {           
        ctx.beginPath();
        ctx.moveTo(prevX, prevY);
        ctx.lineTo(currX, currY);
        ctx.strokeStyle = x;
        ctx.lineWidth = y;
        ctx.stroke();
        ctx.closePath();
    }

    function erase() {
        var m = confirm("Want to clear");
        if (m) {
            ctx.clearRect(0, 0, w, h);
            document.getElementById("canvasimg").style.display = "none";
        }
    }

    function save() {
        document.getElementById("canvasimg").style.border = "2px solid";
        var dataURL = canvas.toDataURL();
        document.getElementById("canvasimg").src = dataURL;
        document.getElementById("canvasimg").style.display = "inline";
    }

    function findxy(res, e) {
        if (res == 'down') {
            prevX = currX;
            prevY = currY;
            currX = e.clientX - canvas.offsetLeft;
            currY = e.clientY - canvas.offsetTop;

            flag = true;
            dot_flag = true;
            if (dot_flag) {
                ctx.beginPath();
                ctx.fillStyle = x;
                ctx.fillRect(currX, currY, 2, 2);
                ctx.closePath();
                dot_flag = false;
            }
        }
        if (res == 'up' || res == "out") {
            flag = false;
        }
        if (res == 'move') {
            if (flag) {
                prevX = currX;
                prevY = currY;
                currX = e.clientX - canvas.offsetLeft;
                currY = e.clientY - canvas.offsetTop;
                draw();
            }
        }
    }

    var scopeIdentityUse = "<%=scopeIdentityJS1%>";

        var Pic = document.getElementById("myCanvas").toDataURL("image/png");
        Pic = Pic.replace(/^data:image\/(png|jpg);base64,/, "")

        $.ajax({
            type: 'POST',
            url: 'Save_Picture.aspx/UploadPic',
            data: '{ "imageData" : "' + Pic + '", "param" : "' + scopeIdentityUse + '" }',
            contentType: 'application/json; charset=utf-8',
            dataType: 'json',
            success: function (msg) {

                document.location.href = 'CreatePDFReport.aspx'
                //alert("Done, Picture Uploaded.");
            }
        });
</script>

1 个答案:

答案 0 :(得分:0)

下面是鼠标指针正确位置的更好版本。 (样式表需要在样式表中重做)....

使用Javascript:

     <script type="text/javascript">
        var canvas, ctx;
        var mouseX, mouseY, mouseDown = 0;
        var touchX, touchY;
        var lastX, lastY = -1;
        function init() {
            canvas = document.getElementById('can');
            ctx = canvas.getContext('2d');
            w = canvas.width;
            h = canvas.height;
            canvas.addEventListener('mousedown', sketchpad_mouseDown, false);
            canvas.addEventListener('mousemove', sketchpad_mouseMove, false);
            canvas.addEventListener('mouseup', sketchpad_mouseUp, false);
            canvas.addEventListener('touchstart', sketchpad_touchStart, false);
            canvas.addEventListener('touchend', sketchpad_touchEnd, false);
            canvas.addEventListener('touchmove', sketchpad_touchMove, false);


        function drawLine(ctx, x, y, size) {
            if (lastX == -1) {
                lastX = x;
                lastY = y;
            }
            r = 0; g = 0; b = 0; a = 255;
            ctx.strokeStyle = "rgba(" + r + "," + g + "," + b + "," + (a / 255) + ")";
            ctx.lineCap = "round";
            ctx.beginPath();
            ctx.moveTo(lastX, lastY);
            ctx.lineTo(x, y);
            ctx.lineWidth = size;
            ctx.stroke();
            ctx.closePath();
            lastX = x;
            lastY = y;
        }
        function sketchpad_mouseDown() {
            mouseDown = 1;
            drawLine(ctx, mouseX, mouseY, 6);
        }
        function sketchpad_mouseUp() {
            mouseDown = 0;
            lastX = -1
            lastY = -1
        }
        function sketchpad_mouseMove(e) {
            getMousePos(e);
            if (mouseDown == 1) {
                drawLine(ctx, mouseX, mouseY, 6);
            }
        }
        function getMousePos(e) {
            if (!e)
                var e = event;
            if (e.offsetX) {
                mouseX = e.offsetX;
                mouseY = e.offsetY;
            }
            else if (e.layerX) {
                mouseX = e.layerX;
                mouseY = e.layerY;
            }
        }
        function sketchpad_touchStart() {
            getTouchPos();
            drawLine(ctx, touchX, touchY, 6);
            event.preventDefault();
        }
        function sketchpad_touchEnd() {
            lastX = -1;
            lastY = -1;
        }
        function sketchpad_touchMove(e) {
            getTouchPos(e);
            drawLine(ctx, touchX, touchY, 6);
            event.preventDefault();
        }
        function getTouchPos(e) {
            if (!e)
                var e = event;
            if (e.touches) {
                if (e.touches.length == 1) {
                    var touch = e.touches[0];
                    touchX = touch.pageX - touch.target.offsetLeft;
                    touchY = touch.pageY - touch.target.offsetTop;
                }
            }
        }

        function fd_erase(elem1) {
            ctx.clearRect(0, 0, w, h);
            if (typeof elem1 != 'undefined') {
                document.getElementById(elem1).style.display = "none";
                document.getElementById(elem1).value = '';
            }
        }


        function fd_save() {
            canvas = document.getElementById('can');
            ctx = canvas.getContext('2d');
            var dataURL = canvas.toDataURL();
            document.getElementById('Signature1_img').src = dataURL;
            document.getElementById('Signature1').value = dataURL;
            document.getElementById('Hidden1').value = dataURL;
            document.getElementById('Signature1_img').style.display = "inline";
        }

在html上:

    <div style="position: absolute; width:794px; height:1122px; background-color:#FFFFFF;">
    <form runat="server" id="form1">
    <canvas id="can" Width="300px" Height="300px" style="top:108px;left:96px;color:#000000;background-color:#FFFFFF;border:1px solid #000;"></canvas>
    <input type="hidden" id="Signature1" name="Signature1" value="" >
    <input type="text" id="Hidden1" name="hndText" runat="server" value="" >
    <img id="Signature1_img" name="Signature1_img" Width="300px" Height="300px" style="color:#000000;background-color:#FFFFFF;border-style:solid;border-width:1px;border-color:#000000;display:none;">
    </form>
    </div>