集成一个好用的canvas签名板

项目地址

开箱可用, 此项目的作者在代码中做了详细的注释。

https://github.com/941477276/Tablet/tree/master

上代码

将它集成到你的项目中需要四个文件。

前端代码

<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8" />
    <meta content="width=device-width,initial-scale=1.0,maximum-scale=1.0,user-scalable=no" id="viewport" name="viewport">
    <meta name="format-detection" content="telephone=no, email=no" />
    <meta name="wap-font-scale" content="no">
    <meta name="apple-touch-fullscreen" content="yes" />
    <meta name="apple-mobile-web-app-status-bar-style" content="black" />
    <meta name="HandheldFriendly" content="true">
    <meta name="MobileOptimized" content="320">
    <meta name="screen-orientation" content="portrait">
    <meta name="x5-orientation" content="portrait">
    <meta name="x5-page-mode" content="app">
    <meta name="msapplication-tap-highlight" content="no">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black">
    <title>用户签名</title>
    <link rel="stylesheet" href="your-path/colpick.css" />
    <style>
        body,canvas{
            padding: 0;
            margin: 0;
            background-color: #f0f0f0;
        }
        *{
            box-sizing: border-box;
            padding: 0;
            margin: 0;
        }
        .container{
            height: 100%;
        }
        .container .-tablet,
        .container .-tablet-container,
        .container .-canvas-wrapper{
            height: 100%;
        }
        
        /* 签字板横屏处理*/
        @media all and (orientation : portrait) {
            .layui-m-layermain {
                transform: rotate(90deg) !important;
            }
        }

    </style>
</head>
<body>
    <div class="container" id="container"></div>
    <script type="text/html" id="temp">
       <span class="save-canvas-to-img">
           确认签名
       </span>
    </script>
    <script src="https://cdn.staticfile.org/jquery/3.3.1/jquery.min.js"></script>
    <script src="your-path/layer.js"></script>
    <script src="your-path/Tablet-1.0.js"></script>
    <script>
        let tablet;
        $(function (){
            tablet = new Tablet("#container",{
                defaultColor: "#000", //笔的默认颜色
                otherHtml: $("#temp").html(), //外部功能小部件
                response: true, //开启响应式
                onInit: function (){
                    let that = this,
                    container = this.container;  
                    container.find(".save-canvas-to-img").on("click", function (){
                    
                    /* 直接获取 base64 编码的图片*/
                    let signImg = that.getBase64()
                    
                    console.log(signImg)
                    
                    layer.open({
                        content: '确定提交自己的个人签名么?'
                        ,btn: ['确定', '取消']
                        ,yes: function(index){
                            layer.close(index)
                            $.ajax({
                                url: "your-url",
                                method: 'post',
                                data: {
                                    signImg: signImg
                                },
                                success: function(data) {
                                    /* 这里返回数据根据你的实际情况处理*/
                                    let status = data.result.status
                                    let result = data.result.result
                                    if (status === 200) {
                                        layer.open({
                                            time: 1,
                                            title: [
                                                '提示信息',
                                                'background-color: green; color:#fff;'
                                            ]
                                            ,content: result.toString()
                                        });
                                    } else {
                                        layer.open({
                                            time: 1,
                                            title: [
                                                '提示信息',
                                                'background-color: #FF4351; color:#fff;'
                                            ]
                                            ,content: result.toString()
                                        });
                                    }
                                },
                                error: function (error) {}
                            })
                                that.clear()
                            },no: function (index) {
                                layer.close(index)
                                that.clear()
                            }
                        })
                    })
                }
            });
            
            /* 横屏处理,这里简单粗暴,如果屏幕转动,直接重载页面。*/
            var evt = "onorientationchange" in window ? "orientationchange" : "resize";
            window.addEventListener(evt,resize,false);
            window.orientation = 90;
            var oldOrientation = window.orientation;

            function resize(fals) {
                if(window.orientation !== oldOrientation) {
                    window.document.location.reload()
                    oldOrientation = window.orientation
                }
                if (window.orientation === 0 || window.orientation === 180) {
                    tablet.rotate(90);
                }
            }
            resize(true);
        });
    </script>
</body>
</html>

后端代码(这里写两个简单的函数,你可以使它更完善)

/* 处理 ajax 传来的 base64编码*/
function userSignData($signImg)
{
    $dest = 'your-path/signImg'.uniqid().'.png';
    
    $base64 = explode(',', $signImg);
    
    /* 这里默认当成 png 处理了,处女座请自己完善*/
    $pngCode = base64_decode(end($base64));

    file_put_contents($dest, $pngCode);

    $res = compressImg($dest, $dest, 0.5);
    if ($res) {
        /* 这里就是压缩后的图片编码*/
        $base64NewImg = base64_encode(file_get_contents($dest));

        /* 删除保存的图片,当然你可以不删除,注释以下即可*/
        unlink($dest);
        
        return ['status' => 200, 'result' => '已提交签名'];
    } else {
        return ['status' => 500, 'result' => '巴拉巴拉巴拉'];
    }
    
}

/* 压缩图片*/
function compressImg($source, $dest, $quality = 0.7)
{
    // 判断原图是否存在
    if(!file_exists($source)){
        return false;
    }
        
    // 获取原图信息
    list($owidth, $oheight, $otype) = getimagesize($source);

    $newWidth = $owidth * $quality;
    $newHeight = $oheight * $quality;

    /* 由于签名是透明背景的 png,这里创建一个透明背景的新图*/
    $newImg = imagecreatetruecolor($newWidth, $newHeight);
    $color=imagecolorallocate($newImg,255,255,255);
    imagecolortransparent($newImg,$color);
    imagefill($newImg,0,0,$color);
    
    
    switch($otype){
        case 1: $source_img = imagecreatefromgif($source); break;
        case 2: $source_img = imagecreatefromjpeg($source); break;
        case 3: $source_img = imagecreatefrompng($source); break;
        default:
            return false;
    }

    imagecopyresampled($newImg, $source_img, 0, 0, 0, 0, $newWidth, $newHeight, $owidth, $oheight);

    // 生成图片
    switch($otype){
        case 1: imagegif($newImg, $dest); break;
        case 2: imagejpeg($newImg, $dest); break;
        case 3: imagepng($newImg, $dest); break;
    }

    imagedestroy($source_img);
    imagedestroy($newImg);
    
    return is_file($dest)? true : false;
}

好了,请自由发挥吧!

posted @ 2018-11-02 14:05  张悟空  阅读(856)  评论(0编辑  收藏  举报