JQuery签名面板插件 [英] JQuery Signature Panel Plugin

查看:107
本文介绍了JQuery签名面板插件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在试图让一个签名小组在Grails中工作。在客户端,一切看起来都很有效,但我一直在努力如何将签名保存到数据库记录中。



我试过了几个不同的版本,最后一个我最接近描述如何使用ImageMagic或类似的使用PHP,红宝石,或Python。然而,在常规方法中尝试这样做会让我失去信心,因为在编码方面我仍然有点儿绿色。另外,我不确定在将要在云代工厂运行时使用第三方实用程序。



名为SignaturePanel的插件看起来与其他代码类似真的...
jes-sherborne / jquery-signature-panel-plugin



以下是我的文件中的代码。

首先,create.gsp包含Javascript代码。

 < ; title>< g:message code =default.create.labelargs =[entityName]/>< / title> 
<! - jQuery签名元素代码从这里开始 - >
<! - [if lt IE 9]>< script type =text / javascriptsrc =$ {resource(dir:'js',file:'excanvas.compiled.js') }>< /脚本><![ENDIF] - GT;
< script type =text / javascriptsrc =$ {resource(dir:'js',file:'jquery-1.4.4.min.js')}>< / script>
< script type =text / javascriptsrc =$ {resource(dir:'js',file:'jquery.signature-panel.js')}>< / script>

link rel =stylesheethref =$ {resource(dir:'css',file:'jquery.signature-panel.css')}type =text / css />


< script type =text / javascript>

函数signatureOK(signatureData){
//将签名发送到服务器并生成一个图像文件。
$ .ajax({
url:processSignature,
type:POST,
data:JSON.stringify(signatureData),
contentType:application / json; charset = utf-8,
dataType:text,
success:function(data,textStatus,jqXHR){
$(#latest-signature)。attr (src,data);
},
错误:函数(jqXHR,textStatus,errorThrown){
console.log(textStatus);
console.log(errorThrown) ;
}
});
$(#sig-panel)。signaturePanel(clear);
}

函数signatureCancel(){
alert(Cancelled。);

$ b $(document).ready(function(){
$(#sig-panel)。signaturePanel({
okCallback:signatureOK,
cancelCallback:signatureCancel
});
});

< / script>

_form.gsp

 <! - 签名面板在此处开始 - > 

< label for =sig>< g:message code =salesOrder.sig.labeldefault =Customer Signature/>< / label>
< div class =fieldcontain$ {hasErrors(bean:s​​alesOrderInstance,field:'sig','error')} id =sig-panelstyle =width:500px; height:150px; border :0px none>< / div>
< canvas id =latest-signaturestyle =width:500px; height:150px; border:0px none>< / canvas>

<! - 签名面板结束 - >

控制器

  //捕获客户签名JSON数据,图像处理和流到数据库
@Secured(['ROLE_ADMIN','ROLE_SALES'])
def processSignature(){
flash.message = message(code:'default.created.message',args:[message(code:'salesOrder.label',default:'Signature'),])
// groovy code here
//我们需要读取JSON POST数据
InputStream body = request.getInputStream();
log.info(body)//此处没有任何反应
}

是我试图弄清楚如何在groovy中做的Ruby示例之一*(或者如果有更好的方法......在客户端,可以右键单击并保存图像,不太确定这是为什么对我来说很困难)

  ###使用Ruby在服务器上生成图像文件

Ruby库使用ImageMagick生成一个`Magick :: Image`对象,您可以使用它来写入图像文件或以各种格式(PNG,JPEG等)流式传输数据。默认情况下,该功能将生成与最初在客户端捕获的像素尺寸相同的图像。您还可以指定生成图像的大小,SignaturePanel将适当缩放签名以适应这些边界。

要生成图像,您需要编写如下代码:

```ruby
require'signature-panel.rb'
.. 。

post'/ process-signature'do
image = SignaturePanel :: GenerateImage(request.body.read)
filename ='latest-signature.png'

image.write(文件名)

#如果您想直接将PNG流式传输到数据库而不是保存文件,可以使用
#获得这样的二进制流:
#image.to_blob {self.format =PNG}

content_type:text

#将新生成的文件的名称发送给客户端
主体文件名
结束
```

再一次是,如何使用groovy将签名和所有其他表单数据一起保存到数据库中?

同样从我的域类中,我应该提及

  byte [] sig 

sig nullable:true,maxSize:1048567

一旦我们解决了这个挑战,我们就可以让这只小狗睡觉; )

解决方案

我总是将JSON数据保存到文本类型字段中(如Oracle中的CLOB),然后使用库函数在页面上显示它:

  $(#signature-display)。signaturePanel(drawClickstreamToCanvas, signatureData); 

其中 signatureData 是JSON字符串。 / p>

所以你可以改变你的领域类来包含

  String sig 

sig nullable:true,maxSize:1048567

这也可以让你做我认为非常酷的东西,不管它是否有用取决于你的应用程序。您可以重新创建签名的实际签名并进行动画处理:

  $(#signature-replay)。signaturePanel(animateClickstreamToCanvas ,signatureData,回调); 

这份文件解释了可选的回调函数。我从来没有使用过。



如果您更改ajax调用的一部分,请删除 contentType 行,因为您正在发送直接文本并设置隐藏字段

 键入:POST,
data:{signature :JSON.stringify(signatureData)},
// contentType:application / json; charset = utf-8,
成功:function(data,textStatus,jqXHR){
//设置隐藏字段值
$('#sig').val(JSON.stringify(signatureData));
//在预览的同一页面上显示签名(可选)
$(#latest-signature)。signaturePanel(drawClickstreamToCanvas,signatureData);
},
....

然后将隐藏字段添加到表格为

 < g:hiddenField name =sig/> 

现在,当他们输入签名并点击确定时, processSignature 不会做任何事情 - 只是充当占位符。 AJAX调用将设置页面上隐藏字段的值。然后,当他们提交整个表单(以及其他数据)时,正常的 save()方法将获得 sig param,并自动将其保存到域类中的 sig 字段中。



您可以将数据作为如果您需要: processSignature 方法中的正常字符串作为 params.signature

  def processSignature(){
flash.message = message(code:'default.created.message',args:[message(code:'salesOrder。标签',默认:'签名'),])
def signature = params.signature
log.info(签名)
response.contentType =application / json
render {ok:true}
}


I've been trying to get a signature panel to work in grails. on the client side everything looks like it works, but I have been struggling on how to get the signature saved to the database record.

I've tried a couple different versions, the last one I ended up with came closest to describing how to use ImageMagic or the like using php, ruby, or python. However trying to do this in groovy left me lost because I'm still a little green on how to code. Also I'm not sure about using a 3rd party utility when this is going to be running on cloud foundry.

The plugin in called SignaturePanel, looks just like the other ones really... jes-sherborne/jquery-signature-panel-plugin

Here is the code from my files.

First, create.gsp contains the Javascript code.

<title><g:message code="default.create.label" args="[entityName]" /></title>
        <!--  jQuery signature element code begins here -->
        <!--[if lt IE 9]><script type="text/javascript" src="${resource(dir: 'js', file: 'excanvas.compiled.js')}"></script><![endif]-->
    <script type="text/javascript" src="${resource(dir: 'js', file: 'jquery-1.4.4.min.js')}"></script>
    <script type="text/javascript" src="${resource(dir: 'js', file: 'jquery.signature-panel.js')}"></script>

    <link rel="stylesheet" href="${resource(dir: 'css', file: 'jquery.signature-panel.css')}" type="text/css"/>


    <script type="text/javascript">

        function signatureOK(signatureData) {
            // Send the signature to the server and generate an image file.
            $.ajax({
                url:"processSignature",
                type:"POST",
                data:JSON.stringify(signatureData),
                contentType:"application/json; charset=utf-8",
                dataType:"text",
                success: function(data, textStatus, jqXHR){
                    $("#latest-signature").attr("src", data);
                },
                error: function(jqXHR, textStatus, errorThrown) {
                    console.log(textStatus);
                    console.log(errorThrown);
                }
            });
            $("#sig-panel").signaturePanel("clear");
        }

        function signatureCancel() {
            alert("Cancelled.");
        }

        $(document).ready(function() {
            $("#sig-panel").signaturePanel({
                okCallback: signatureOK,
                cancelCallback: signatureCancel
            });
        });

    </script>

_form.gsp

<!-- Signature Panel Begins Here -->

    <label for="sig"><g:message code="salesOrder.sig.label" default="Customer Signature" /></label>
    <div class="fieldcontain" ${hasErrors(bean: salesOrderInstance, field: 'sig','error')} id="sig-panel" style="width: 500px; height: 150px; border: 0px none"></div>
    <canvas id="latest-signature" style="width: 500px; height: 150px; border: 0px none"></canvas>

<!-- End of Signature Panel -->

Controller

// Capture Customer Signature JSON Data, Processes to Image, and Stream to Database
    @Secured(['ROLE_ADMIN','ROLE_SALES'])
    def processSignature() {
        flash.message = message(code: 'default.created.message', args: [message(code: 'salesOrder.label', default: 'Signature'), ])
        // groovy code here 
        // We need to read the JSON POST data
         InputStream body = request.getInputStream();
         log.info(body) // nothing happens here
    }

Here is one of the Ruby examples I'm trying to figure out how to do in groovy.*(or if there is a better way... on the client side one can just right click and save the image. not really sure why this is so difficult for me)

### Generating image files on the server using Ruby

The Ruby library uses ImageMagick to generate a `Magick::Image` object, which you can use to write image files or stream the data in a variety of formats (PNG, JPEG, etc.). By default, the function will generate an image with the same pixel measurements as were originally captured on the client. You can also specify the size of the generated image, and SignaturePanel will scale the signature appropriately to fit within these bounds.

To generate the image, you will write code like this:

```ruby
require 'signature-panel.rb'
...

post '/process-signature' do
    image = SignaturePanel::GenerateImage(request.body.read)
    filename = 'latest-signature.png'

    image.write(filename)

    # If you want to stream your PNG directly to a database instead of saving a file,
    # you can get a binary stream like this:
    # image.to_blob {self.format = "PNG"}

    content_type :text

    # Send the name of the newly-generated file to the client
    body filename
end
```

So my question once again is, how does one save the signature along with all the rest of the form data in to the database using groovy?

Also from my domain class I should mention

byte[] sig

sig nullable: true, maxSize: 1048567

Once we get this challenge solved, we can put this puppy to bed ; )

解决方案

I've always just saved the JSON data into a text type field (like a CLOB in Oracle) and then used the library functions to show it on the page:

$("#signature-display").signaturePanel("drawClickstreamToCanvas", signatureData); 

where signatureData is the JSON string.

So you could change your domain class to include

String sig

sig nullable: true, maxSize: 1048567

This also allows you to do something I think is very cool, although whether it's useful or not depends on your app. You can recreate and animate the actual signing of the signature:

$("#signature-replay").signaturePanel("animateClickstreamToCanvas", signatureData, callback);

The docs explain the optional callback function. I've never used that though.

If you change part of your ajax call, removing the contentType line because you are sending straight text and setting the hidden field

type:"POST",
data:{"signature": JSON.stringify(signatureData)},
//contentType:"application/json; charset=utf-8",
success: function(data, textStatus, jqXHR){
    //set the hidden field value
    $('#sig').val(JSON.stringify(signatureData));
    //show signature on same page as preview (optional)
    $("#latest-signature").signaturePanel("drawClickstreamToCanvas", signatureData);
},
....

And then add the hidden field in the form as

<g:hiddenField name="sig" />

So now when they enter the signature and hit "OK" the processSignature won't really do anything - just act as a placeholder. The AJAX call will set the value of the hidden field on the page. Then when they submit the entire form (with other data) the normal save() method will get sig as just another param and will automatically save it to a sig field in the domain class.

You could access the data as a normal string in the processSignature method as params.signature if you needed to:

def processSignature() {
    flash.message = message(code: 'default.created.message', args: [message(code: 'salesOrder.label', default: 'Signature'), ])
    def signature = params.signature
    log.info(signature)
    response.contentType = "application/json"
    render """{"ok":true}"""
}

这篇关于JQuery签名面板插件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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