Giter Club home page Giter Club logo

canvas-draw's Introduction

canvas-draw

License MIT

demo 微信中签名并分享请戳 sign demo

use canvas to draw

Clone

git clone [email protected]:Louiszhai/canvas-draw.git

Build Setup

# install dependencies
npm install

# serve with hot reload at localhost:9588
npm run dev

# build for production with minification
npm run build

# build for production and view the bundle analyzer report
npm run build --report

How to use

canvas-draw基于vue-cli搭建,支持pc和mobile端。其核心代码为src/utils/draw.js,使用方法请参考src/components/Canvas.vue

以下是详细介绍。

支持mobile端时,由于手机尺寸限制,画布甚至包含画布的父级容器往往需要旋转至横屏展示,旋转角度通常有如下三种:

0°	正常
90°	顺时针旋转90°
180°	顺时针旋转180°
-90°	逆时针旋转90°

第一步,旋转画布或其父级容器。

getStyle() {
  const d = document;
  const w = window.innerWidth || d.documentElement.clientWidth || d.body.clientWidth;
  const h = window.innerHeight || d.documentElement.clientHeight || d.body.clientHeight;
  let length = (h - w) / 2;
  let width = w;
  let height = h;

  switch (this.degree) {
    case -90:
      length = -length;
    case 90:
      width = h;
      height = w;
      break;
    default:
      length = 0;
  }
  return {
    transform: `rotate(${this.degree}deg) translate(${length}px,${length}px)`, // rotate后需要translate以适应新的宽高
    width: `${width}px`,
    height: `${height}px`,
    transformOrigin: 'center center', // 指定旋转的中心
  };
},

以上,获取了画布或其父级容器的样式,degree是旋转度数,默认为0。请注意,旋转只是视觉变化,此时canvas的坐标系并没有变化,依然是标准坐标系。因此需要重置画布坐标系。

第二步,初始化canvas画布,支持手写,并重置坐标系。

import Draw from '../utils/draw';
initCanvas() {
  const canvas = document.querySelector('canvas');
  this.draw = new Draw(canvas, -this.degree);
},

接下来就可以尝试手写了,由于画布可能旋转,并且坐标系可能被重置,因此擦除画布内容参考如下。

clear() {
  this.draw.clear();
},

绘画好的内容,需要这么下载(由于移动端webview限制,现仅支持PC端下载)。

download() {
  this.draw.downloadPNGImage(this.draw.getPNGImage());
},

当然,你可以将内容上传至服务器,参考如下。

upload() {
  const image = this.draw.getPNGImage();
  const blob = this.draw.dataURLtoBlob(image);

  const url = ''; // 此处替换为你的远程服务器上传地址
  const successCallback = (response) => {
    console.log(response);
  };
  const failureCallback = (error) => {
    console.log(error);
  };
  this.draw.upload(blob, url, successCallback, failureCallback);
},

除此之外,canvas-draw还内置了scalerotate方法,你可以更灵活地调整画布大小、处理图片旋转等问题,祝使用愉快。

More detail

最后,奉上canvas-draw的实现细节:匠心打造canvas签名组件

License

Released under MIT LICENSE。

canvas-draw's People

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

canvas-draw's Issues

当我页面上有其他dom结构时,绘画的起点就偏移了 ToT...

<div class="header"> <img src="../../../static/img/bg.png" alt="" width="100%"> </div> <div class="line-s"> <van-row> <van-col> <div style="margin-left:6px;"> <i class="iconfont icon-xiezi little-i"></i><span class="title">电子签名</span> </div> </van-col> </van-row> <div class="box-area"> <!-- 签名版 --> <sign/> </div>
当我把header这个img去掉之后,就可以正常签名,但是加上了之后,我的落笔点和实际出来的笔触偏移了很多

这个插件怎么用。。

之前用的其它的是npm i xxx --save就下载到了,这个我把clone的命令复制 运行没用,报了小错,我是想在已有项目中用这个,作者还在么= =

ios 有时候无法签名

不知道是不是组件加载的顺序有问题。ios下有时候无法签名,或者是签名的坐标有问题。重新刷新一下界面就可以了

希望提供文档与demo

已经用在项目中了,不过还是希望能提供完整的文档及demo,这样会有更多的人关注到的~

我在vue中使用该插件,无法绘画

<template>
<div class="evaluation">
    <Header title="服务评分" goBack="true"> </Header>
    <div class="mui-content">
        <div class="form-wrap">
            <form class="mui-input-group">
                <div class="mui-input-row">
                    <label>任务名称</label>
                    <input type="text" placeholder="任务名称">
                </div>
                <div class="mui-input-row">
                    <label>时间安排</label>
                    <div class="self-choose">
                        <div class="self">
                            <div class="before-self">
                                <input type="text" placeholder="事项" readonly>
                                <span>
                                    <svg class="icon svg-icon" aria-hidden="true">
                                        <use xlink:href="#iconrili1"></use>
                                    </svg>
                                </span>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="evaluation-list mt-2">
                    <p class="evaluation-list-content">
                        测试
                    </p>
                    <div class="mui-input-row">
                        <label for="">结果</label>
                        <input type="text">
                    </div>
                </div>
            </form>

            <div class="custom-sign mt-2">
                <p>客户签字:</p>
                <div class="sign-board mt-2">
                    <div class="canvas-img" v-if='!flag'>
                        <img src="https://img.yzcdn.cn/vant/leaf.jpg" alt="签名">
                    </div>
                </div>
                <div class="sign-btn mt-2">
                    <mt-button type='primary' size='small' @click="showPopup"> 客户签名</mt-button>
                </div>

            </div>
            <div class="">
                <van-popup v-model="show" position="bottom" :style="{ height: '100%' }">
                    <div class="canvas-wrap" id="canvasBox" :style="getHorizontalStyle">
                        <canvas id="canvas"></canvas>
                    </div>
                    <div class="sign-btn">
                        <mt-button type='primary' size='small' @touchstart="clear" @mousedown="clear"> 重置</mt-button>
                        <mt-button type='primary' size='small' @click="closePopup">取消</mt-button>
                        <mt-button type='primary' size='small' @touchstart="download" @mousedown="download">确认</mt-button>
                    </div>

                </van-popup>
            </div>

            <div class="footer"></div>
        </div>

        <div class="add-submit">
            <mt-button type="primary" :disabled="isClicked">提交</mt-button>
        </div>
    </div>
    <Tabbar></Tabbar>
</div>
</template>

<script>
import Header from '@/components/Header';
import Tabbar from '@/components/Tabbar';

import {
    serviceSureQueryList, // 确认标准
    taskMainQueryList, //任务信息
} from '@/api/afterSale/serviceScore/index.js'

import Draw from '@/assets/draw/draw.js';

export default {
    name: 'serviceScore',
    data() {
        return {
            isClicked: false,
            task_id: null, //任务id
            flag: false,
            degree: 0,
            signImage: null,
            show: false,
            canvasBox: null,
            scope: [{
                    value: 0,
                    title: '正常',
                },
                {
                    value: 90,
                    title: '顺时针旋转90°',
                },
                {
                    value: 180,
                    title: '顺时针旋转180°',
                },
                {
                    value: -90,
                    title: '逆时针旋转90°',
                },
            ],

        }
    },
    components: {
        Header,
        Tabbar,
        Draw,

    },
    mounted() {
        this.canvasBox = document.getElementById('canvasBox');
        this.initCanvas();
    },
    computed: {
        getHorizontalStyle() {
            const d = document;
            const w = window.innerWidth || d.documentElement.clientWidth || d.body.clientWidth;
            const h = window.innerHeight || d.documentElement.clientHeight || d.body.clientHeight;
            let length = (h - w) / 2;
            let width = w;
            let height = h;
            switch (this.degree) {
                case -90:
                    length = -length;
                case 90:
                    width = h;
                    height = w;
                    break;
                default:
                    length = 0;
            }
            if (this.canvasBox) {
                this.canvasBox.removeChild(document.querySelector('canvas'));
                this.canvasBox.appendChild(document.createElement('canvas'));
                setTimeout(() => {
                    this.initCanvas();
                }, 200);
            }
            return {
                transform: `rotate(${this.degree}deg) translate(${length}px,${length}px)`,
                width: `${width}px`,
                height: `${height}px`,
                transformOrigin: 'center center',
            };
        },
    },
    watch: {

    },
    methods: {
        showPopup() {
            this.show = true;

        },
        closePopup() {
            this.show = false;

        },
        initCanvas() {
            const canvas = document.querySelector('canvas');
            this.draw = new Draw(canvas, -this.degree);
        },
        clear() {
            this.draw.clear();
        },
        download() {
            this.draw.downloadPNGImage(this.draw.getPNGImage());
        },
        savePNG() {
            this.signImage = this.draw.getPNGImage();
        },
        upload() {
            const image = this.draw.getPNGImage();
            const blob = this.draw.dataURLtoBlob(image);
            const url = '';
            const successCallback = (response) => {
                console.log(response);
            };
            const failureCallback = (error) => {
                console.log(error);
            };
            this.draw.upload(blob, url, successCallback, failureCallback);
        },
        getTaskInfo() {
            // 任务id
            this.task_id = this.$route.params.taskId;
            // 获取确认内容
            this.getServiceSureQueryList(this.task_id);
            // 获取任务单主信息
            this.getTaskMainQueryList(this.task_id)
        },
        // 确认标准
        getServiceSureQueryList(taskId) {
            serviceSureQueryList({
                task_id: taskId
            }).then((result) => {
                console.log(result);
            }).catch((err) => {
                console.log(err);
            });
        },
        // 任务单主信息
        getTaskMainQueryList(taskId) {
            taskMainQueryList({
                id: taskId
            }).then((result) => {
                console.log(result);
            }).catch((err) => {
                console.log(err);
            });
        },

    }
}
</script>

<style scoped>
.evaluation {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-color: #fff;
    z-index: 199;
    height: 100%;
}

.mui-content {
    width: 100%;
    height: 100%;
    padding-top: 44px;
    padding-bottom: 50px;
    overflow: scroll;
    background-color: #fff;
}

.form-wrap {
    width: 100%;
    /* padding: 0 .625rem; */
    background-color: #fff;
}

.mui-input-group {
    padding: 0 .625rem;
}

/* 输入框自定义 右侧带有icon 开始 */
.self-choose {
    float: right;
    height: 40px;
    width: 65%;
}

.self {
    height: 100%;
    display: flex;
    display: -webkit-flex;
    justify-content: space-between;
    align-items: center;
}

.before-self {
    position: relative;
    height: 100%;
    width: 100%;
    display: flex;
    display: -webkit-flex;
    justify-content: space-between;
    align-items: center;
}

.before-self input {
    padding-left: 0;
}

.before-self .svg-icon {
    width: 1.4em;
    height: 1.4em;
}

.before-self span:nth-child(2) {
    align-self: center;
}

/* 输入框自定义 右侧带有icon 结束*/

.mui-input-group:before {
    position: absolute;
    top: 0;
    right: 0;
    left: 0;
    height: 0;
    content: '';
    /* -webkit-transform: scaleY(.5); */
    /* transform: scaleY(.5); */
    /* background-color: #c8c7cc; */
}

.mui-input-group:after {
    position: absolute;
    right: 0;
    bottom: 0;
    left: 0;
    height: 0;
    content: '';
    /* -webkit-transform: scaleY(.5); */
    /* transform: scaleY(.5); */
    /* background-color: #c8c7cc; */
}

.evaluation-list {
    padding: .5rem;
    width: 100%;
    border: 1px solid #f2f2f2;
    border-radius: .5rem;
    box-shadow: 1px 2px 3px #ddd;

}

/* 签字板 */
.custom-sign {
    width: 100%;
    padding: 0 .625rem
}

.sign-board {
    width: 100%;
    height: 16rem;
    background-color: #fff;
    border-radius: .5rem;
    /* border: 1px solid #c8c7cc; */
}

/* 写字板图片 */
.canvas-img {
    width: 100%;
    height: 100%;
    border-radius: .5rem;

}

.canvas-img img {
    display: inline-block;
    width: 100%;
    height: 100%;
    margin: 0 auto;
    border-radius: .5rem;

}

.canvas-wrap {
    padding: .625rem;
    width: 100%;
    height: 85%;
    border: 1px solid #c8c7cc;
}

.canvas-wrap #canvas {
    width: 100%;
    height: 85%;
    background-color: #f2f2f2;
    cursor: crosshair;
}

.sign-btn {
    width: 100%;
    height: 15%;
    padding: .625rem;
    display: flex;
    justify-content: space-between;
}


</style>

Ubuntu下npm run dev 和build报错

如题。dev错误日志如下:

0 info it worked if it ends with ok
1 verbose cli [ '/usr/local/node/bin/node',
1 verbose cli   '/usr/local/node/bin/npm',
1 verbose cli   'run',
1 verbose cli   'dev' ]
2 info using [email protected]
3 info using [email protected]
4 verbose run-script [ 'predev', 'dev', 'postdev' ]
5 info lifecycle [email protected]~predev: [email protected]
6 info lifecycle [email protected]~dev: [email protected]
7 verbose lifecycle [email protected]~dev: unsafe-perm in lifecycle true
8 verbose lifecycle [email protected]~dev: PATH: /usr/local/node/lib/node_modules/npm/node_modules/npm-lifecycle/node-gyp-bin:/home/demo/code/canvas-draw/node_modules/.bin:/home/demo/bin:/home/demo/.local/bin:/usr/local/node/bin:/home/demo/jdk1.8.0_181/bin:/home/demo/jdk1.8.0_181/jre/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/home/demo/jdk1.8.0_181/bin:/snap/bin
9 verbose lifecycle [email protected]~dev: CWD: /home/demo/code/canvas-draw
10 silly lifecycle [email protected]~dev: Args: [ '-c', 'node build/dev-server.js' ]
11 silly lifecycle [email protected]~dev: Returned: code: 1  signal: null
12 info lifecycle [email protected]~dev: Failed to exec dev script
13 verbose stack Error: [email protected] dev: `node build/dev-server.js`
13 verbose stack Exit status 1
13 verbose stack     at EventEmitter.<anonymous> (/usr/local/node/lib/node_modules/npm/node_modules/npm-lifecycle/index.js:304:16)
13 verbose stack     at emitTwo (events.js:126:13)
13 verbose stack     at EventEmitter.emit (events.js:214:7)
13 verbose stack     at ChildProcess.<anonymous> (/usr/local/node/lib/node_modules/npm/node_modules/npm-lifecycle/lib/spawn.js:55:14)
13 verbose stack     at emitTwo (events.js:126:13)
13 verbose stack     at ChildProcess.emit (events.js:214:7)
13 verbose stack     at maybeClose (internal/child_process.js:925:16)
13 verbose stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:209:5)
14 verbose pkgid [email protected]
15 verbose cwd /home/demo/code/canvas-draw
16 verbose Linux 4.15.0-36-generic
17 verbose argv "/usr/local/node/bin/node" "/usr/local/node/bin/npm" "run" "dev"
18 verbose node v8.11.3
19 verbose npm  v6.4.0
20 error code ELIFECYCLE
21 error errno 1
22 error [email protected] dev: `node build/dev-server.js`
22 error Exit status 1
23 error Failed at the [email protected] dev script.
23 error This is probably not a problem with npm. There is likely additional logging output above.
24 verbose exit [ 1, true ]

IOS中不能签名啊?

方便的话qq联系 13665179 。 单独运行demo时可以,但是路由跳转到签名页面时就没效果,不能手写签名。

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.