1. 程式人生 > >移動端簽名板的實現

移動端簽名板的實現

直接上程式碼
<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
		<link rel="stylesheet" href="../css/mui.css" />
		<script type="text/javascript" src="../js/mui.js" ></script>
		<script type="text/javascript" src="../js/jquery-3.1.1.min.js" ></script>
	    <script src="../js/bootstrap.js"></script>
	    <link href="../css/bootstrap.min.css" rel="stylesheet" />
	</head>
	<body onload="redea()">
	    <!-- 主頁面標題 -->
	    <header class="mui-bar mui-bar-nav">
	    	<a class=" mui-icon mui-icon-left-nav mui-pull-left mui-action-back"></a> 
	        <h1 class="mui-title" id="title">標題</h1>
	    </header>
	    <!-- 主頁面內容容器 -->
	    <div class="mui-content">
	    	<div class="mui-scroll">
		      <!--  <div class=" mui-media" id="value" style="word-break:break-all">ppp1111</div><br>-->
		        <div style="margin-top:20px;">
		        	<h3>處理者簽名:</h3>
	                <div class="js-signature" id="mySignature"></div>
	                <div>
	                    <button type="button" class="mui-btn" id="myBackColor">選擇背景顏色</button>
	                    <button type="button" class="mui-btn" id="myColor">選擇字型顏色</button>
	                    <div id="colorpanel" style="position:absolute;z-index:99;display:none"></div>
	                    <button type="button" class="mui-btn" id="myEmpty">重寫</button>
	                    <button type="button" class="mui-btn" id="mySave">儲存</button>
	                </div>
	                <div id="myImg"></div>	                
	           </div>
           </div>
	    </div>
	</body>
	<script type="text/javascript">
		mui.init();
		mui.plusReady(function(){
			
		});
		function redea(){
			new WritingPad();
		}
	</script>
</html>
<script type="text/javascript">
/**
 * 功能:簽名canvas面板初始化,為WritingPad.js手寫面板js服務。
 */

(function (window, document, jQuery) {
    'use strict';

  // 獲取繪製螢幕的規則間隔
  window.requestAnimFrame = (function (callback) {
    return window.requestAnimationFrame || 
      window.webkitRequestAnimationFrame ||
      window.mozRequestAnimationFrame ||
      window.oRequestAnimationFrame ||
      window.msRequestAnimaitonFrame ||
      function (callback) {
        window.setTimeout(callback, 1000/60);
      };
  })();

  /*
  * 外掛建構函式
  */

  var pluginName = 'jqSignature',
      defaults = {
        lineColor: '#222222',
        lineWidth: 1,
        border: '1px dashed #CCFF99',
        background: '#FFFFFF',
        width: 500,
        height: 200,
        autoFit: false
      },
      canvasFixture = '<canvas></canvas>';

  function Signature(element, options) {
    // DOM元素/物件
    this.element = element;
    this.jQueryelement = jQuery(this.element);
    this.canvas = false;
    this.jQuerycanvas = false;
    this.ctx = false;
    // Drawing state
    this.drawing = false;
    this.currentPos = {
      x: 0,
      y: 0
    };
    this.lastPos = this.currentPos;
    // 確定外掛的設定
    this._data = this.jQueryelement.data();
    this.settings = jQuery.extend({}, defaults, options, this._data);
    // 初始化外掛
    this.init();
  }

  Signature.prototype = {
    // 初始化簽名畫布
    init: function() {
      // 設定畫布
      this.jQuerycanvas = jQuery(canvasFixture).appendTo(this.jQueryelement);
      this.jQuerycanvas.attr({
        width: this.settings.width,
        height: this.settings.height
      });
      this.jQuerycanvas.css({
        boxSizing: 'border-box',
        width: this.settings.width + 'px',
        height: this.settings.height + 'px',
        border: this.settings.border,
        background: this.settings.background,
        cursor: 'crosshair'
      });
      //將畫布安裝到父寬
      if (this.settings.autoFit === true) {
        this._resizeCanvas();
      }
      this.canvas = this.jQuerycanvas[0];
      this._resetCanvas();
      //設定滑鼠事件
      this.jQuerycanvas.on('mousedown touchstart', jQuery.proxy(function(e) {
        this.drawing = true;
        this.lastPos = this.currentPos = this._getPosition(e);
      }, this));
      this.jQuerycanvas.on('mousemove touchmove', jQuery.proxy(function(e) {
        this.currentPos = this._getPosition(e);
      }, this));
      this.jQuerycanvas.on('mouseup touchend', jQuery.proxy(function(e) {
        this.drawing = false;
        // 觸發更改事件
        var changedEvent = jQuery.Event('jq.signature.changed');
        this.jQueryelement.trigger(changedEvent);
      }, this));
      // 觸控畫布時防止檔案滾動
      jQuery(document).on('touchstart touchmove touchend', jQuery.proxy(function(e) {
        if (e.target === this.canvas) {
          e.preventDefault();
        }
      }, this));
      // 開始畫
      var that = this;
      (function drawLoop() {
        window.requestAnimFrame(drawLoop);
        that._renderCanvas();
      })();
    },
    //重置的畫布
    clearCanvas: function() {
      this.canvas.width = this.canvas.width;
      this._resetCanvas();
    },
    // 把畫布的內容為Base64編碼資料的URL
    getDataURL: function() {
      return this.canvas.toDataURL();
    },

    reLoadData: function () {
        this.jQuerycanvas.remove();
        this._data = this.jQueryelement.data();
        this.init();
    },
    // 獲取滑鼠/觸控的位置
    _getPosition: function(event) {
      var xPos, yPos, rect;
      rect = this.canvas.getBoundingClientRect();
      event = event.originalEvent;
      // 觸控事件
      if (event.type.indexOf('touch') !== -1) { // event.constructor === TouchEvent
        xPos = event.touches[0].clientX - rect.left;
        yPos = event.touches[0].clientY - rect.top;
      }
      // 滑鼠事件
      else {
        xPos = event.clientX - rect.left;
        yPos = event.clientY - rect.top;
      }
      return {
        x: xPos,
        y: yPos
      };
    },
    // 將簽名渲染到畫布
    _renderCanvas: function() {
      if (this.drawing) {
        this.ctx.moveTo(this.lastPos.x, this.lastPos.y);
        this.ctx.lineTo(this.currentPos.x, this.currentPos.y);
        this.ctx.stroke();
        this.lastPos = this.currentPos;
      }
    },
    //重置畫布上下文
    _resetCanvas: function() {
      this.ctx = this.canvas.getContext("2d");
      this.ctx.strokeStyle = this.settings.lineColor;
      this.ctx.lineWidth = this.settings.lineWidth;
    },
    // 調整畫布元素的大小
    _resizeCanvas: function() {
      var width = this.jQueryelement.outerWidth();
      this.jQuerycanvas.attr('width', width);
      this.jQuerycanvas.css('width', width + 'px');
    }
  };

  /*
  * 外掛和初始化
  */

  jQuery.fn[pluginName] = function ( options ) {
    var args = arguments;
    if (options === undefined || typeof options === 'object') {
      return this.each(function () {
        if (!jQuery.data(this, 'plugin_' + pluginName)) {
          jQuery.data(this, 'plugin_' + pluginName, new Signature( this, options ));
        }
      });
    } 
    else if (typeof options === 'string' && options[0] !== '_' && options !== 'init') {
      var returns;
      this.each(function () {
        var instance = jQuery.data(this, 'plugin_' + pluginName);
        if (instance instanceof Signature && typeof instance[options] === 'function') {
            var myArr=Array.prototype.slice.call( args, 1 );
            returns = instance[options].apply(instance, myArr);
        }
        if (options === 'destroy') {
          jQuery.data(this, 'plugin_' + pluginName, null);
        }
      });
      return returns !== undefined ? returns : this;
    }
  };

})(window, document, jQuery);
</script>

<script type="text/javascript">
/**
 * 功能:使用該jQuery外掛來製作線上簽名或塗鴉板,使用者繪製的東西可以用圖片的形式儲存下來。
 */

var WritingPad = function () {

    var current = null;

    jQuery(function () {

        initTable();

        initSignature();

        if (jQuery(".modal")) {
            jQuery(".modal").modal("toggle");
        } else {
            mui.alert("沒用手寫面板");
        }

        jQuery(document).on("click", "#mySave", null, function () {
        	var myImg=jQuery("#myImg").empty();
            var dataUrl = jQuery('.js-signature').jqSignature('getDataURL');
            var img=jQuery('<img>').attr("src",dataUrl);
            jQuery(myImg).append(img);

        });

        jQuery(document).on("click", "#myEmpty", null, function () {
            jQuery('.js-signature').jqSignature('clearCanvas');
        });

        jQuery(document).on("click", "#myBackColor", null, function () {

            jQuery('#colorpanel').css('left', '95px').css('top', '45px').css("display", "block").fadeIn();
            jQuery("#btnSave").data("sender", "#myBackColor");
        });

        jQuery(document).on("click", "#myColor", null, function () {
            jQuery('#colorpanel').css('left', '205px').css('top', '45px').css("display", "block").fadeIn();
            jQuery("#btnSave").data("sender", "#myColor");
        });

        jQuery(document).on("mouseover", "#myTable", null, function () {

            if ((event.srcElement.tagName == "TD") && (current != event.srcElement)) {
                if (current != null) { current.style.backgroundColor = current._background }
                event.srcElement._background = event.srcElement.style.backgroundColor;
                current = event.srcElement;
            }

        });

        jQuery(document).on("mouseout", "#myTable", null, function () {

            if (current != null) current.style.backgroundColor = current._background

        });

        jQuery(document).on("click", "#myTable", null, function () {

            if (event.srcElement.tagName == "TD") {
                var color = event.srcElement._background;
                if (color) {
                    jQuery("input[name=DisColor]").css("background-color", color);
                    var strArr = color.substring(4, color.length - 1).split(',');
                    var num = showRGB(strArr);
                    jQuery("input[name=HexColor]").val(num);
                }
            }

        });

        jQuery(document).on("click", "#btnSave", null, function () {

            jQuery('#colorpanel').css("display", "none");
            var typeData = jQuery("#btnSave").data("sender");
            var HexColor = jQuery("input[name=HexColor]").val();
            var data = jQuery(".js-signature").data();
            if (typeData == "#myColor") {
                data["plugin_jqSignature"]["settings"]["lineColor"] = HexColor;
                jQuery('.js-signature').jqSignature('reLoadData');
            }
            if (typeData == "#myBackColor") {

                data["plugin_jqSignature"]["settings"]["background"] = HexColor;
                jQuery('.js-signature').jqSignature('reLoadData');
            }
        });

        jQuery("#mymodal").on('hide.bs.modal', function () {
            jQuery("#colorpanel").remove();
            jQuery("#mymodal").remove();
            jQuery("#myTable").remove();
        });

    });

    function initTable() {
        var colorTable = "";
        var ColorHex = new Array('00', '33', '66', '99', 'CC', 'FF');
        var SpColorHex = new Array('FF0000', '00FF00', '0000FF', 'FFFF00', '00FFFF', 'FF00FF');
        for (var i = 0; i < 2; i++)
        {
            for (var j = 0; j < 6; j++)
            {
                colorTable = colorTable + '<tr height=12>';
                colorTable = colorTable + '<td width=11 style="background-color:#000000"></td>';

                if (i == 0)
                {
                    colorTable = colorTable + '<td width=11 style="background-color:#' + ColorHex[j] + ColorHex[j] + ColorHex[j] + '"></td>';
                }
                else
                {
                    colorTable = colorTable + '<td width=11 style="background-color:#' + SpColorHex[j] + '"></td>';
                }

                //colorTable = colorTable + '<td width=11 style="background-color:#000000"></td>';

                for (var k = 0; k < 3; k++)
                {
                    for (l = 0; l < 6; l++)
                    {
                        colorTable = colorTable + '<td width=11 style="background-color:#' + ColorHex[k + i * 3] + ColorHex[l] + ColorHex[j] + '"></td>';
                    }
                }
                colorTable = colorTable + '</tr>';


            }
        }
        colorTable =
        '<table border="1" id="myTable" cellspacing="0" cellpadding="0" style="border-collapse: collapse;cursor:pointer;" bordercolor="000000">'
        + colorTable + '</table>' +
        '<table width=225 border="0" cellspacing="0" cellpadding="0" style="border:1px #000000 solid;border-collapse: collapse;background-color:#000000">' +
        '<tr style="height:30px">' +
        '<td colspan=21 bgcolor=#cccccc>' +

        '<table cellpadding="0" cellspacing="1" border="0" style="border-collapse: collapse">' +
        '<tr>' +
        '<td width="3"><input type="text" name="DisColor" size="6" disabled style="border:solid 1px #000000;background-color:#ffff00"></td>' +
        '<td width="3"><input type="hidden" name="HexColor" size="7" style="border:inset 1px;font-family:Arial;" value="#000000" ></td>' +
         '<td width="3"><button type="button" class="btn btn-primary btn-sm" id="btnSave">確認</button></td>' +
        '</tr>' +
        '</table>' +
       
        '</td>' +
        '</tr>' +
        '</table>';
        jQuery("#colorpanel").append(colorTable);
    }

    function initSignature() {

        if (window.requestAnimFrame) {
            var signature = jQuery("#mySignature");
            signature.jqSignature({ width:300, height: 260, border: '1px solid #CDC9A5', background: '#EEEED1', lineColor: '#969696', lineWidth: 2, autoFit: false });
        } else {

            mui.alert("請載入jq-signature.js");
            return;
        }
    }

    function showRGB(arr) {
        hexcode = "#";
        for (x = 0; x < 3; x++) {
            var n = arr[x];
            if (n == "") n = "0";
            if (parseInt(n) != n)
                return mui.alert("RGB顏色值不是數字!");
            if (n > 255)
                return mui.alert("RGB顏色數字必須在0-255之間!");
            var c = "0123456789ABCDEF", b = "", a = n % 16;
            b = c.substr(a, 1); a = (n - a) / 16;
            hexcode += c.substr(a, 1) + b
        }
        return hexcode;
    }

    function init() {


    }

    return {
        init: function () {
            init();
        }
    };
}
</script>
效果圖

相關推薦

移動簽名實現

直接上程式碼<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> <link rel="stylesheet" href="../cs

pc移動拖拽實現

ack spa listen prev odi nth 獲取 lock top #div1 { width: 100px; height: 100px; background: red; position: absolute; }

移動用rem實現 和 用jq實現的兩種方法

隨著現在移動端越來越方便,專案中移動端的web頁面也越來越多。除了用Bootstrap這種自適應的前端開發工具包,經常用到的就是rem佈局和jq實現兩種方法。rem結合了css3的media媒體查詢,同時我必須要說的是felx佈局,用起來真的覺得很方便。方便,方

web移動:touchmove實現區域性滾動

總結一下最近專案用到的一個功能點,具體要求如下: body中會呈現一個可滾動的長頁面,在點選某個按鈕的時候,會出現一個彈出框,由於彈出框的內容較長,會出現滾動條,但是要保證位於彈框下部的body在彈框滾動的時候不觸發滾動事件 實現效果圖如下: 一.

input type=“file” 在移動H5頁面實現呼叫本地相簿、拍照、錄音

<input type="file" accept="image/*" mutiple="mutiple" capture="camera" /> 三個屬性: accept - 規定可提交的檔案型別。 capture - 系統所捕獲的預設裝置。camera(照相機),camc

移動1px邊框實現

Retina螢幕,裝置畫素比,移動端的邊框在這些螢幕上1px  會表現處2px,3px畫素的寬度,所以出現各種解決方案,今天只總結一種,以後慢慢補充。。通過偽類 ::after。,原理就是通過tra

移動通過JQ實現瀑布流效果方法

近期做了一個移動端的搜尋瀑布流的效果,現在這種前端效果被廣泛使用在各大無限裝置上,方便、簡潔、流暢是其最大特性!這次的效果是頁面每行三個div展示內容,共三行。最底部用文字“獲取更多”來提示使用者點選“獲取更多”通過JQ實現頁面無重新整理從資料庫查詢新的內容,並插入到原內容底

hbuilder的移動APP如何實現微信支付,求具體流程詳解

HBuilder 基座已實現H5 plus的支付API,現已整合支付寶快捷支付平臺。使用支付功能前必須在支付寶網站開通”快捷支付“服務,並配置伺服器生成訂單資訊。 開發指導 支付流程如下: plus API使用步驟: 1. 呼叫plus.payment.getChan

使用websocket實現手機掃描PC二維碼,移動canvas手繪簽名確定後將圖片同步到PC 掃碼及時更新圖片

這個Demo我放到線上啦,大家可以試一下(前端是用vue寫的,後臺是用springboot寫的 還處於學習階段  幫不到各位大神也請各位輕點噴我們首先看下效果,我把圖截下來來:1.這個是線上地址開啟的頁面2.這是掃描二維碼後手機開啟的介面(不要用微信去掃,微信顯示不安全  用

JS pc移動共同實現復制到剪貼功能實現

oct com put 而是 minimum size func char ror JS pc端和移動端實現復制到剪貼板功能實現 在網頁上復制文本到剪切板,一般是使用JS+Flash結合的方法,網上有很多相關文章介紹。隨著 HTML5 技術的發展,Flash 已經在很多場合

VS2013下實現移動的跨平臺開發

event 關系 擴展 真機測試 trap 框架 intel als pac http://www.th7.cn/Program/Android/201412/336394.shtml 前一天準備下載VS2015預覽版,到VisualStudio官網一看,發現微軟發布了

使用css 3實現 移動 文本 點點的效果

ext overflow webkit wrap kit hidden -c pre idt { width: 200px; text-overflow: ellipsis; /*white-space: nowrap;*/ overflow: hi

實現移動touch事件的橫向滑動列表效果

parseint 滑動 borde lec let doc kit order mov 要實現手機端橫向滑動效果並不難,了解實現的原理及業務邏輯就很容易實現。原理:touchstart(手指按下瞬間獲取相對於頁面的位置)——》touchmove(手指移動多少,元素相應移動多

JS實現移動下拉刷新更多分頁請求功能方法2.0

keyframes 發生 usb 第一次 odr back eight urn 返回頂部 本次2.0升級版為js實現移動端加載更多下拉刷新更多分頁請求功能方法(數據一次請求,前端分頁,適用於數據流量較少,數據量壓力小的頁面)同時新增loading組件,turnToTop組件

移動web頭像上傳實現截取和照片方向修復

trac 支持 隱藏 gre jquery 頭像 圖像加載 fun 僅供參考 實戰所需js包: jQuery、Jcrop、EXIF 本次實戰功能是在 app 中的 我的客戶 的客戶信息頁面中實現移動端web的頭像上傳,本次沒有實現圖像拖拽、縮放的觸摸事件功能(Jcro

Unity NGUI實現移動輸入法取認事件響應

輸入法時間NGUI已經實現了事件的監聽功能,看下圖:On Return Key(選擇Snbmit) ,可以直接註冊監聽事件。實現如下:1、搭建一個簡單場景2、新建一個腳本InputTest.cs 掛載在Input物體下,並拖拽賦值Txt_content, inputusing UnityEngine; //

移動頁面實現多行文本溢出顯示省略號...

一個 bsp 獵豹 oid col spa 移動 clas 搜狗 手機瀏覽器種類: UC瀏覽器,QQ瀏覽器,歐朋瀏覽器,百度手機瀏覽器,360安全瀏覽器,谷歌瀏覽器,搜狗手機瀏覽器,獵豹瀏覽器,其他雜牌瀏覽器 國內的UC和QQ,百度等手機瀏覽器都是根據Webkit修改過來的

【js】再談移動的模態框實現

其中 這就是 層級關系 成了 移動 top 做了 rop 操作   移動端模態框的機制因為與PC的模態框機制一直有所區別,一直是許多新人很容易踩坑的地方,最近筆者作為一條老鹹魚也踩進了一個新坑中,真是平日裏代碼讀得太粗略,故而寫上幾筆,以儆效尤。   故事的起因是這樣的,兄

實現移動頂部與底部固定,內容區優化的效果

tro 好的 中心 use cal ul li dea tex 出場 實現頂部與底部固定的效果十分容易,且很多人都會選擇用這個方式,就是頂部position:fixed,底部也position:fixed。實現的效果就像下面兩張圖,container區域是布滿整個屏幕的,且

用偽元素寫移動1px邊框時想實現邊角效果

ack img ive cal left image event 發現 邊框 做移動端頁面時,又想用偽元素做真實1像素邊框,又想有邊角時,會發現只加一個border-radius時出來的效果邊款並沒有變成圓角,解決辦法是加兩個border-radius <div c