简体   繁体   English

HTML5画布绘图应用程序... x,y正确,但绘图已关闭

[英]HTML5 canvas drawing application…x,y correct, but drawing is off

Have an odd problem with a 'Signature Pad" I'm building for an employment application... 我正在为就业申请建立一个'签名垫'有一个奇怪的问题...

The issue is that when you are at the left side of the canvas the line being drawn and the cursor line up...as you move towards the right side the the X chord being draw and the x chord of the cursor don't line up. 问题在于,当您在画布的左侧时,正在绘制的线条和光标对齐...当您向右侧移动时,正在绘制的X和弦和光标的x和弦不对齐起来。 The difference between the two grows as you move from left to right. 当你从左向右移动时,两者之间的差异会增大。 I have no multiplication in my code '*' only subtraction when dealing with Firefox. 在处理Firefox时,我的代码'*'中没有乘法减法。

HTML I did leave the other scripts/divs that will most likely be used once launched in there so you can see full code...I'm also including the js for those even though they should have no effect at the moment. HTML 我确实留下了其他脚本/ div,这些脚本/ div最有可能在那里发布后使用,所以你可以看到完整的代码......我也包括那些js,尽管它们现在应该没有效果。

<div id="container">
    <canvas id="imageView">
        <p>
            Unfortunately, your browser is currently unsupported by our web 
            application.  We are sorry for the inconvenience. Please use one of the 
            supported browsers listed below, or fill out a paper Signature release.
        </p>
        <p>
            Supported browsers:<br /> 
            <a href="http://www.opera.com/browser/download/">Opera Browser</a> 
            <a href="http://www.mozilla.org/en-US/firefox/features/">Firefox</a>
            <a href="http://www.apple.com/safari/download/">Safari</a>
            <a href="http://www.konqueror.org/download/">Konqueror (Linux PC)</a>
        </p>
    </canvas><!--
    <div id="SigCover"></div>
    <div id="SigCoverText"><span><br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Signature Saved</span></div>
    <div class="ClearBoth"></div>-->
</div>
<form action="">
    <input type="button" value="Save Signature" onclick="SaveImage()" />
    <input type="button" value="Reset Signature" onclick="ResetSignature()" />
</form>
<div id="ImageToSave"></div>
<!--<script type="text/javascript" src="@Url.Content("~/Scripts/Signature/canvas2image.js")"></script>-->
<script type="text/javascript" src="@Url.Content("~/Scripts/Signature/Signature.js")"></script><!--
<script type="text/javascript" src="@Url.Content("~/Scripts/Signature/SaveSignature.js")"></script>
<script type="text/javascript" src="@Url.Content("~/Scripts/Signature/ResetSignature.js")"></script>-->

Signature/Drawing js... 签名/绘图js ...

var points = new Array();
if (window.addEventListener) {
    window.addEventListener('load', function () {
        var canvas, context, tool;

        function init() {
            // Find the canvas element.
            canvas = document.getElementById('imageView');
            if (!canvas) {
                alert('Error: I cannot find the canvas element!');
                return;
            }

            if (!canvas.getContext) {
                alert('Error: no canvas.getContext!');
                return;
            }

            // Get the 2D canvas context.
            context = canvas.getContext('2d');
            if (!context) {
                alert('Error: failed to getContext!');
                return;
            }

            // Pencil tool instance.
            tool = new tool_pencil();

            // Attach the mousedown, mousemove and mouseup event listeners.
            canvas.addEventListener('mousedown', ev_canvas, false);
            canvas.addEventListener('mousemove', ev_canvas, false);
            canvas.addEventListener('mouseup', ev_canvas, false);
        }

        // This painting tool works like a drawing pencil which tracks the mouse 
        // movements.
        function tool_pencil() {
            var tool = this;
            this.started = false;

            // This is called when you start holding down the mouse button.
            // This starts the pencil drawing.
            this.mousedown = function (ev) {
                context.beginPath();
                context.moveTo(ev._x, ev._y);
                tool.started = true;
            };

            // This function is called every time you move the mouse. Obviously, it only 
            // draws if the tool.started state is set to true (when you are holding down 
            // the mouse button).
            this.mousemove = function (ev) {
                if (tool.started) {
                    context.lineTo(ev._x, ev._y);
                    context.stroke();
                }
            };

            // This is called when you release the mouse button.
            this.mouseup = function (ev) {
                if (tool.started) {
                    tool.mousemove(ev);
                    tool.started = false;
                }
            };
        }
        // The general-purpose event handler. This function just determines the mouse 
        // position relative to the canvas element.
        function ev_canvas(ev) {
            if (navigator.appName == 'Microsoft Internet Explorer' || navigator.vendor == 'Google Inc.' || navigator.vendor == 'Apple Computer, Inc.') { // IE or Chrome
                ev._x = ev.offsetX;
                ev._y = ev.offsetY;
            } else if (ev.layerX || ev.layerX == 0) { // Firefox
                ev._x = ev.layerX - this.offsetLeft;
                ev._y = ev.layerY - this.offsetTop;
            } else if (ev.offsetX || ev.offsetX == 0) { // Opera
                ev._x = ev.offsetX;
                ev._y = ev.offsetY;
            }
            // Call the event handler of the tool.
            var func = tool[ev.type];
            if (func) {
                func(ev);
            }
            points.push(ev);
        }

        init();

    }, false);
}

Reset Signature js... 重置签名js ...

function ResetSignature() {
    var canvasReset = document.getElementById('imageView');
    var contextReset = canvasReset.getContext('2d');

    contextReset.fillStyle = '#000000';
    contextReset.fillRect(0, 0, $('imageView').css('width'), $('imageView').css('height'));
    canvasReset.width = canvasReset.width;
    canvasReset.width = canvasReset.width;

    alert(points.length);
    points = new Array();
}

Save Signature js (uses Canvas2Image lib) 保存签名js(使用Canvas2Image lib)

function SaveImage() {
    var CanvasToSave = document.getElementById('imageView');

    var oImg = Canvas2Image.saveAsPNG(CanvasToSave, true);

    $('#ImageToSave').html(oImg);

    $('#SigCover').css('z-index', 102);
    $('#SigCover').css('left', 23);
    $('#SigCover').css('width', 402);
    $('#SigCover').css('height', 152);
    $('#SigCoverText').css('z-index', 101);
    $('#SigCoverText').css('left', 23);
    $('#SigCoverText').css('width', 400);
    $('#SigCoverText').css('height', 150);
    alert(points.length);
}

Lastly the CSS 最后是CSS

#imageView
{
    background-color: #FFFFFF;
    width: 400px;
    height: 150px;
    z-index: 100;
}/*

#SigCover
{
    background-color: Gray;
    opacity: .5;
    width: 0px;
    height: 0px;
    position: absolute;
    top: 57px;
    left: -4000px;
    z-index: -1;
    float: left;
}

#SigCoverText
{
    background-color: Gray;
    opacity: .5;
    width: 0px;
    height: 0px;
    position: absolute;
    top: 57px;
    left: -4000px;
    z-index: -1;
    float: left;
}

I just can't find what is causing the X choord variance to exponentially grow like it is...the Y choord is fine throughout and has no variance. 我只是找不到导致X choord方差成倍增长的因素...... Y合唱团一直很好而且没有变化。 Pulling my hair out here!!! 把头发拉到这里!!!

EDIT: I'm including images to show you what I'm talking about the large(r) black dots are the approx location of cursor the top image is pretty much spot on and the bottom image you can see that the cursor is far to the left of where it should be. 编辑:我包括图像,以显示我在说什么大(r)黑点是光标的大致位置顶部图像几乎是点上,底部图像,你可以看到光标是远的应该在哪里的左边。

图像显示正确的光标位置朝向画布的左侧

图像显示不正确的光标位置朝向画布右侧

EDIT 2: As requested this has been put into jsFiddle... HERE 编辑2:根据要求,这已被放入jsFiddle ... 这里

You have to use canvas.width and canvas.height to size your canvas, NOT CSS width/height. 您必须使用canvas.width和canvas.height来调整画布大小,而不是 CSS宽度/高度。

Here you are merely stretching the canvas: 在这里你只是拉伸画布:

#imageView
{
    background-color: #FFFFFF;
    width: 400px;
    height: 150px;
    z-index: 100;
}

And you do not want to do that. 你不想那样做。

Here it is fixed: 这是固定的:

http://jsfiddle.net/KtuRA/5/ http://jsfiddle.net/KtuRA/5/

I agree with the Simon Sarris answer with one additional detail. 我同意Simon Sarris的回答,还有一个额外的细节。 Just in case you do not want to specify canvas height and width and want it to take the height of the parent, then to refrain your drawings to be off the point of interest, add following line of code in init function 如果您不想指定画布高度和宽度并希望它获取父级的高度,那么为了避免您的绘图偏离感兴趣的点,在init函数中添加以下代码行

canvas.width = canvas.offsetWidth;
canvas.height = canvas.offsetHeight;

Furthermore for calculating accurate ev._x and ev._y, do read this post, its helpful when document structure is complex 此外,为了计算准确的ev._x和ev._y,请阅读这篇文章,当文档结构复杂时,它很有用

Tracking mouse position in canvas when no surrounding element exists 当没有周围元素时,在画布中跟踪鼠标位置

Add the scroll Top and scroll Left,because at the time of scrolling we should add these factors. 添加滚动顶部并向左滚动,因为在滚动时我们应该添加这些因素。 Try the below code it could be helpful for you. 尝试以下代码,它可能对您有所帮助。

<html>
    <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('can');
        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);
    } 
    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();
                    }
                }
    }

    </script>

    <body onload="init()">
            <canvas id="can" width="400"height="400" style="position:absolute;top:10%;left:10%;border:2px solid;"></canvas>

            <div style="position:absolute;top:12%;left:43%;">Choose Color</div>
            <div style="position:absolute;top:15%;left:45%;width:10px;height:10px;background:green;" id="green" onclick="color(this)"></div>
            <div style="position:absolute;top:15%;left:46%;width:10px;height:10px;background:blue;" id="blue" onclick="color(this)"></div>
            <div style="position:absolute;top:15%;left:47%;width:10px;height:10px;background:red;" id="red" onclick="color(this)"></div>
            <div style="position:absolute;top:17%;left:45%;width:10px;height:10px;background:yellow;" id="yellow" onclick="color(this)"></div>
            <div style="position:absolute;top:17%;left:46%;width:10px;height:10px;background:orange;" id="orange" onclick="color(this)"></div>
            <div style="position:absolute;top:17%;left:47%;width:10px;height:10px;background:black;" id="black" onclick="color(this)"></div>
            <div style="position:absolute;top:20%;left:43%;">Eraser</div>
            <div style="position:absolute;top:22%;left:45%;width:15px;height:15px;background:white;border:2px solid;" id="white" onclick="color(this)"></div>

            <img id="canvasimg"style="position:absolute;top:10%;left:52%;" style="display:none;">
        <input type="button" value="save" id="btn" size="30" onclick="save()"style="position:absolute;top:55%;left:10%;">
        <input type="button" value="clear" id="clr" size="23" onclick="erase()"style="position:absolute;top:55%;left:15%;">
    </body>
</html>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM