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

相关文章

springboot filter实现请求响应全链路拦截

《springbootfilter实现请求响应全链路拦截》这篇文章主要为大家详细介绍了SpringBoot如何结合Filter同时拦截请求和响应,从而实现​​日志采集自动化,感兴趣的小伙伴可以跟随小... 目录一、为什么你需要这个过滤器?​​​二、核心实现:一个Filter搞定双向数据流​​​​三、完整代码

SpringBoot利用@Validated注解优雅实现参数校验

《SpringBoot利用@Validated注解优雅实现参数校验》在开发Web应用时,用户输入的合法性校验是保障系统稳定性的基础,​SpringBoot的@Validated注解提供了一种更优雅的解... 目录​一、为什么需要参数校验二、Validated 的核心用法​1. 基础校验2. php分组校验3

Python实现AVIF图片与其他图片格式间的批量转换

《Python实现AVIF图片与其他图片格式间的批量转换》这篇文章主要为大家详细介绍了如何使用Pillow库实现AVIF与其他格式的相互转换,即将AVIF转换为常见的格式,比如JPG或PNG,需要的小... 目录环境配置1.将单个 AVIF 图片转换为 JPG 和 PNG2.批量转换目录下所有 AVIF 图

Pydantic中model_validator的实现

《Pydantic中model_validator的实现》本文主要介绍了Pydantic中model_validator的实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价... 目录引言基础知识创建 Pydantic 模型使用 model_validator 装饰器高级用法mo

Vue3使用router,params传参为空问题

《Vue3使用router,params传参为空问题》:本文主要介绍Vue3使用router,params传参为空问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐... 目录vue3使用China编程router,params传参为空1.使用query方式传参2.使用 Histo

AJAX请求上传下载进度监控实现方式

《AJAX请求上传下载进度监控实现方式》在日常Web开发中,AJAX(AsynchronousJavaScriptandXML)被广泛用于异步请求数据,而无需刷新整个页面,:本文主要介绍AJAX请... 目录1. 前言2. 基于XMLHttpRequest的进度监控2.1 基础版文件上传监控2.2 增强版多

Redis分片集群的实现

《Redis分片集群的实现》Redis分片集群是一种将Redis数据库分散到多个节点上的方式,以提供更高的性能和可伸缩性,本文主要介绍了Redis分片集群的实现,具有一定的参考价值,感兴趣的可以了解一... 目录1. Redis Cluster的核心概念哈希槽(Hash Slots)主从复制与故障转移2.

springboot+dubbo实现时间轮算法

《springboot+dubbo实现时间轮算法》时间轮是一种高效利用线程资源进行批量化调度的算法,本文主要介绍了springboot+dubbo实现时间轮算法,文中通过示例代码介绍的非常详细,对大家... 目录前言一、参数说明二、具体实现1、HashedwheelTimer2、createWheel3、n

使用Python实现一键隐藏屏幕并锁定输入

《使用Python实现一键隐藏屏幕并锁定输入》本文主要介绍了使用Python编写一个一键隐藏屏幕并锁定输入的黑科技程序,能够在指定热键触发后立即遮挡屏幕,并禁止一切键盘鼠标输入,这样就再也不用担心自己... 目录1. 概述2. 功能亮点3.代码实现4.使用方法5. 展示效果6. 代码优化与拓展7. 总结1.

Mybatis 传参与排序模糊查询功能实现

《Mybatis传参与排序模糊查询功能实现》:本文主要介绍Mybatis传参与排序模糊查询功能实现,本文通过实例代码给大家介绍的非常详细,感兴趣的朋友跟随小编一起看看吧... 目录一、#{ }和${ }传参的区别二、排序三、like查询四、数据库连接池五、mysql 开发企业规范一、#{ }和${ }传参的