vue+canvas实现逐字手写效果

2024-05-24 06:52

本文主要是介绍vue+canvas实现逐字手写效果,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

在pc端进行逐字手写的功能。用户可以在一个 inputCanvas 上书写单个字,然后在特定时间后将这个字添加到 outputCanvas 上,形成一个逐字的手写效果。用户还可以保存整幅图像或者撤销上一个添加的字。

<template><div class="container" v-if="!disabled"><div class="tipCn"><div>请您在右侧区域内逐字手写以下文字,全部写完后点击保存!</div><div>{{ ruleForm.sqcn }}</div></div><div style="margin: 0px 20px"><span class="dialog-footer"><el-button @click="undoChar" type="danger" :icon="RefreshRight">撤销上一个字</el-button><el-button @click="saveImage" type="primary" :icon="Check">保存</el-button></span><canvasref="inputCanvas"class="input-canvas":width="canvasWidth":height="canvasHeight"@mousedown="startDrawing"@mousemove="draw"@mouseup="stopDrawing"@mouseleave="stopDrawing"></canvas></div><canvas ref="outputCanvas" class="output-canvas" :width="outputWidth" :height="outputHeight"></canvas></div><img class="Signature" v-else :src="resultImg" alt="commitment Image" />
</template><script setup>
import { ref, onMounted, nextTick, watch } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import fileService from "@/api/sys/fileService.js";
import { Check, RefreshRight } from "@element-plus/icons-vue";
import knsService from "@/api/sys/kns/knsService";const canvasWidth = 300;
const canvasHeight = 300;
const isDrawing = ref(false);
const startX = ref(0);
const startY = ref(0);
const charObjects = ref([]);
const timer = ref(null);
const delay = 1000; // 1秒延迟
let outputWidth = 300;
let outputHeight = ref(50);
let resultImg = ref("");
let context = null;
let outputContext = null;const inputCanvas = ref(null);
const outputCanvas = ref(null);let ruleForm = ref({});const emit = defineEmits(["update:modelValue"]);
const props = defineProps({modelValue: {type: [Number, String],default: ""},disabled: {type: Boolean,default: false}
});// 当输入框内容变化时触发更新父组件的 value
watch(resultImg,(newValue) => {emit("update:modelValue", newValue);},{ deep: true }
);watch(() => props.modelValue,(newValue) => {resultImg.value = newValue;},{ deep: true, immediate: true }
);onMounted(() => {if (!props.disabled) {getData();context = inputCanvas.value.getContext("2d");outputContext = outputCanvas.value.getContext("2d");context.strokeStyle = "#000000";context.lineWidth = 4;context.lineCap = "round";context.lineJoin = "round";outputContext.strokeStyle = "#000000";outputContext.lineWidth = 3;outputContext.lineCap = "round";outputContext.lineJoin = "round";}
});// 获取承诺
const getData = async () => {const res = await knsService.getSettingData();ruleForm.value = res[0];
};const startDrawing = (e) => {if (timer.value) {clearTimeout(timer.value);timer.value = null;}isDrawing.value = true;startX.value = e.offsetX;startY.value = e.offsetY;context.beginPath();context.moveTo(startX.value, startY.value);
};const draw = (e) => {if (!isDrawing.value) return;context.lineTo(e.offsetX, e.offsetY);context.stroke();
};const stopDrawing = () => {if (isDrawing.value) {isDrawing.value = false;context.closePath();timer.value = setTimeout(addChar, delay);}
};const addChar = () => {const canvas = inputCanvas.value;const dataUrl = canvas.toDataURL("image/png");charObjects.value.push(dataUrl);clearCanvas();redrawOutputCanvas();
};const clearCanvas = () => {const canvas = inputCanvas.value;context.clearRect(0, 0, canvas.width, canvas.height);
};const undoChar = () => {if (charObjects.value.length > 0) {charObjects.value.pop();redrawOutputCanvas();if (charObjects.value.length === 0) {outputHeight.value = 50; // 如果字符对象为空,则将输出画布高度设置为 50outputCanvas.value.height = outputHeight.value; // 更新画布高度}}
};const redrawOutputCanvas = () => {outputContext.clearRect(0, 0, outputWidth, outputHeight.value);const charSize = 50; // 调整字符大小const charSpacing = 50; // 调整字符间距const maxCharsPerRow = Math.floor(outputWidth / charSize); // 每行最大字符数const numRows = Math.ceil(charObjects.value.length / maxCharsPerRow); // 计算行数const newOutputHeight = numRows * charSize; // 动态计算输出画布的高度if (newOutputHeight !== outputHeight.value) {outputHeight.value = newOutputHeight;outputCanvas.value.height = outputHeight.value; // 更新画布高度}nextTick(() => {charObjects.value.forEach((char, index) => {const rowIndex = Math.floor(index / maxCharsPerRow); // 当前字符的行索引const colIndex = index % maxCharsPerRow; // 当前字符的列索引const img = new Image();img.onload = () => {outputContext.drawImage(img, colIndex * charSpacing, rowIndex * charSpacing, charSize, charSize); // 绘制字符图片到输出画布上};img.src = char;});});
};const saveImage = () => {if (charObjects.value.length === 0) {ElMessage.error("请输入!");return false;}const canvas = outputCanvas.value;const dataUrl = canvas.toDataURL("image/png");console.log(dataUrl, "dataUrldataUrldataUrl"); // 您可以将此图片上传或保存// 生成带有当前日期和时间的文件名const now = new Date();const filename = `承诺-${now.getFullYear()}${padZero(now.getMonth() + 1)}${padZero(now.getDate())}${padZero(now.getHours())}${padZero(now.getMinutes())}${padZero(now.getSeconds())}.jpg`;const blob = dataURLtoBlob(dataUrl);const tofile = blobToFile(blob, filename);setTimeout(async () => {const formData = new FormData();formData.append("file", tofile, tofile.name);formData.append("fileType", 9);console.log(formData, "formDataformData");const res2 = await fileService.uploadFile(formData);resultImg.value = res2;console.log(resultImg.value, "resultImg.value");});ElMessage.success("保存成功!");
};const dataURLtoBlob = (dataurl) => {const arr = dataurl.split(",");const mime = arr[0].match(/:(.*?);/)[1];const bstr = atob(arr[1]);let n = bstr.length;const u8arr = new Uint8Array(n);while (n--) {u8arr[n] = bstr.charCodeAt(n);}return new Blob([u8arr], { type: mime });
};const blobToFile = (theBlob, fileName) => {theBlob.lastModifiedDate = new Date();theBlob.name = fileName;return theBlob;
};const padZero = (num) => {return num < 10 ? "0" + num : num;
};
</script><style scoped lang="scss">
.container {display: flex;align-items: flex-start;justify-content: flex-start;.output-canvas {border: 1px solid #ddd;}img {width: 50px;height: 50px;margin: 1px;}.input-canvas {border-radius: 5px;border: 1px dashed #dddee1;}.dialog-footer {display: flex;justify-content: space-between;margin-bottom: 10px;}.tipCn {div:nth-child(1) {color: #ff6f77;font-size: 12px;}div:nth-child(2) {background-color: #ecf5ff;padding: 0px 10px;border-radius: 4px;color: #3c9cff;font-size: 14px;text-align: left;}}
}
.Signature {width: 500px;height: 150px;margin-top: 10px;border: 1px solid #dddee1;}
</style>

这篇关于vue+canvas实现逐字手写效果的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/997681

相关文章

Vue3 的 shallowRef 和 shallowReactive:优化性能

大家对 Vue3 的 ref 和 reactive 都很熟悉,那么对 shallowRef 和 shallowReactive 是否了解呢? 在编程和数据结构中,“shallow”(浅层)通常指对数据结构的最外层进行操作,而不递归地处理其内部或嵌套的数据。这种处理方式关注的是数据结构的第一层属性或元素,而忽略更深层次的嵌套内容。 1. 浅层与深层的对比 1.1 浅层(Shallow) 定义

这15个Vue指令,让你的项目开发爽到爆

1. V-Hotkey 仓库地址: github.com/Dafrok/v-ho… Demo: 戳这里 https://dafrok.github.io/v-hotkey 安装: npm install --save v-hotkey 这个指令可以给组件绑定一个或多个快捷键。你想要通过按下 Escape 键后隐藏某个组件,按住 Control 和回车键再显示它吗?小菜一碟: <template

【 html+css 绚丽Loading 】000046 三才归元阵

前言:哈喽,大家好,今天给大家分享html+css 绚丽Loading!并提供具体代码帮助大家深入理解,彻底掌握!创作不易,如果能帮助到大家或者给大家一些灵感和启发,欢迎收藏+关注哦 💕 目录 📚一、效果📚二、信息💡1.简介:💡2.外观描述:💡3.使用方式:💡4.战斗方式:💡5.提升:💡6.传说: 📚三、源代码,上代码,可以直接复制使用🎥效果🗂️目录✍️

【前端学习】AntV G6-08 深入图形与图形分组、自定义节点、节点动画(下)

【课程链接】 AntV G6:深入图形与图形分组、自定义节点、节点动画(下)_哔哩哔哩_bilibili 本章十吾老师讲解了一个复杂的自定义节点中,应该怎样去计算和绘制图形,如何给一个图形制作不间断的动画,以及在鼠标事件之后产生动画。(有点难,需要好好理解) <!DOCTYPE html><html><head><meta charset="UTF-8"><title>06

hdu1043(八数码问题,广搜 + hash(实现状态压缩) )

利用康拓展开将一个排列映射成一个自然数,然后就变成了普通的广搜题。 #include<iostream>#include<algorithm>#include<string>#include<stack>#include<queue>#include<map>#include<stdio.h>#include<stdlib.h>#include<ctype.h>#inclu

【C++】_list常用方法解析及模拟实现

相信自己的力量,只要对自己始终保持信心,尽自己最大努力去完成任何事,就算事情最终结果是失败了,努力了也不留遗憾。💓💓💓 目录   ✨说在前面 🍋知识点一:什么是list? •🌰1.list的定义 •🌰2.list的基本特性 •🌰3.常用接口介绍 🍋知识点二:list常用接口 •🌰1.默认成员函数 🔥构造函数(⭐) 🔥析构函数 •🌰2.list对象

【Prometheus】PromQL向量匹配实现不同标签的向量数据进行运算

✨✨ 欢迎大家来到景天科技苑✨✨ 🎈🎈 养成好习惯,先赞后看哦~🎈🎈 🏆 作者简介:景天科技苑 🏆《头衔》:大厂架构师,华为云开发者社区专家博主,阿里云开发者社区专家博主,CSDN全栈领域优质创作者,掘金优秀博主,51CTO博客专家等。 🏆《博客》:Python全栈,前后端开发,小程序开发,人工智能,js逆向,App逆向,网络系统安全,数据分析,Django,fastapi

让树莓派智能语音助手实现定时提醒功能

最初的时候是想直接在rasa 的chatbot上实现,因为rasa本身是带有remindschedule模块的。不过经过一番折腾后,忽然发现,chatbot上实现的定时,语音助手不一定会有响应。因为,我目前语音助手的代码设置了长时间无应答会结束对话,这样一来,chatbot定时提醒的触发就不会被语音助手获悉。那怎么让语音助手也具有定时提醒功能呢? 我最后选择的方法是用threading.Time

Android实现任意版本设置默认的锁屏壁纸和桌面壁纸(两张壁纸可不一致)

客户有些需求需要设置默认壁纸和锁屏壁纸  在默认情况下 这两个壁纸是相同的  如果需要默认的锁屏壁纸和桌面壁纸不一样 需要额外修改 Android13实现 替换默认桌面壁纸: 将图片文件替换frameworks/base/core/res/res/drawable-nodpi/default_wallpaper.*  (注意不能是bmp格式) 替换默认锁屏壁纸: 将图片资源放入vendo

C#实战|大乐透选号器[6]:实现实时显示已选择的红蓝球数量

哈喽,你好啊,我是雷工。 关于大乐透选号器在前面已经记录了5篇笔记,这是第6篇; 接下来实现实时显示当前选中红球数量,蓝球数量; 以下为练习笔记。 01 效果演示 当选择和取消选择红球或蓝球时,在对应的位置显示实时已选择的红球、蓝球的数量; 02 标签名称 分别设置Label标签名称为:lblRedCount、lblBlueCount