本文实例为大家分享了VUE使用canvas实现签名组件的具体代码,供大家参考,具体内容如下
效果如下:
- <template>
- <div class="sign">
- <div class="content">
- <canvas id="canvas" :width="width" :height="height"/>
- </div>
- <div class="btn">
- <button @click="clearCanvas()">清除</button>
- <button @click="save()">保存</button>
- </div>
- </div>
- </template>
- <script>
- export default {
- name: 'App',
- data () {
- return {
- };
- },
- props: {
- // 画布宽度
- width: {
- type: Number,
- default: window.innerWidth
- },
- // 画布高度
- height: {
- type: Number,
- default: 500
- },
- // 笔触半径
- radius: {
- type: Number,
- default: 10
- },
- // 笔触颜色
- color: {
- type: String,
- default: '#000'
- },
- // 画布填充背景
- fillStyle: {
- type: String,
- default: '#ccc'
- }
- },
- created () {
- },
- mounted (){
- this.int();
- },
- methods: {
- // 绘制涂擦效果圆形
- // @param { integer } 圆心的x坐标
- // @param { integer } 圆心的y坐标
- // @param { integer } 圆心半径
- // @param { string } 填充的颜色
- fillCircle (ctx, x, y, radius, fillColor) {
- ctx.fillStyle = fillColor || this.color;
- ctx.beginPath();
- ctx.moveTo(x, y);
- ctx.arc(x, y, radius, 0, Math.PI * 2, false); // 标准画圆
- ctx.fill();
- },
- // 保存图片
- save (name = '签名图片') {
- let imgBase64 = this.canvas.toDataURL('image/png'); // 获取截图base64, 1表示质量(无损压缩)
- let a = document.createElement('a');
- a.download = name + '.png'; // 必须要设置download属性才能够直接下载base64图片
- a.href = imgBase64;
- a.click(); // 触发点击,起到下载效果
- },
- // 清除画布
- clearCanvas () {
- let canvas = this.canvas;
- canvas.getContext('2d').fillStyle = this.fillStyle;
- canvas.getContext('2d').fillRect(0, 0, this.width, this.height);
- },
- // 数据初始化
- int () {
- this.canvas = document.querySelector('#canvas');
- let ctx = this.canvas.getContext('2d');
- let move = false; // 按下标识
- ctx.fillStyle = this.fillStyle;
- ctx.fillRect(0, 0, this.width, this.height);
- // 事件兼容PC 移动端
- let eventStart = 'ontouchstart' in document ? 'touchstart' : 'mousedown';
- let eventMove = 'ontouchmove' in document ? 'touchmove' : 'mousemove';
- let eventEnd = 'ontouchend' in document ? 'touchend' : 'mouseup';
- this.canvas.addEventListener(eventStart, (e) => {
- console.log(e);
- let sx = e.touches ? e.touches[0].pageX : e.pageX;
- let sy = e.touches ? e.touches[0].pageY : e.pageY;
- move = true;
- this.fillCircle(ctx, sx, sy, this.radius);
- }, false);
- this.canvas.addEventListener(eventMove, (e) => {
- let sx = e.touches ? e.touches[0].pageX : e.pageX;
- let sy = e.touches ? e.touches[0].pageY : e.pageY;
- move && this.fillCircle(ctx, sx, sy, this.radius);
- }, false);
- this.canvas.addEventListener(eventEnd, (e) => {
- move = false;
- }, false);
- }
- }
- };
- </script>
- <style lang="less" scoped>
- .sign{
- .btn {
- padding:10px;
- button {
- height: 50px;
- width:100%;
- margin-bottom:10px;
- font-size: 20px;
- }
- }
- }
- </style>
复制代码以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持中国红客联盟。 |