vue用canvas横屏签名
最近遇到一个签名需求由于canvas一些特性,横屏签名不好控制,也是多方借鉴才解决,写真就是为了记录下,方便有需要的同学。
js代码如下:
import Draw from "../../../libs/draw";
export default {
name: "canvas",
data() {
return {
degree: 0 // 屏幕整体旋转的角度, 可取 -90,90,180等值
};
},
components: {
Draw
},
inject: ["reload"],
mounted() {
this.canvasBox = document.getElementById("canvasBox");
this.initCanvas();
var evt = "onorientationchange" in window ? "orientationchange" : "resize";
var that = this;
window.addEventListener(
evt,
function() {
// alert(evt);
setTimeout(function() {
that.reload();
}, 300);
},
false
);
},
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;
if (width < height) {
this.degree = 90;
width = h;
height = w;
} else {
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"
};
}
},
methods: {
initCanvas() {
const canvas = document.querySelector("canvas");
this.draw = new Draw(canvas, -this.degree);
},
clear() {
this.draw.clear();
},
download() {
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);
}
}
};
html代码:
<template>
<div id="canvasBox" :style="getHorizontalStyle">
<canvas style="background-color:#fff;"></canvas>
<div class="greet">
<div class="btnBox">
<div class="btn" @click.native="clear()">重置</div>
<div class="btn" @click.native="download()" style="backgroundColor:#409EEF">确认</div>
</div>
</div>
</div>
</template>
css部分
<style lang="less" scoped>
#canvasBox {
display: flex;
flex-direction: column;
height: 100%;
}
.greet {
padding: 20px;
font-size: 20px;
user-select: none;
}
.greet a {
cursor: pointer;
}
.greet select {
font-size: 18px;
}
canvas {
flex: 1;
cursor: crosshair;
}
.btnBox {
padding: 0 2%;
box-sizing: border-box;
.btn {
text-align: center;
color: #fff;
background-color: #f91;
height: 40px;
line-height: 40px;
font-weight: 300;
font-size: 1em;
border-radius: 4px;
}
}
</style>
这个项目需要一个插件draw.js
毕竟不是app无法控制横竖屏,所以本来是横屏就直接签名,竖屏旋转。