vue+canvas实现逐字手写效果

news2024/10/6 19:20:51

在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>
      <canvas
        ref="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; // 如果字符对象为空,则将输出画布高度设置为 50
      outputCanvas.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>

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1684754.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

【B站 heima】小兔鲜Vue3 项目学习笔记

系列文章目录 Day 01 目录 系列文章目录前言Day011.项目使用相关技术栈2. 项目规模和亮点3. Vue2和Vue3实现一个小案例4. vue3的优势5. create-vue脚手架工具6. 熟悉我们的项目目录和文件7. 组合式API-setup选项8. 组合式API-reactive和ref函数9. 组合式API-computed计算属性…

动态IP与静态IP有什么区别?如何选择?

动态IP和静态IP都是指网络设备&#xff08;如计算机、服务器、路由器等&#xff09;在互联网上分配的IP地址的类型。 一、什么是动态IP&#xff0c;什么是静态IP&#xff1f; 1、什么是动态IP&#xff1f; 动态IP是指由Internet服务提供商&#xff08;ISP&#xff09;动态分配…

xrdp多用户多控制界面远程控制

1、无桌面安装桌面&#xff08;原本有ubuntu桌面的可以直接跳过这一步&#xff09; Gnome 与 xfce 相比&#xff0c;xfce 由于其轻巧&#xff0c;它可以安装在低端台式机上。Xfce 优雅的外观&#xff0c;增强了用户体验&#xff0c;它对用户非常友好&#xff0c;性能优于其他桌…

docker- 购建服务镜像并启动

文章目录 前言docker- 购建服务镜像并启动1. 前期准备2. 构建镜像3. 运行容器4. 验证 前言 如果您觉得有用的话&#xff0c;记得给博主点个赞&#xff0c;评论&#xff0c;收藏一键三连啊&#xff0c;写作不易啊^ _ ^。   而且听说点赞的人每天的运气都不会太差&#xff0c;实…

扩散模型自动管道AutoPipeline

推荐&#xff1a;write_own_pipeline.ipynb - Colab (google.com) 为您的任务选择一个 AutoPipeline 首先选择一个检查点。例如&#xff0c;如果您对使用 runwayml/stable-diffusion-v1-5 检查点的文本到图像感兴趣&#xff0c;请使用 AutoPipelineForText2Image&#xff1a; f…

linux ping https是否连接

在Linux系统中&#xff0c;ping通常用于测试网络上另一台主机的可达性。它使用的是ICMP协议&#xff0c;这是一种设计用来处理网络通信问题的协议。HTTPS则是一种安全的网络传输协议&#xff0c;它使用SSL/TLS加密。 如果你想要测试到某个HTTPS服务器的连接&#xff0c;你可以使…

【MySQL精通之路】InnoDB(6)-磁盘结构(2)-索引

主博客&#xff1a; 【MySQL精通之路】InnoDB(6)-磁盘上的InnoDB结构-CSDN博客 上一篇&#xff1a; 下一篇&#xff1a; 【MySQL精通之路】磁盘上的InnoDB结构-表空间-CSDN博客 目录 1.聚集索引和二级索引 1.1 Innodb 如何建立聚集索引 1.2 聚集索引如何加快查询速度 1…

CustomTkinter:便捷美化Tkinter的UI界面(附模板)

CustomTkinter是一个基于Tkinter的Python用户界面库。 pip3 install customtkinter它提供了各种UI界面常见的小部件。这些小部件可以像正常的Tkinter小部件一样创建和使用&#xff0c;也可以与正常的Tkinter元素一起使用。 它的优势如下&#xff1a; CustomTkinter的小部件和…

四天学会JS高阶(学好vue的关键)——深入面向对象(理论+实战)(第三天)

***本章面试使用居多* 理论篇**一、编程思想 1.1 面向过程 JS 前端居多 按照步骤 性能高 适合跟硬件关系很紧密 没有面向对象易维护易复用易扩展 1.2 面向对象 java典型 按照功能&#xff0c;把事务分别成一个个对象&#xff0c;对象之间分工合作 比较灵活 适合多人合作的…

模拟笔试 - 卡码网周赛第十八期(23年科大讯飞提前批笔试真题)

第一题&#xff1a; 参考思路解析&#xff1a;&#xff08;遍历nums中的每个数字&#xff0c;得到不为0的数位即可。&#xff09; 1.导入Scanner类&#xff1a; import java.util.Scanner;&#xff1a;引入 Scanner 类&#xff0c;用于读取用户输入。 2.主方法&#xff1a; …

力扣1809 没有广告的剧集(postgresql)

需求 Table: Playback ----------------- | Column Name | Type | ----------------- | session_id | int | | customer_id | int | | start_time | int | | end_time | int | ----------------- 该表主键为&#xff1a;session_id &#xff08;剧集id&#xff09; customer_…

【C++算法】BFS解决FloodFill算法相关经典算法题

1.图像渲染 我们这道题可以使用深搜来解决&#xff0c;利用一个队列遍历到与该点相连的所有像素相同的点&#xff0c;然后将其修改成指定的像素即可&#xff0c;直接上思路&#xff1a; 直接上代码&#xff1a; class Solution {int dx[4] {0, 0, 1, -1};int dy[4] {1, -1, …

计组期末必考大题

一.寻址方式详解 1.直接寻址 指令地址码直接给到操作数所在的存储单元地址 2.间接寻址 A为操作数EA的地址 3.寄存寻址 4.寄存器间接寻址 5.变址寻址 6.基地址寻址 7.小结 二、指令周期详解 一、基本概念 指令周期:去除指令并执行指令所需要的时间指令周期:由若干个CPU周…

go语言的一些常见踩坑问题

开始之前&#xff0c;介绍一下​最近很火的开源技术&#xff0c;低代码。 作为一种软件开发技术逐渐进入了人们的视角里&#xff0c;它利用自身独特的优势占领市场一角——让使用者可以通过可视化的方式&#xff0c;以更少的编码&#xff0c;更快速地构建和交付应用软件&#…

docker 安装minio 服务 ssl 证书

minio 安装 ssl 证书 下载apache 证书 &#xff08;可以使用免费的证书&#xff09; 放在/opt/minio/conf/certs 下 (安装minio 时的 挂载目录 参考文章 docker 安装minio,详细图解 ) 拷贝进容器 /root/.minio docker cp /opt/minio/conf/certs/private.key minio:/root/.mi…

蜂窝物联四情监测:助力农业升级,科技赋能打造丰收新篇章!

农业四情指的是田间的虫情、作物的苗情、气候的灾情和土壤墒情。“四情”监测预警系统的组成包括管式土壤墒情监测站、虫情测报灯、气象站、农情监测摄像机&#xff0c;可实时监测基地状况,可以提高监测的效率和准确性&#xff0c;为农业生产提供及时、科学的数据支持&#xff…

知识图谱数据预处理笔记

知识图谱数据预处理笔记 0. 引言1. 笔记1-1. \的转义1-2. 特殊符号的清理1-3. 检查结尾是否正常1-4. 检查<>是否存在1-5. 两端空格的清理1-6. 检查object内容长时是否以<开始 0. 引言 最近学习知识图谱&#xff0c;发现数据有很多问题&#xff0c;这篇笔记记录遇到的…

【android 9】【input】【2.结构体含义】

系列文章目录 可跳转到下面链接查看下表所有内容https://blog.csdn.net/handsomethefirst/article/details/138226266?spm1001.2014.3001.5501文章浏览阅读2次。系列文章大全https://blog.csdn.net/handsomethefirst/article/details/138226266?spm1001.2014.3001.5501 目录…

怎么认识和应用Redis内部数据结构?no.22

Redis 内部数据结构 RdeisDb Redis 中所有数据都保存在 DB 中&#xff0c;一个 Redis 默认最多支持 16 个 DB。Redis 中的每个 DB 都对应一个 redisDb 结构&#xff0c;即每个 Redis 实例&#xff0c;默认有 16 个 redisDb。用户访问时&#xff0c;默认使用的是 0 号 DB&#…

NLP(18)--大模型发展(2)

前言 仅记录学习过程&#xff0c;有问题欢迎讨论 LLM的结构变化&#xff1a; Muti-head 共享&#xff1a; Q继续切割为muti-head,但是K,V少切&#xff0c;比如切为2个&#xff0c;然后复制到n个muti-head减少参数量&#xff0c;加速训练 attention结构改动&#xff1a; s…