赞
踩
使用vue-cli4脚手架,js-signature 2.0.0(https://www.npmjs.com/package/jq-signature)jquery 3.4.1。
1.安装jq及js-signature(js-siganture依赖于jquery)
npm i jquery jq-signature -S
2.小插曲->若只使用jquery,只需要在使用的组件中导入或者在入口main.js中配置
2.1 方式一 :组件中直接使用
- <template>
- <div id="test">
- </div>
- <script>
- import $ from 'jquery';
- export default{
- mounted(){
- let dv = $("#test");
- console.log(dv)
- }
- }
- </script>
2.2方式二:
main.js中配置
- import Vue from 'vue'
- import App from './App.vue'
- import Router from './router'
- import Store from './store'
- import $ from 'jquery'
-
- Vue.prototype.$ = $;
-
- new Vue({
- Router,
- Store,
- render:h=>h(App)
- }).$mount('#app')
使用:
- <template>
- <div id="test">
- </div>
- <script>
- export default{
- mounted(){
- let dv = this.$("#test");
- console.log(dv)
- }
- }
- </script>
3。言归正传,开始电子签名,需要在vue.config.js中配置jquery插件,否则jq-signature会报错:jQuery is undefined
vue.config.js配置如下
- const webpack = require('webpack')
- module.exports = {
- chainWebpack:config=>{
- config.plugin('provide').use(webpack.ProvidePlugin,[
- {
- $:'jquery',
- jquery:'jquery',
- jQuery:'jquery',
- 'window.jQuery':'jquery'
- }
- ])
- }
- }
使用:
- <template>
- <div id="app">
- <div id="signature" style="width:100%;height:300px;"></div><!-- 画布容器 -->
- <button id="clearSignature" @click='clearSignature'>清除签名</button>
- <button id="saveSignature" @click='saveSignature'>保存签名</button>
- <div id="result"></div><!-- 预览容器 -->
- </div>
- </template>
- <script>
- import 'jq-signature'//也可以在入口js文件main.js中导入,则此处不用在导入
- export default {
- data(){
- return{
-
- }
- },
- mounted(){
- $('#signature').jqSignature({
- width:'300',//canvas 宽度,默认值300
- height:'200',//canvas 高度,默认值100
- border:'1px solid #ff6700',//canvas 边框,默认值'1px solid red'
- background:'#ddd',//canvas 背景,默认值'#ffffff'
- lineColor:"#0A4D82",//签名线条颜色,默认值'#222222'
- lineWidth:3,//签名线条宽度,默认值1
- autoFit:true//使canvas的宽度充满父元素,默认值 false
- })
- },
- methods:{
- clearSignature(){
- $('#result').html('')//清除预览img
- $('#signature').jqSignature('clearCanvas')//清除canvas
- },
- saveSignature(){
- let signatureBox = $('#signature');
- let canvas = signatureBox.children('canvas').eq(0)[0]
- let data = signatureBox.jqSignature('getDataURL');//base64数据
- //创建一个空的canvas,判断是否画布为空
- var blankCanvas = document.createElement('canvas');
- blankCanvas.width = canvas.width;
- blankCanvas.height = canvas.height;
- if(blankCanvas.toDataURL() == canvas.toDataURL()){
- alert('请签名')
- return;
- }
- //为了解决在ios设备上修改img标签src地址无效的问题,所以每次保存重新创建一个预览img标签,在清除签名时,在移除img标签
- let img = new Image();
- img.src = data;
- img.onload = (e)=>{
- $('#result').append(img)
- }
- img.onerror = (e)=>{
- console.log('预览失败')
- }
- }
- }
- }
- </script>
效果图:
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。