无法获取HTML5画布签名板提交到数据库 [英] Can't get html5 Canvas signature pad to submit to database

查看:103
本文介绍了无法获取HTML5画布签名板提交到数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,我一直在寻找周为一个签名捕获脚本,实际工作,将节省的签名MySQL和我终于找到了我想要的,但有2个问题。

  1. 我不明白,为什么在画布不会清除签名时清除按钮是pressed。

  2. 它不会图像提交给MySQL时保存签名按钮是pressed。

这code是pretty的老,我一直试图联系开发商,但还没有得到答复回来,我希望我可以在这里得到一些帮助。

下面是HTML:

 <!DOCTYPE HTML PUBLIC -  // W3C // DTD XHTML 1.0过渡// ENhttp://www.w3.org/TR/xhtml1/DTD/ XHTML1-transitional.dtd>
    < HTML的xmlns =htt​​p://www.w3.org/1999/xhtml>

    < HEAD>
    < META CONTENT =text / html的;字符集= UTF-8HTTP-EQUIV =Content-Type的/>
    <冠军>签名板< /标题>
    <脚本类型=文/ JavaScript的SRC =jquery.min.js>< / SCRIPT>
    < /头>
    <身体GT;
    <中心>
        <字段集的风格=宽度:435px>
            < BR />
            < BR />
            < D​​IV ID =signaturePad的风格=边界:1px的固体#ccc;高度:55像素;宽度:400像素;>< / DIV>
            < BR />
            <按钮ID =clearSig类型=按钮>清除签名< /按钮>&安培; NBSP;
            <按钮ID =saveSig类型=按钮>保存签名< /按钮>
            < D​​IV ID =imgData>< / DIV>
            < D​​IV ID =imgData>< / DIV>
            < BR />
            < BR />
        < /字段集>
    < /中心>
    < /身体GT;
    < / HTML>
 

和剩余的PHP和脚本:

  $(文件)。就绪(函数(){
    / **设置画布大小** /
    VAR canvasWidth = 400;
    VAR canvasHeight = 75;

    / ** IE支持** /
    变种canvasDiv =的document.getElementById('signaturePad');
    帆布= document.createElement方法('画布');
    canvas.setAttribute('宽',canvasWidth);
    canvas.setAttribute(高度,canvasHeight);
    canvas.setAttribute('身份证','画布');
    canvasDiv.appendChild(画布);
    如果(typeof运算G_vmlCanvasManager!='不确定'){
        帆布= G_vmlCanvasManager.initElement(画布);
    }
    上下文= canvas.getContext(2D);

    VAR clickX =新的Array();
    VAR clickY =新的Array();
    VAR clickDrag =新的Array();
    VAR漆;

    / **重绘帆布** /
    功能重绘(){
        canvas.width = canvas.width; //清除画布

        context.strokeStyle =#000000;
        context.lineJoin =斜切;
        context.lineWidth = 2;

        对于(VAR I = 0; I< clickX.length;我++){
            context.beginPath();
            如果(clickDrag [1]  - 安培;&安培;我){
                context.moveTo(clickX [我 -  1],clickY [我 -  1]);
            } 其他 {
                context.moveTo(clickX [I]  -  1,clickY [I]);
            }
            context.lineTo(clickX [I],clickY [I]);
            context.closePath();
            context.stroke();
        }
    }

    / **保存帆布** /
    $(#saveSig)。点击(函数saveSig(){
        VAR sigData = canvas.toDataURL(图像/ PNG);
        $(#imgData)HTML('谢谢你的签名保存!')。
        VAR阿贾克斯= XMLHtt prequest();
        ajax.open(POST,http://www.your-domain.com/folder/post-html.php');
        ajax.setRequestHeader(内容类型,应用程序/上传);
        ajax.send(sigData);
    });

    / **清除帆布** /
    传播clearSig(){
        clickX =新的Array();
        clickY =新的Array();
        clickDrag =新的Array();
        canvas.width = canvas.width;
        canvas.height = canvas.height;
    }

    / **动过当画布绘制** /
    $('#signaturePad)。鼠标移动(功能(E){
        如果(油漆){
            添加点击(e.pageX  -  this.offsetLeft,e.pageY  -  this.offsetTop,真正的);
            重绘();
        }
    });

    / **停止绘制的鼠标松开** /
    $('#signaturePad)。鼠标松开(功能(E){
        油漆= FALSE;
    });

    / **启动点击** /
    功能添加点击(X,Y,拖){
        clickX.push(X);
        clickY.push(Y);
        clickDrag.push(拖拽);
    }

    $('#signaturePad)。的mousedown(功能(E){
        VAR mouseX = e.pageX  -  this.offsetLeft;
        VAR mouseY的= e.pageY  -  this.offsetTop;

        油漆= TRUE;
        添加点击(e.pageX  -  this.offsetLeft,e.pageY  -  this.offsetTop);
        重绘();
    });

});
 

MySQL的部分:

 < PHP
如果(使用isset($ GLOBALS [HTTP_RAW_POST_DATA]))
{
$ SESSION_ID = $ _ SERVER ['REMOTE_ADDR'];
//获取数据
$为imageData = $ GLOBALS ['HTTP_RAW_POST_DATA'];

//删除标题(数据:,)的一部分。
//实际的应用程序应根据需要,如检查图像类型使用它们
$ filteredData = SUBSTR($为imageData,strpos($为imageData,,)+ 1);

//需要节省,因为我们收到的数据已经Base64的EN codeD之前取消code
$ unen codedData = base64_de code($ filteredData);

//回声unen codedData$ unen codedData。
$ imageName =sign_。兰特(5,1000)。兰特(1,10)。兰德(10000,150000)。兰特(1500亿)。 .png格式;
//设置绝对路径的文件夹(如/ usr /家庭/您的域/您的文件夹/
$文件路径=的htdocs /阿尔法/ site6 /签名/图片/。 $ imageName;

$计划生育=的fopen($文件路径,世行);
FWRITE($计划生育,$ unen codedData);
fclose函数($ FP);

//连接到MySQL数据库和存储用户的信息,以便您可以在以后链接到它
$链接=的mysql_connect('本地主机','根','PWD')或死亡(mysql_error);
mysql_select_db(审判,$链接);
请求mysql_query(INSERT INTO客户(`session`,`image_location`)VALUES('$ session_id的','$ imageName'))或死亡(mysql_error());
则mysql_close($链接);
}
?>
 

解决方案

我只能给一个局部的答案,因为我不能帮助PHP的一部分。

我把code在与一些修改这里的jsfiddle:
http://jsfiddle.net/AbdiasSoftware/M8pzB/

您可以看到清晰的按钮的使用方式,我建议(除非我用CTX在我的意见,而不是上下文)。

我也是从HTML中删除双ID'ed格(imgData)。

清晰的功能:

  $('#clearSig)。点击(
    传播clearSig(){
        clickX =新的Array();
        clickY =新的Array();
        clickDrag =新的Array();
        context.clearRect(0,0,canvas.width,canvas.height);
});
 

我添加了一个调试标签,显示一切现在工作了,以至于你会它发送到服务器的HTML。正如我不能测试这一部分,我只能建议你从那个部分开始调试。

我还添加了URI编码所产生的数据的URL从帆布这是有必要的。

传输MIME可文本/纯,而不是为你传递的是一个字符串。由于您使用jQuery,您可以使用内置的功能,AJAX转移:
http://api.jquery.com/jQuery.ajax/

在PHP端你再德code中的URI,去掉数据链接的标题为你做什么,然后去BASE64 code,如果你想将它保存为二进制文件。请注意,在MySQL中,你一定要去其存储为BLOB(不要与HTML5的Blob对象混淆)。

So I've been looking for weeks for a signature capture script that actually works and will save the signature to MySQL and I've finally found what I want but there are 2 problems.

  1. I can't figure out why the canvas wont clear the signature when the clear button is pressed.

  2. It wont submit the image to MySQL when the save signature button is pressed.

This code is pretty old and I've tried to contact the developer but haven't gotten a response back so I'm hoping I can get some help here.

Here is the html:

        <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">

    <head>
    <meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
    <title>Signature Pad</title>
    <script type="text/javascript" src="jquery.min.js"></script>
    </head>
    <body>
    <center>
        <fieldset style="width: 435px">
            <br/>
            <br/>
            <div id="signaturePad" style="border: 1px solid #ccc; height: 55px; width: 400px;"></div>
            <br/>
            <button id="clearSig" type="button">Clear Signature</button>&nbsp;
            <button id="saveSig" type="button">Save Signature</button>
            <div id="imgData"></div>
            <div id="imgData"></div>
            <br/>
            <br/>
        </fieldset>
    </center>
    </body>
    </html>

And the remaining php and scripts:

    $(document).ready(function () {
    /** Set Canvas Size **/
    var canvasWidth = 400;
    var canvasHeight = 75;

    /** IE SUPPORT **/
    var canvasDiv = document.getElementById('signaturePad');
    canvas = document.createElement('canvas');
    canvas.setAttribute('width', canvasWidth);
    canvas.setAttribute('height', canvasHeight);
    canvas.setAttribute('id', 'canvas');
    canvasDiv.appendChild(canvas);
    if (typeof G_vmlCanvasManager != 'undefined') {
        canvas = G_vmlCanvasManager.initElement(canvas);
    }
    context = canvas.getContext("2d");

    var clickX = new Array();
    var clickY = new Array();
    var clickDrag = new Array();
    var paint;

    /** Redraw the Canvas **/
    function redraw() {
        canvas.width = canvas.width; // Clears the canvas

        context.strokeStyle = "#000000";
        context.lineJoin = "miter";
        context.lineWidth = 2;

        for (var i = 0; i < clickX.length; i++) {
            context.beginPath();
            if (clickDrag[i] && i) {
                context.moveTo(clickX[i - 1], clickY[i - 1]);
            } else {
                context.moveTo(clickX[i] - 1, clickY[i]);
            }
            context.lineTo(clickX[i], clickY[i]);
            context.closePath();
            context.stroke();
        }
    }

    /** Save Canvas **/
    $("#saveSig").click(function saveSig() {
        var sigData = canvas.toDataURL("image/png");
        $("#imgData").html('Thank you! Your signature was saved');
        var ajax = XMLHttpRequest();
        ajax.open("POST", 'http://www.your-domain.com/folder/post-html.php');
        ajax.setRequestHeader('Content-Type', 'application/upload');
        ajax.send(sigData);
    });

    /** Clear Canvas **/
    function clearSig() {
        clickX = new Array();
        clickY = new Array();
        clickDrag = new Array();
        canvas.width = canvas.width;
        canvas.height = canvas.height;
    }

    /**Draw when moving over Canvas **/
    $('#signaturePad').mousemove(function (e) {
        if (paint) {
            addClick(e.pageX - this.offsetLeft, e.pageY - this.offsetTop, true);
            redraw();
        }
    });

    /**Stop Drawing on Mouseup **/
    $('#signaturePad').mouseup(function (e) {
        paint = false;
    });

    /** Starting a Click **/
    function addClick(x, y, dragging) {
        clickX.push(x);
        clickY.push(y);
        clickDrag.push(dragging);
    }

    $('#signaturePad').mousedown(function (e) {
        var mouseX = e.pageX - this.offsetLeft;
        var mouseY = e.pageY - this.offsetTop;

        paint = true;
        addClick(e.pageX - this.offsetLeft, e.pageY - this.offsetTop);
        redraw();
    });

});

MySQL portion:

    <?php
if (isset($GLOBALS["HTTP_RAW_POST_DATA"]))
{
$session_id = $_SERVER['REMOTE_ADDR'];
// Get the data
$imageData=$GLOBALS['HTTP_RAW_POST_DATA'];

// Remove the headers (data:,) part.
// A real application should use them according to needs such as to check image type
$filteredData=substr($imageData, strpos($imageData, ",")+1);

// Need to decode before saving since the data we received is already base64 encoded
$unencodedData=base64_decode($filteredData);

//echo "unencodedData".$unencodedData;
$imageName = "sign_" . rand(5,1000) . rand(1, 10) . rand(10000, 150000) . rand(1500, 100000000) . ".png";
//Set the absolute path to your folder (i.e. /usr/home/your-domain/your-folder/
$filepath = "htdocs/alpha/site6/signature/images/" . $imageName;

$fp = fopen("$filepath", 'wb' );
fwrite( $fp, $unencodedData);
fclose( $fp );

//Connect to a mySQL database and store the user's information so you can link to it later
$link = mysql_connect('localhost','root', 'pwd') OR DIE(mysql_error);
mysql_select_db("trial", $link);
mysql_query("INSERT INTO customer (`session`, `image_location`) VALUES ('$session_id', '$imageName')") OR DIE(mysql_error());
mysql_close($link);
}
?>

解决方案

I can only give a partial answer as I cannot help with the PHP part.

I put the code in a jsfiddle with a few corrections here:
http://jsfiddle.net/AbdiasSoftware/M8pzB/

You can see the clear button works as I suggested (except I used ctx in my comment instead of context).

I also removed a double ID'ed div (imgData) from the HTML.

The clear function:

$('#clearSig').click(
    function clearSig() {
        clickX = new Array();
        clickY = new Array();
        clickDrag = new Array();
        context.clearRect(0, 0, canvas.width, canvas.height);
});

I added a debug tag to the HTML which shows everything now works up to the point where you gonna send it to server. As I cannot test this part I can only suggest you start debug from that part.

I also added URI encoding for the resulting data-url from canvas which is necessary.

The transfer MIME can be text/plain instead as what you transfer is a string. Since you use jQuery you can use the built-in function for ajax-transfer:
http://api.jquery.com/jQuery.ajax/

On PHP-side you then decode the URI, strip off header of data-url as you do and then base64 decode it if you want to store it as binary. Note that in MySQL you will then need to store it as a BLOB (not to be confused with HTML5's Blob object).

这篇关于无法获取HTML5画布签名板提交到数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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