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

时间:2011-11-04 16:31:30

标签: javascript jquery html5 canvas

对于'招牌垫'有一个奇怪的问题我正在为就业申请建立......

问题在于,当您在画布的左侧时,正在绘制的线条和光标对齐...当您向右侧移动时,正在绘制的X和弦以及光标的x和弦排队。当你从左向右移动时,两者之间的差异会增大。在处理Firefox时,我的代码'*'中没有乘法减法。

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>-->

签名/绘图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);
}

重置签名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();
}

保存签名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);
}

最后是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;
}

我只是找不到导致X颂歌方差成倍增长的因素...... Y合唱团一直很好而且没有变化。把头发拉到这里!!!

编辑:我包括图像,向您展示我所说的大(r)黑点是光标的近似位置,顶部图像几乎是点上的,底部图像可以看到光标它远离它应该的左侧。

Image showing correct cursor position towards left of canvas

Image showing incorrect cursor position towards right of canvas

编辑2:根据要求,这已被放入jsFiddle ... HERE

3 个答案:

答案 0 :(得分:3)

您必须使用canvas.width和canvas.height来调整画布大小, CSS宽度/高度。

这里你只是伸展画布:

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

你不想这样做。

这里修好了:

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

答案 1 :(得分:1)

我同意Simon Sarris的回答,还有一个额外的细节。如果您不想指定画布高度和宽度并希望它获取父级的高度,那么为了避免您的绘图偏离感兴趣的点,在init函数中添加以下代码行

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

此外,为了计算准确的ev._x和ev._y,请阅读这篇文章,当文档结构复杂时它很有用

Tracking mouse position in canvas when no surrounding element exists

答案 2 :(得分:0)

添加滚动顶部并向左滚动,因为在滚动时我们应该添加这些因素。尝试以下代码,它可能对您有所帮助。

<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>