专注收集记录技术开发学习笔记、技术难点、解决方案
网站信息搜索 >> 请输入关键词:
您当前的位置: 首页 > HTML5

HTML5 中canvas支持触摸屏的签字面板

发布时间:2010-05-20 14:01:29 文章来源:www.iduyao.cn 采编人员:星星草
HTML5 中canvas支持触摸屏的签名面板

1.前言

       最近实在是太忙了,从国庆之后的辞职,在慢慢的找工作,到今天在现在的这家公司上班大半个月了,太多的心酸泪无以言表,面试过程中,见到的坑货公司是一家又一家,好几家公司自己都只是上一天班就走了,其中有第一天上班就加班到10点的,有一家公司在体育西路那边,太远,第一天回家挤公交也是太累,以前上班都是走路上班的,自己确实不适合挤公交,还有的公司面试的时候和你说什么大数据,性能优化什么的,进公司一看,他们就是用的最简单的三层,没有什么设计模式,总之太多心酸,幸运的是现在这家公司还不错,找工作就是要宁缺毋滥。

2.canvcas标签

canvas基础教程:<canvas> 标签定义图形,比如图表和其他图像。HTML5 的 canvas 元素使用 JavaScript 在网页上绘制图像。甚至可以在 canvas 上创建并操作动画,这不是使用画笔和油彩所能够实现的。跨所有 web 浏览器的完整 HTML5 支持还没有完成,但在新兴的支持中,canvas 已经可以在几乎所有现代浏览器上良好运行。canvas 拥有多种绘制路径、矩形、圆形、字符以及添加图像的方法。来公司一个月了主要也是学习为主,我是做后台开发,以前也没有用过Oracle数据库,这一个月也主要是学习H5的一些新特新,还有就是css3.0,在就是Oracle在服务器上面的安装部署,一些数据导入导出,数据备份啥的,前端的东西都比较差,现在也是一个学习的机会,就当好好学习了。

3.手写签名面板

公司做的是自动化办公OA系统,一些审核的地方需要加入一些手写签名的功能,刚开始做这个也是没有思路,在网上也找了一下资料,后来发现H5有这个canvcas新标签,感到格外是欣喜。于是拿过来试一下,还真可以。

4.页面代码

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Testpage</title>
    <script src="~/Assets/jquery-2.1.1.js"></script>
    <script src="~/Assets/bootstrap/bootstrap.js"></script>
    <link href="~/Assets/bootstrap/bootstrap.css" rel="stylesheet" />
    <script src="~/Scripts/WritingPad.js"></script>
    <script src="~/Assets/jq-signature.js"></script>
</head>
<body style="background-color:#b6ff00">

    <button class="btn btn-primary" type="button" style="position:relative">点击我</button>

</body>
</html>
<script>

    $(function () {

        $(".btn,.btn-primary").click(function () {
            var wp = new WritingPad();
            //wp.init();
        });
    });

</script>

5.脚本代码一

/**
 * 功能:签名canvas面板初始化,为WritingPad.js手写面板js服务。
 * 作者:黄金锋 (549387177@qq.com)
 * 日期:2015-11-15  15:51:01
 * 版本:version 1.0
 */

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

  // Get a regular interval for drawing to the screen
  window.requestAnimFrame = (function (callback) {
    return window.requestAnimationFrame || 
      window.webkitRequestAnimationFrame ||
      window.mozRequestAnimationFrame ||
      window.oRequestAnimationFrame ||
      window.msRequestAnimaitonFrame ||
      function (callback) {
        window.setTimeout(callback, 1000/60);
      };
  })();

  /*
  * Plugin Constructor
  */

  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 elements/objects
    this.element = element;
    this.$element = $(this.element);
    this.canvas = false;
    this.$canvas = false;
    this.ctx = false;
    // Drawing state
    this.drawing = false;
    this.currentPos = {
      x: 0,
      y: 0
    };
    this.lastPos = this.currentPos;
    // Determine plugin settings
    this._data = this.$element.data();
    this.settings = $.extend({}, defaults, options, this._data);
    // Initialize the plugin
    this.init();
  }

  Signature.prototype = {
    // Initialize the signature canvas
    init: function() {
      // Set up the canvas
      this.$canvas = $(canvasFixture).appendTo(this.$element);
      this.$canvas.attr({
        width: this.settings.width,
        height: this.settings.height
      });
      this.$canvas.css({
        boxSizing: 'border-box',
        width: this.settings.width + 'px',
        height: this.settings.height + 'px',
        border: this.settings.border,
        background: this.settings.background,
        cursor: 'crosshair'
      });
      // Fit canvas to width of parent
      if (this.settings.autoFit === true) {
        this._resizeCanvas();
      }
      this.canvas = this.$canvas[0];
      this._resetCanvas();
      // Set up mouse events
      this.$canvas.on('mousedown touchstart', $.proxy(function(e) {
        this.drawing = true;
        this.lastPos = this.currentPos = this._getPosition(e);
      }, this));
      this.$canvas.on('mousemove touchmove', $.proxy(function(e) {
        this.currentPos = this._getPosition(e);
      }, this));
      this.$canvas.on('mouseup touchend', $.proxy(function(e) {
        this.drawing = false;
        // Trigger a change event
        var changedEvent = $.Event('jq.signature.changed');
        this.$element.trigger(changedEvent);
      }, this));
      // Prevent document scrolling when touching canvas
      $(document).on('touchstart touchmove touchend', $.proxy(function(e) {
        if (e.target === this.canvas) {
          e.preventDefault();
        }
      }, this));
      // Start drawing
      var that = this;
      (function drawLoop() {
        window.requestAnimFrame(drawLoop);
        that._renderCanvas();
      })();
    },
    // Clear the canvas
    clearCanvas: function() {
      this.canvas.width = this.canvas.width;
      this._resetCanvas();
    },
    // Get the content of the canvas as a base64 data URL
    getDataURL: function() {
      return this.canvas.toDataURL();
    },

    reLoadData: function () {
        this.$canvas.remove();
        this._data = this.$element.data();

        //for (var i in this.settings) {
        //    alert(i+":"+this.settings[i]);
        //}

        //this.settings = $.extend({}, defaults, this._data);
        this.init();
    },
    // Get the position of the mouse/touch
    _getPosition: function(event) {
      var xPos, yPos, rect;
      rect = this.canvas.getBoundingClientRect();
      event = event.originalEvent;
      // Touch event
      if (event.type.indexOf('touch') !== -1) { // event.constructor === TouchEvent
        xPos = event.touches[0].clientX - rect.left;
        yPos = event.touches[0].clientY - rect.top;
      }
      // Mouse event
      else {
        xPos = event.clientX - rect.left;
        yPos = event.clientY - rect.top;
      }
      return {
        x: xPos,
        y: yPos
      };
    },
    // Render the signature to the canvas
    _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;
      }
    },
    // Reset the canvas context
    _resetCanvas: function() {
      this.ctx = this.canvas.getContext("2d");
      this.ctx.strokeStyle = this.settings.lineColor;
      this.ctx.lineWidth = this.settings.lineWidth;
    },
    // Resize the canvas element
    _resizeCanvas: function() {
      var width = this.$element.outerWidth();
      this.$canvas.attr('width', width);
      this.$canvas.css('width', width + 'px');
    }
  };

  /*
  * Plugin wrapper and initialization
  */

  $.fn[pluginName] = function ( options ) {
    var args = arguments;
    if (options === undefined || typeof options === 'object') {
      return this.each(function () {
        if (!$.data(this, 'plugin_' + pluginName)) {
          $.data(this, 'plugin_' + pluginName, new Signature( this, options ));
        }
      });
    } 
    else if (typeof options === 'string' && options[0] !== '_' && options !== 'init') {
      var returns;
      this.each(function () {
        var instance = $.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') {
          $.data(this, 'plugin_' + pluginName, null);
        }
        //if (options === 'reLoadData') {
        //    //this.$canvas.remove();
        //    $.data(this, 'plugin_' + pluginName, null);
        //    this._data = this.$element.data();
        //    this.settings = $.extend({}, defaults, options, this._data);
        //    this.init();
        //}
      });
      return returns !== undefined ? returns : this;
    }
  };

})(window, document, jQuery);

6.脚本代码二

/**
 * 功能:使用该jQuery插件来制作在线签名或涂鸦板,用户绘制的东西可以用图片的形式保存下来。
 * 作者:黄金锋 (549387177@qq.com)
 * 日期:2015-11-16  13:51:01
 * 版本:version 1.0
 */

var WritingPad = function () {

    var current = null;

    $(function () {

        initHtml();

        initTable();

        initSignature();

        if ($(".modal")) {
            $(".modal").modal("toggle");
        } else {
            alert("没用手写面板");
        }

        $(document).on("click", "#myClose,.close", null, function () {
            $('#mymodal').modal('hide');
            $("#mymodal").remove();

        });

        $(document).on("click", "#mySave", null, function () {

            var myImg = $('#myImg').empty();
            var dataUrl = $('.js-signature').jqSignature('getDataURL');
            var img = $('<img>').attr('src', dataUrl);
            $(myImg).append($('<p>').text("图片保存在这里"));
            $(myImg).append(img);

        });

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

        });

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

            $('#colorpanel').css('left', '95px').css('top', '45px').css("display", "block").fadeIn();
            //$("canvas").css("background", "#EEEEEE");
            $("#btnSave").data("sender", "#myBackColor");
        });

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

        $(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;
                //$("input[name=DisColor]").css("background-color", event.srcElement.style.backgroundColor);
                //var color = event.srcElement.style.backgroundColor;
                //var strArr = color.substring(4, color.length - 1).split(',');
                //var num = showRGB(strArr);
                //$("input[name=HexColor]").val(num);
                current = event.srcElement;
            }

        });

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

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

        });

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

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

        });

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

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

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

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

    });

    function initHtml() {

        var html = '<div class="modal" id="mymodal">' +
            '<div class="modal-dialog">' +
                '<div class="modal-content">' +
                    '<div class="modal-header">' +
                        '<button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">&times;</span><span class="sr-only">Close</span></button>' +
                        '<h4 class="modal-title">手写面板</h4>' +
                    '</div>' +
                    '<div class="modal-body">' +
                        '<div class="js-signature" id="mySignature">' +
                         '</div>' +
                         '<div>' +
                         '<button type="button" class="btn btn-default" id="myEmpty">清空面板</button>' +
                         '<button type="button" class="btn btn-default" id="myBackColor">设置背景颜色</button>' +
                         //'<div style="position:absolute;relative">' +
                         '<button type="button" class="btn btn-default" id="myColor">设置字体颜色</button>' +
                         '<div id="colorpanel" style="position:absolute;z-index:99;display:none"></div>' +
                         //'</div>'+
                         '</div>' +
                    '</div>' +
                    '<div class="modal-footer">' +

                        '<button type="button" class="btn btn-default" id="myClose">关闭</button>' +
                        '<button type="button" class="btn btn-primary" id="mySave">保存</button>' +
                        '<div id="myImg">' +
                        '<div>' +

                    '</div>' +
                '</div>' +
            '</div>' +
        '</div>';

        $('body').append(html);
    }

    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="text" 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>';
        $("#colorpanel").append(colorTable);
    }

    function initSignature() {

        if (window.requestAnimFrame) {
            var signature = $("#mySignature");
            signature.jqSignature({ width: 500, height: 200, border: '1px solid red', background: '#16A085', lineColor: '#ABCDEF', lineWidth: 2, autoFit: false });
            //{ width: 600, height: 200, border: '1px solid red', background: '#16A085', lineColor: '#ABCDEF', lineWidth: 2, autoFit: true }
        } else {

            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 alert("RGB颜色值不是数字!");
            if (n > 255)
                return 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();
        }
    };
}

 

8楼敷衍不起
沙发。
Re: 枫伶忆
@敷衍不起,你是天天在博客园待着,我是好久都没这么有时间了。
7楼井传红
入职不签合同,给双方留下反悔的机会这办法优点和缺点也比较明显,公司观察入职人员是否如简历上面那般合格,应聘者考察公司环境是否理想。优点是给双方留了后路,缺点也在此,公司基本留不住人,如果不怎么样的公司基本就是流动性的市场。。。
Re: 枫伶忆
@井传红,引用入职不签合同,给双方留下反悔的机会这办法优点和缺点也比较明显,公司观察入职人员是否如简历上面那般合格,应聘者考察公司环境是否理想。优点是给双方留了后路,缺点也在此,公司基本留不住人,如果不怎么样的公司基本就是流动性的市场。。。,,说的有道理,入职本来就应该签合同的
6楼井传红
这还叫前端差?我这个做前端的要撞墙了
5楼井传红
那个脚本代码一写的我都看不懂了,需要一行行看下来 但写不出来,组件化的风格真是需要水平的
Re: 枫伶忆
@井传红,引用那个脚本代码一写的我都看不懂了,需要一行行看下来 但写不出来,组件化的风格真是需要水平的,,这特别是这些功能要写成通用的js,是要水平的,我们公司的js都要写成通用的,加载也是异步加载,用require.js,像什么a,li标签的hover都要写成通用的,js都用命名空间来管理,你写的js在注册到项目的命名空间下,以前做后台前端都没怎么写过,现在都要学习一下。
4楼井传红
你上一天班就不干了 那入职不都是签合同 办手续 办体检什么的耗时很长吗,这不干了还得把那些手续啥的都退回来拿回体检报告。。。几家公司这么下来,那光等待入职的时间就半个月过去了
Re: 枫伶忆
@井传红,引用你上一天班就不干了 那入职不都是签合同 办手续 办体检什么的耗时很长吗,这不干了还得把那些手续啥的都退回来拿回体检报告。。。几家公司这么下来,那光等待入职的时间就半个月过去了,,广州这边的公司都比较贼吧,第一天都不签合同的,大部分公司都是一个星期才钱合同,有的公司还是半个月签合同,如果他要这些资料我都是给复印件,特别是离职证明,我说我要提取公积金,过一段时间在给他们,这个都是自己的选择,外面的公司在坑了,他们说的在好,只有你去公司里面了才知道,其实也没有什么,也有耽误几天时间,我坚信一个公司有什么是你不能容忍的,迟到你还是坚持不下去的...
3楼_Skywalker
屌的一比
Re: 枫伶忆
@_Skywalker,引用屌的一比,前端很差,真正学习中,感谢支持
2楼强大大
原来你是广州的,我也是广州的在软件园这边
Re: 枫伶忆
@强大大,引用原来你是广州的,我也是广州的在软件园这边,广州小伙伴很多,一起加油...
1楼浮云也是种寂寞
看你这博客 真心木有感觉到你所说的前端差
Re: 枫伶忆
@浮云也是种寂寞,引用看你这博客 真心木有感觉到你所说的前端差,目前在公司还看不到后台代码,转正才能看,经理也督促我加强js,正在努力修炼中,没办法人都是被逼出来的
友情提示:
信息收集于互联网,如果您发现错误或造成侵权,请及时通知本站更正或删除,具体联系方式见页面底部联系我们,谢谢。

其他相似内容:

  • 使用HBuilder编辑器将html五页面打包成APP

    使用HBuilder编辑器将html5页面打包成APP   使用HBuilder编辑器将html5页面打包成APP (ios+安卓) 1.首先先安装HBuilder编...

  • 基于phonegap,html5,ratchet,handlebars等技术的微神情APP

    基于phonegap,html5,ratchet,handlebars等技术的微表情APP 该app是由很多有意思的微表情构成的,支持40种表情,并且每种表情都有不同的...

  • HTML5 Web 客户端五种离线储存方式汇总

    HTML5 Web 客户端五种离线存储方式汇总 最近折腾HTML5游戏需要离线存储功能,便把目前可用的几种HTML5存储方式研究了下,基于H...

  • SPICE-HTML5 鼠标指针BUG修补

    SPICE-HTML5 鼠标指针BUG修复 研究SPICE,找到了他们官方指定的HTML5客户端。 下载下来用一下,发现跟网页VNC的水平差不多了。 http:...

  • HTML5+JS 《五子飞》游戏实现(5)移动棋子

    HTML5+JS 《五子飞》游戏实现(五)移动棋子 上一章 我们知道了怎么处理两个重要的吃棋动作,想要吃对方的棋子,首先得移动自己的棋子。...

  • HTML5中怎么上传Resize后的图片

    HTML5中如何上传Resize后的图片 参考资料: 不依赖form标签,而是自己定义FormData上传数据,文件被编码为一个Blob或File对象: https...

  • (1)HTML5

    (一)HTML5 可以解决什么问题: 可以实现网页的ajax加载,同时又能完成URL的改变而没有网页跳转刷新的迹象,就像是改变了网页的hash(#)一样。...

  • 一款纯html5实现的钟表

    一款纯html5实现的时钟 今天给大家分享一款非常漂亮的纯html5实现的时钟。整个界面都由html5绘制而成。一起看下效果图: 在线预览...

  • 使用 WebSockets 开展 HTML5 视频直播

    使用 WebSockets 进行 HTML5 视频直播 实验环境:Ubuntu。 参考以下两个链接进行实践: http://segmentfault.com/blog/xingrz/119...

  • 查询浏览器是不是支持html5

    查询浏览器是否支持html5 js判断 插入js代码====================================================== <script> wind...

热门推荐: