Home > Web Front-end > JS Tutorial > body text

jsignature Chinese development tutorial

青灯夜游
Release: 2022-03-02 09:45:14
forward
3697 people have browsed it

jSignature is a simple plug-in that simplifies signing in a browser window and allows users to write signatures with a mouse, pen, or finger. The following article will share with you a jsignature Chinese development tutorial, and briefly understand the usage of the jsignature plug-in. I hope it will be helpful to everyone!

jSignature captures signatures through vector outlines of strokes. jSignature can output PNG images and has great flexibility.

  • github:https://github.com/brinley/jSignature

  • http://www.unbolt.net/jSignature/ Part of English document

This article will finally bring a complete digitally signed demo and background processing PHP version. Please see the QQ group account at the bottom and enter the download. I want more people to join. Communicate and avoid detours

Please note that the best version of jquery you have used is relatively new. Mine is jquery2.1.4, and the version of jSignature is jSignature v2, because the newer the version, the better the effect of writing on h5 flow.

Please note that this document is based on the translation of the old version and some repairs based on personal experience

Finally there are some tips and personal experience

Note:

The latest version of this plug-in supports IE8. Please test on the local server and do not open it directly because some js file request protocols do not support the windows local file protocol

Differences between file:// and http requests

If you don’t know the difference in how to request the protocol, please don’t worry, go directly to the local server to test

Basically used method

<div id="signature"></div>
<script type="text/javascript" src="jquery.js"></script>
<script language="JavaScript" type="text/javascript" src="jSignature.js"></script>

 <script type="text/javascript">
 $(document).ready(function() {
   $("#signature").jSignature();
 });
 </script>
Copy after login

If

is only quoted in html5, the browser needs to use

<div id="signature"></div>
<script type="text/javascript" src="jquery.js"></script>
<script language="JavaScript" type="text/javascript" src="jSignature.js"></script>

   <!--[if lt IE 9]>
        <script type="text/javascript" src="flashcanvas.js"></script>
        <![endif]-->

 <script type="text/javascript">
 $(document).ready(function() {
   $("#signature").jSignature();
 });
 </script>
Copy after login

to solve this compatibility problem

Method:

Method nameUsage methodDescription
clear.jSignature("clear")Clear and reset the canvas
getData.jSignature("getData", "base30 ")Convert the canvas to a base64 encoded data string that can be saved as a string in any database when the form is posted or submitted
importData.jSignature("importData",dataurl)Update the existing jSignature canvas with the data URL extracted from the above getData method

Option parameters:

##Parameter nameDescriptionDefault valuewidthDefine the width of the canvas. There is no % or px value (the new version can use percentage and px suffixes) 250height Define the height of the canvas. There is no % or px value (the new version can use percentage and px suffixes) 150color Define the color of the strokes on the canvas. Accepts any color hexadecimal value #000background-color Defines the background color of the canvas. Accepts any color hexadecimal value #ffflineWidth Defines the thickness of the line. Accepts any positive value (also the width of the default canvas's horizontal line brush) 1cssclass Custom css class that defines the canvasNone

导入图像数据

画布图像导入并保存到数据库后,可以通过其base64编码的字符串轻松显示图像,

要通过jQuery来做,可以使用类似的东西

$("<img class=&#39;imported&#39;></img>").attr("src",sig.jSignature(&#39;getData&#39;, &#39;base30&#39;)).appendTo(sig);
Copy after login

或者直接从服务器端输入数据串到img的的src属性中

<img src="<? echo $datastring ?>" />
Copy after login

您还可以将dataUrl导入到jSignature画布中,以便您可以通过以下JavaScript代码编辑签名

$("#signature").jSignature("importData",dataurl);
Copy after login

dataurl是上面使用的相同的数据串。 您可以在下面的演示中通过从其中一个jSignature复制数据字符串,然后单击另一个jSignaure的“导入数据到画布”,

并将数据字符串粘贴到出现的对话框中,从而在下面的演示中看到它

giehub官方版本部分

jSignature是一个jQuery插件,它简化了浏览器窗口中签名捕获字段的创建,允许用户使用鼠标,笔或手指绘制签名。

j签名将签名作为笔画的向量轮廓捕获。 虽然jSignature也可以导出伟大的位图(PNG),提取签名的高度可扩展的行程移动坐标(也称为矢量图像)允许更大的灵活性

进行额外的努力(通过平滑和压力模拟),使得笔画在屏幕上看起来很漂亮,而这些画面由阁下绘制。

所有主要的桌面,平板电脑和手机浏览器的支持。默认情况下使用HTML5画布元素。我们依靠基于canvas元素模拟器Flash(flashcanvas)当实际帆布不支持的浏览器(Internet Explorer 8节下)。

实时jsignature呈现只有装置适当的“漂亮的”逼近我们捕获。捕获的数据总是相同的-我们尽可能捕捉尽可能多的运动坐标。笔触的绘制不同于浏览器的功能,设备的效率,屏幕大小。

捕获的签名的屏幕表示的这种降级和增强是为了确保渲染不会影响捕获的响应性而进行的。 例如,在缓慢渲染设备(Android浏览器,基于FlashCanvas的Canvas仿真)上,平滑被踢出了一个缺口,以补偿捕获的笔画坐标中的巨大差距 - 捕获设备效率低下的结果。 在所有情况下,客户都会对图纸的反应和美观感到高兴。

jSignature可以轻松地将其自己调入现有样式的网站。 jSignature自动检测包装元素上使用的颜色(文字颜色=笔颜色,背景=背景),并自动选择“装饰”(签名行)的令人愉快的中间色调。 jSignature适用于固定和可变宽度的网页设计,以及各种大小的屏幕(手机,平板电脑,电脑屏幕),并且当父元素更改大小时自动重新绘制绘图区域和签名。

demos here:

http://brinley.github.io/jSignature/

将jSignature添加到您的页面

查看源代码树中的libs文件夹。 从那里挑选3个文件:

1、jSignature.min*.js (“*”表示您有选择。 您可以选择常规的以jQuery为中心的构建或特殊的jQuery.NoConflict构建)

2、flashcanvas.js

3、flashcanvas.swf

jSignature取决于(至少最新版)jQuery

如果您不打算支持IE 7和8,则不需要下载FlashCanvas文件。

请注意,FlashCanvas是两个文件的连贯一组,分别是flashcanvas.swf和flashcanvas.js,这两个文件必须位于同一个文件夹中。 不要将它们从单独的文件夹托管,因为flashcanvas.js在与其提供的同一文件夹中查找flashcanvas.swf。 不要将flashcanvas.js重命名为其他任何东西,因为它在DOM中通过该名称查找自己,以找出从哪里加载flashcanvas.swf。

jSignature本身有三个不同的代码段转换成一个最小的可部署::

  • 准备Canvas元素的代码。 它包括检测浏览器功能,最大限度地利用div的范围内的画布,在需要时使用Flashcanvas设置仿真画布。

  • 处理实际签名捕获+数据导入/导出API的代码。 它附加并监听移动事件处理程序,将数据结构中的笔触数据存储起来,处理API调用。

  • 插件可帮助您获取方便您的格式的签名数据,如原始数据坐标,图像,压缩的url兼容字符串,SVG。

如果您确定受众受限于特定的浏览器引擎(您可以通过嵌入式浏览器小部件部署,使用类似PhoneGap的部件),您可以卷起袖子并将其放在第1部分。 如果你知道你只需要一个导出/导入插件,那么从最小化的可部署中删除你不需要的插件。

更多自定义数据导出/导入插件可以单独加载,而无需重新设置主要部署。 但是,缩小是有趣和容易的。 只需看看wscript.py文件,并更改几行以包含/排除某些部分。

对于“通用”部署场景(包括旧IE的支持),将其添加到您的页面:

<!-- this, preferably, goes inside head element: -->
<!--[if lt IE 9]>
<script type="text/javascript" src="path/to/flashcanvas.js"></script>
<![endif]-->

<div id="signature"></div>

<!-- you load jquery somewhere before jSignature ... -->
<script src="path/to/jSignature.min.js"></script>
<script>
    $(document).ready(function() {
        $("#signature").jSignature()
    })
</script>
Copy after login

解释:

  • [if lt IE 9]部分加载IE小于9的Flashcanvas库(仅在IE上支持Flashcanvas,所以没有任何意义进行功能检测。)

  • 我们标记一个div,其中将创建canvas元素。 任何ID或其他jQuery选择器都可以。

  • 我们加载jSignature插件。

  • 最后,脚本调用指定DIV中的签名小部件。

API

以下方法暴露在jQuery对象之上:.jSignature(String command,* args)

参数因命令而异。 当提供命令时,命令将是一个带有jSignature命令的字符串。 目前支持的命令:

  • init是默认的,假定的动作。 init需要一个参数 - 一个设置对象。 您可以省略命令,并在init中传递设置对象。 返回(以传统的jQuery链接方式)jQuery对象引用应用插件的元素。

  • reset 复位只是清除签名板,数据存储(并放回签名线和其他装饰)。 返回(以传统的jQuery链接方式)jQuery对象引用应用插件的元素。

  • clear reset别名,历史遗留

  • getData 接受参数 - 数据格式的名称。 返回适合数据格式的数据对象

  • setData 需要两个参数 - 数据对象,数据格式名称。 当数据对象是以data-url模式格式化的字符串时,您不需要指定数据dormat名称。 数据格式名称(mime)将从data-url前缀中隐含。 见下面的例子。 返回(以传统的jQuery链接方式)jQuery对象引用应用插件的元素。

  • importData setData的别名 ,历史遗留

  • listPlugins 接受一个参数 - 表示要列出的插件的类别(仅导出,此时支持的导入)的字符串。 返回字符串数组。

  • disable 使画布只读,并禁用jSignature按钮

  • enable 使画布只读,并启用jSignature按钮

  • isModified 如果jSignature被修改,返回一个布尔值true,否则返回false。

  • getSettings 返回jSignature实例的可配置设置。

  • updateSetting 需要三个参数 - 设置名称,新值,布尔值,如果更改应该影响当前签名或将来的笔画。 这允许您更新某些设置,如lineWidth或线条颜色,使用第三个参数可以使更改适用于现有笔画。 目前,更新现有笔画的更改仅适用于像颜色这样的几个设置。 返回更新的值

使用实例:

var $sigdiv = $("#signature")
$sigdiv.jSignature() //初始化 jSignature 插件
// after some doodling...
$sigdiv.jSignature("reset") // 清除画布并在其上重新装饰。
// 将签名作为SVG并在浏览器中呈现SVG。
// (!!!来自IMG元素的内联SVG渲染在所有浏览器中都不起作用!!!)
//这个导出插件返回一个数组[mimetype,base64编码的SVG的字符串的签名笔画]
var datapair = $sigdiv.jSignature("getData", "svgbase64") 
var i = new Image()
i.src = "data:" + datapair[0] + "," + datapair[1] 
$(i).appendTo($("#someelement")) // append the image (SVG) to DOM.

// 获取签名为“base30”数据对
// 数组[mimetype,jSignature的自定义Base30压缩格式的字符串]
datapair = $sigdiv.jSignature("getData","base30") 
// 将数据重新导入jSignature。
// 导入插件了解数据网址格式的字符串,如“data:mime; encoding,data”
$sigdiv.jSignature("setData", "data:" + datapair.join(","))
Copy after login

数据导入/导出(和插件)

以下插件(数据格式)是主线j签名的一部分,可分发:

  • default (仅限EXPORT ONLY)(BITMAP)数据格式与输出格式j兼容,在早期版本中生成的getData被调用时不带参数。 默认情况下,默认情况下(默认情况下)调用$ obj.jSignature(“getData”)数据格式是Canvas - data-url格式化的base64编码(可能的PNG)位图数据,如下所示 :data:image / png; base64,i1234lkj123; k4; l1j34l1kj3j ...此导出调用返回单个数据网址格式的字符串。

  • native (导出和导入)(VECTOR)(VECTOR)数据格式是绘制笔画的自定义表示形式,作为具有道具.x,.y的对象数组,每个对象都是一个数组。这个JavaScript对象结构是每个绘图笔画存储在jSignature中的实际数据结构。该结构专门用于收集笔触数据点的速度和效率。 (尽管它有一些反直觉,章鱼式的结构,它(a)允许快速堆积双轴坐标,而不需要为每个数据点创建Point对象,(b)提供非常简单的循环,基于数据的处理)。虽然您可以JSONify,它传递,解析,从此渲染,它可能不是最有效的方式来存储数据,因为内部格式可能会改变其他主要版本的jSignature。我建议将base30格式视为直接的,但紧凑的等同于“native”-as-JSON。这个数据适用于运行统计信息(尺寸,画布上的签名位置)和编辑笔画(例如允许“撤消最后一个笔画”)。

  • base30 (alias image/jSignature; base30) (EXPORT AND IMPORT) (VECTOR) (VECTOR) (VECTOR) (VECTOR) (VECTOR) (VECTOR) The data format is A Base64 based compression format for ridiculous compactness and native url compatibility. It is a "native" data structure compressed into a compact string representation of all vectors. Code examples (.Net, PHP, Ruby) to unpack this format into a renderable format (SVG, language-native coordinate array) are provided in the extras folder. One possible method of transferring data to the server is JSONP, which has a real URL length limit of no more than 2000 characters (imposed by IE). This compressed format is local URL compatible and requires no re-encoding, but fits within the 2000 characters of most non-complex signatures.

  • svg (alias image/svg xml) (EXPORT ONLY) (VECTOR) (VECTOR) data format generates signatures for SVG images (SVG XML text). All strokes are denoised and smoothed. This format is a good medium between "easy to view" and "highly scalable". Most browsers currently support viewing SVG, however, this format can be infinitely scaled and enhanced for printing. The data is text and is easy to store and transfer. The call to jSignature("getData", "svg") returns an array of the form ""image/svg xml","svg xml here"].

  • svgbase64 (alias image/svg xml; base64) (EXPORT ONLY) (VECTOR) Same as the "svg" plugin, but compresses the SVG XML text using base64 encoding. Although many browsers now have base64 encoders built in ( btoa()), but some like Internet Explorer don't. The plugin has its own (short and efficient) copy of the software-based base64 encoder that is called on browsers that lack btoa(). Right The call to jSignature("getData", "svgbase64") returns an array of ["image/svg xml;base64", "base64 encoded svg xml here"). This two-component array can easily be turned into data-url formatted characters String("data:" data.join(",")), or converted to args and passed to the server as a form value.

  • image (EXPORT ONLY) (BITMAP) data format is basically the same as the "default" data format above, but is parsed so that the mimetype and data are separate objects in an array structure similar to that produced by the "svg" export. Example (shortened) ["image/ png;base64","i123i412i341jijalsdfjijl234123i..."]. Because the image export filter depends on (somewhat thin) browser support and picks up unnecessary data, it is recommended to use it only for demonstration and development.

Choose export/storage format

#I know you are trying to get the "image" from jSignature, but, please control yourself and Stay away. Instead, consider capturing "base30" or "svg" data on the post-production server side and enhance the rendering.

If you export as a "bitmap", the image will retain the actual drawing colors, sizes, defects, and The bottom line is that may not work on all browsers.

  • The decoration (signature line) will be on the image. If jSignature is designed with a dark background light pen color then you will have What you get on the image - a dark background with a light drawing covering the gray signature line. This image is almost useless when printed. This would be the case if your background was the same intensity as the pen (e.g. blue for red) Worse, in this case, when printed in black and white, the image is just a dark gray rectangle. If you change the page colors, the captured images now start wearing those colors.

  • Android 1.6 -2.2 (2.3?) does not support canvas.toDataURL method - bitmap export function.

  • Small screens (mobile phones) produce tiny ugly bitmaps.

  • Canvas exported bitmaps have GARGANTUAN dimensions compared to vectors because it preserves all intermediate shadow and background pixels.

If you want to force yourself to capture only black on top of the web style using a white signature, use a bitmap export. If you want to make your database administrator scream because a backup of the database with all bitmap data will take more than a day, use bitmap export. If you want your sales/business department to scream at you because your signature capture format cannot be easily integrated into a new well-designed wizbang product/service, use bitmap export. If you want to explain why the selected siganture format export is not available for all target platforms, use bitmap export. If you want to take the easy route now and make the IT guy come in after you're fired and have the difficult task of applying an ImageMagic smart card to the mess of colorful pixels you decided to collect, use the bitmap export format.

如果使用捕获的签名与“业务”或“打印”或“多个演示场所”有任何关系,则使用“base30”或“svg”数据等矢量格式,并在后期制作中增强+渲染。 “extras”文件夹中可以找到解压缩和样本,基本的渲染代码(.Net,截至2012年2月的PHP)。 您将使用这些为核心,为您自己的渲染逻辑提供可循环的坐标数据数组。

Events(事件)

jSignature初始化的dom元素在笔画完成后立即发出“change”事件,并将其添加到存储器中。 (换句话说,当用户完成绘制每个笔画时,如果用户绘制3笔画,则每次笔画完成后,此事件将发出3次)。

以下是您如何绑定到该事件:

$("#signature").bind(&#39;change&#39;, function(e){ /* &#39;e.target&#39; will refer to div with "#signature" */ })
Copy after login

事件通过“线程”(setTimeout(...,3))异步发出,因此您不需要将事件处理程序包装到任何类型的“线程”中,因为jSignature小部件将继续执行,并且不会等待 你要完成你的自定义事件处理程序逻辑。

个人经验和一个完整的php版本demo

html部分

//jquery.moblie会和jsignature有冲突,不知道是版本问题,还是代码代码冲突
<script src="__PUBLIC__/hplus/js/jquery.min.js"></script>
<script src="__PUBLIC__/sign/jSignature.min.js"></script>
<script src="__PUBLIC__/hplus/js/plugins/pace/pace.min.js"></script>
<!--<script src="__PUBLIC__/hplus/js/bootstrap.min.js?v=3.3.6"></script>-->
<link href="__PUBLIC__/hplus/css/bootstrap.min14ed.css?v=3.3.6" rel="stylesheet">
<script src="__PUBLIC__/hplus/js/plugins/layer/layer.min.js"></script>



<style type="text/css"> 
    .zx11{
        border: 1px;
        border-color: red;
    }
    #signatureparent {
        color:black;
        background-color:darkgrey;
    }
    #signature {
        border: 2px dotted black;

    }

</style>

<div class="container">
    <div id="signatureparent">
        <div id="signature"></div>
    </div>
    <br>
    <button type="button" class="btn btn-primary btn-block" id="save">保存</button>
    <button type="button" class="btn btn-default btn-block" id="clear">清除</button>
</div>

<script>
    $(document).ready(function () {

        var arguments = {
            width: &#39;100%&#39;,
            height: &#39;300px&#39;,
            cssclass: &#39;zx11&#39;,
            signatureLine: false,//去除默认画布上那条横线
            lineWidth: &#39;5&#39;
        };
        $("#signature").jSignature(arguments);

        $(&#39;#clear&#39;).click(function () {
            $("#signature").jSignature("reset");
        });
        $(&#39;#save&#39;).click(function () {
            //标准格式但是base64会被tp框架过滤,所不校验,但是jSignature默认是使用png
            var datapair = $("#signature").jSignature("getData", "image");
            var i = new Image();
            i.src = "data:" + datapair[0] + "," + datapair[1];
            i.image = datapair[1];
            var requestTag;
            requestTag = &#39;{$Think.get.identify}&#39;;
            console.log(i.image);
//            console.log(i.src);

            //询问框
            layer.confirm("如果确认无误,请确认<br><img src=" + i.src + " height=&#39;100px&#39; width=&#39;100px&#39; />", {
                btn: [&#39;确认&#39;, &#39;取消&#39;] //按钮
            }, function () {


                $.ajax({
                    url: "/app.php?m={$Think.MODULE_NAME}&a={$Think.ACTION_NAME}",
                    //dataType: "json",                    contentType: "application/json; charset=utf-8",
                    data: "{\"identify\":\"" + requestTag + "\",\"image_data\":\"" + encodeURIComponent(i.image) + "\"}",//避免base64长度过大,json传输
                    type: "post",
                    cache: false,
                    success: function (msg) {
                        if (msg.code === 1) {
                            layer.msg(&#39;上传成功&#39;);
                        } else {
                            layer.msg(&#39;上传失败,请再次签名!&#39;);
                        }
                    }
                });
            }, function () {
                layer.msg(&#39;取消成功&#39;);
            });



        });
    });
</script>
Copy after login

php部分

$image_data = json_decode(file_get_contents(&#39;php://input&#39;), true); //只能这样接收
$data = rawurldecode($image_data[&#39;image_data&#39;]);

$file_name = time().&#39;.png&#39;; //必须png
$a = file_put_contents($file_name, base64_decode($data));
Copy after login

【相关推荐:javascript学习教程web前端

The above is the detailed content of jsignature Chinese development tutorial. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:cnblogs.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template