html
<template>
<div class="canvas">
<canvas id="" ref="canvasBox" @touchstart="bindState">
</canvas>
<button @click="clear">清除签名</button>
<button @click="submit">上传</button>
</div>
<img :src="imgUrl" alt="">
</template>
javascript
<script setup>
import { ref, reactive, computed, watchEffect, onMounted, onBeforeUpdate, onUpdated, onBeforeUnmount, onUnmounted, toRefs, toRaw, provide, inject, } from 'vue'
import { Upload } from '@/api/index'
const canvasBox = ref(null)
let data = reactive({
name: '潘伟吉',
url: 'http://t15.baidu.com/it/u=2027854191,2160613474&fm=224&app=112&f=JPEG?w=240&h=240',
imgUrl: '',
ratio: 1
});
let { name, url, imgUrl, ratio } = toRefs(data);
function getadapt() {
ratio.value = window.innerWidth / 750
}
function bindState($event) {
const obj = canvasBox.value.getBoundingClientRect()
let ctx = canvasBox.value.getContext('2d')
let X = $event.touches[0].clientX-obj.x
let Y = $event.touches[0].clientY-obj.y
ctx.beginPath()
canvasBox.value.addEventListener("touchmove", move, {
capture: false,
passive: true,
once: false
});
function move(e) {
X = e.touches[0].clientX-obj.x;
Y = e.touches[0].clientY-obj.y;
ctx.lineTo(X, Y);
ctx.stroke();
}
canvasBox.value.addEventListener("touchend", function (e) {
canvasBox.value.removeEventListener("touchmove", move);
ctx.closePath()
}, {
capture: false,
passive: false,
once: true
}
);
}
function clear() {
canvasBox.value.getContext('2d').clearRect(0, 0, canvasBox.value.clientWidth, canvasBox.value.clientHeight)
}
async function submit(){
var imgsrcs = canvasBox.value.toDataURL()
let res1 = await changeBase64ToBlob(imgsrcs, "fileName")
let res2 = await Upload({
file: res1,
userId: '11111111',
});
}
function changeBase64ToBlob(base64, name) {
let base64Arr = base64.split(',');
console.log(base64Arr);
let imgType = '';
let base64String = '';
if (base64Arr.length > 1) {
base64String = base64Arr[1];
imgType = base64Arr[0].substring(base64Arr[0].indexOf(':') + 1, base64Arr[0].indexOf(';'));
}
let bytes = atob(base64String);
let bytesCode = new ArrayBuffer(bytes.length);
let byteArray = new Uint8Array(bytesCode);
for (let i = 0; i < bytes.length; i++) {
byteArray[i] = bytes.charCodeAt(i);
}
let blobData = new Blob([bytesCode], { type: imgType });
console.log(blobData);
let imgSuffix = '.' + imgType.split('/')[1]
console.log(imgSuffix);
let imageFile = new File([blobData], name + imgSuffix)
return imageFile
}
onMounted(() => {
getadapt()
canvasBox.value.width = `${750 * ratio.value}`
canvasBox.value.height = `${700 * ratio.value}`
})
</script>
css
<style scoped lang="less">
.canvas {
.name {
input {
border: 1px solid black;
border-width: 1px;
}
button {
width: 100px;
height: 60px;
background: red;
margin-left: 10px;
}
}
}
img {
width: 240px;
height: 240px;
margin-left: 100px;
}
canvas {
border: 1px solid black;
border-width: 1px;
}
</style>