首页 > 其他分享 >vue.js3:用html2canvas把html转canvas图片([email protected] / [email protected])

vue.js3:用html2canvas把html转canvas图片([email protected] / [email protected])

时间:2022-11-13 08:22:30浏览次数:67  
标签:1.4 vue const img value html2canvas let

一,安装html2canvas

1,官网:
https://html2canvas.hertzen.com/

如图:

代码站:
https://github.com/niklasvh/html2canvas
2,通过npm安装
liuhongdi@lhdpc:/data/vue/touch$ npm install --save html2canvas
 
added 5 packages in 4s
3,查看已安装的html2canvas库的版本
liuhongdi@lhdpc:/data/vue/touch$ npm list html2canvas
[email protected] /data/vue/touch
└── [email protected]

说明:刘宏缔的架构森林是一个专注架构的博客,地址:https://www.cnblogs.com/architectforest

         对应的源码可以访问这里获取: https://github.com/liuhongdi/
         或: https://gitee.com/liuhongdi

说明:作者:刘宏缔 邮箱: [email protected]

二,js代码:

<template>
  <div>
    <div style="width:800px;margin: auto;display: flex;flex-direction: column;">
      <div>请选择上传图片:
        <input type="file" id="back" ref="backfile" accept="image/*" @change="handleFile" /></div>

      <div id="imgContainer" style="position: relative;margin-left:150px;margin-top:10px;width:500px;height:500px;overflow: hidden;background: lightgray;" >
        <div id="imgDiv">
        <img id="img" :src="imgSrc" style="" />
          <div id="text"
               :style="{
                  width:'600px',
                  height:'200px',
                  position: 'absolute',
                  left:'50px',
                  top:'50px',
                  width: '300px',
                   height: 'auto',
                   fontSize:fontSizeValue+'px',
                   color:colorValue,
                   fontStyle:styleValue,
                   fontWeight:weightValue,
                   opacity:opacityValue,
                   textAlign:alignValue }">这是一个可编辑的信息,测试思源的字体文件</div>
        </div>
      </div>
      <div>
        字号: <el-input-number
          v-model="fontSizeValue"
          class="mx-4"
          :min="10"
          :max="100"
          controls-position="right"
          @change="fontSizeChange"
      /><br/>
        颜色:<el-color-picker v-model="colorValue" @active-change="setColor" /><br/>
        <span>透明度:</span><el-slider v-model="opacityDispValue" :min="0" :max="100" @input="setOpacity" style="width:300px;" /><br/>
        <button @click="weight">加粗</button>
        <button @click="style">斜体</button>
      </div>

      <div id="dpiBtn" style="display: none;">
        <input type="button" value="保存图片" @click="makeCanvas" />
      </div>
    </div>
  </div>
</template>

<script>
import {ref} from "vue";
import html2canvas from "html2canvas"

export default {
  name: "ImageText",
  setup() {
    //图片的原宽高
    const imgWidth = ref(0);
    const imgHeight = ref(0);
    //图片内容
    const imgSrc = ref("");
    //选中的图片文件
    const imgFile = ref();
    //选中图片后的处理
    const handleFile = () => {
      let filePaths = window.event.target.files;
      //清空原有缩略图
      if (filePaths.length === 0) {
        //未选择,则返回
        return
      }
      //把新选中的图片加入数组
      imgFile.value = filePaths[0];
      imgSrc.value = URL.createObjectURL(imgFile.value);
      let reader = new FileReader();
      reader.readAsDataURL(imgFile.value);
      reader.onload = () =>{
        //显示图片
        imgSrc.value = reader.result;
        //得到宽高
        let img = new Image();
        img.src= reader.result;
        img.onload = () => {
          //保存宽高
          imgWidth.value = img.width;
          imgHeight.value = img.height;

          if (img.width >= img.height) {
            let rate = 500 / img.width;

            let left = (500-img.width) / 2;
            let top = (500 -img.height) / 2;

            let styleStr =  'display:block;width:100%;height:100%;';

            document.getElementById('img').style =  styleStr;

            let styleDivStr = 'position:absolute;width:'+img.width+'px;height:'+img.height+'px;transform:scale('+rate+');left:'+left+'px;display: block;top:'+top+'px;';
            document.getElementById('imgDiv').style =  styleDivStr;

          } else {
            let rate = 500 / img.height;

            let left = (500-img.width) / 2;
            let top = (500 -img.height) / 2;
            let styleStr =  'display: inline-block;width:100%;height:100%;';
            document.getElementById('img').style =  styleStr;

            let styleDivStr = 'position:absolute;width:'+img.width+'px;height:'+img.height+'px;transform:scale('+rate+');left:'+left+'px;display: block;top:'+top+'px;';
            document.getElementById('imgDiv').style =  styleDivStr;
          }
          document.getElementById('dpiBtn').style.display="";
        }
      }
    }

    //对齐
    const alignValue = ref("left");

    //倾斜
    const styleValue = ref("normal");
    const style = () => {
      if (styleValue.value == 'normal') {
        styleValue.value ='italic'
      } else {
        styleValue.value ='normal'
      }
    }
    //加粗
    const weightValue = ref("normal");
    const weight = () => {
      if (weightValue.value == 'normal') {
        weightValue.value ='bold'
      } else {
        weightValue.value ='normal'
      }
    }
    //透明度
    const opacityValue = ref(1);
    const opacityDispValue = ref(100);
    const setOpacity = (value) => {
      opacityValue.value = value / 100;
    }

    //颜色
    const colorValue = ref("#2c3e50");
    const setColor = (value) => {
      colorValue.value = value;
    }
    //字号
    const fontSizeValue = ref(38);
    const fontSizeChange = (value) =>{
      fontSizeValue.value = value;
    }

    //把编辑的文字部分保存成图片
    const makeCanvas = () => {
      html2canvas(document.getElementById('text'),{
        onclone: function(documentClone){
          documentClone.getElementById('imgDiv').style.transform = 'scale(1)';
        }
      }).then(function(canvas){
        downPngByCanvas(canvas);
      });
    }

    //下载图片
    const downPngByCanvas = (canvas) => {
      var oA = document.createElement("a");
      let time = timeFormat();
      oA.download = "img_"+time+'.png';// 设置下载的文件名,默认是'下载'
      oA.href = canvas.toDataURL("image/png").replace('image/png', 'image/octet-stream');

      document.body.appendChild(oA);
      oA.click();
      oA.remove(); // 下载之后把创建的元素删除
    }
    //补0
    const add0 = (m) => {
      return m<10?'0'+m:m
    }
    //格式化时间
    const timeFormat = ()=>{
      var time = new Date();
      var y = time.getFullYear();
      var m = time.getMonth()+1;
      var d = time.getDate();
      var h = time.getHours();
      var mm = time.getMinutes();
      var s = time.getSeconds();
      let res = y+add0(m)+add0(d)+add0(h)+add0(mm)+add0(s);
      return res;
    }

       return {
         imgSrc,
         handleFile,
         alignValue,
         style,
         styleValue,
         weight,
         weightValue,
         opacityValue,
         opacityDispValue,
         setOpacity,
         colorValue,
         setColor,
         fontSizeValue,
         fontSizeChange,

         makeCanvas,
       }
  }
}
</script>

<style scoped>
</style>

三,测试效果:

转canvas后:

四,查看vue框架的版本:

root@lhdpc:/data/vue/imgtouch# npm list vue
[email protected] /data/vue/imgtouch
├─┬ @vue/[email protected]
│ └─┬ @vue/[email protected]
│   └── [email protected] deduped
└─┬ [email protected]
  └─┬ @vue/[email protected]
    └── [email protected] deduped

 

标签:1.4,vue,const,img,value,html2canvas,let
From: https://www.cnblogs.com/architectforest/p/16885361.html

相关文章

  • Vue.js -- 动态组件&异步组件
    动态组件根据数据的变化,动态切换组件的显示。点击切换组件首先定义两个子组件//子组件app.component('myInput',{template:`......
  • vue监视实操案例-根据导航条点击面包屑发生改动
    监视部分代码: $route(to,From){console.log(to,From);if(to.path=="/Home"){this.path="";this.name="";}else......
  • 谈一谈 vuex 的运行机制
    Vuex提供数据(state)来驱动视图(vuecomponents),通过dispath派发actions,在其中可以做一些异步的操作,然后通过commit来提交mutations,最后mutations来更改state。 ......
  • 我们如何在 vue 应用我们的权限
    权限可以分为用户权限和按钮权限;用户权限,让不同的用户拥有不同的路由映射,具体实现方法:1.初始化路由实例的时候,只把静态路由规则注入,不要注入动态路由规则;2.......
  • Vue生命周期及组件
    目录Vue生命周期钩子钩子函数的由来生命周期钩子函数生命周期图示Vue生命周期钩子钩子函数的由来每个Vue实例在被创建时都要经过一系列的初始化过程——例如,需要......
  • vue3.2 setup语法糖,多个API解释
    前言在vue3中删除了vue2中的data函数,因此,vue3.0要在template中使用某些变量就必须在最后return出来,多次声明变量,不太方便,也不太友好。而在vue3.2版本之后,我们只需在......
  • 12-使用Vue与axios改造jquery原页面
    改造List页面1引入文件<!--1引入vuejsaxios文件--><scripttype="text/javascript"src="js/vue.js"></script><scripttype="text/javascript"src="js/axios.j......
  • 11-SpringBoot2整合Vue最简入门
    vuejs入门环境搭建》1:导入文件<scripttype="text/javascript"src="js/vue.js"></script><scripttype="text/javascript"src="js/axios.js"></script>》2:准备app视......
  • 如何使用vite搭建vue3项目详解
    目录一:npm构建二:更改http://localhost:3000/到8080与Network路由访问三:配置vite别名(npminstall@types/node--save-dev)四:路由(npminstallvue-router@4)五:vuex(n......
  • vue 翻页组件vue-flip-page
    方法change(改变页面)tap(点击)turning(正在翻页)prev(前一页)next(后一页)翻到指定页面:handleSwitchManual(index){if(index===this.currentIndex)......