1. 程式人生 > >整合一個好用的canvas簽名板

整合一個好用的canvas簽名板

目錄

專案地址

開箱可用, 此專案的作者在程式碼中做了詳細的註釋。

上程式碼

將它整合到你的專案中需要四個檔案。

前端程式碼

<!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;
}

好了,請自由發揮吧!