vue3实现下载图片功能

1.安装插件 html2canavs插件:

npm install  html2canvas
cnpm i  html2canvas  --save

2.组件中进行引入下载的插件:

import html2canvas from "html2canvas";

3.该组件中使用:

<template>
    <div>
        <div ref="poster" class="posterImg">
            <h3>公告</h3>
            <p>
                如果同学们的这个项目写的比较快,也能接收额外实战知识,增加难度
            </p>
            <img src="https://img2.baidu.com/it/u=2683586264,3988923268&fm=253&fmt=auto&app=138&f=JPEG?w=452&h=457" />
 
        </div>
        <img :src="posterimg"/>
        <button type="button" class=""  @click="download">下载</button>
    </div>
</template>


<script setup lang="ts">
import {  ref } from "vue";
import html2canvas from "html2canvas";
const  posterimg  = ref();
// 绑定内容生成图片
const  poster  =ref();
 
const  download= ()=> {
    // 通过ref获取元素的自身宽度和高度
    // poster.value.offsetWidth  poster.value.offsetHeight
    // 海报图默认是  2倍尺寸
    html2canvas(poster.value,{
        backgroundColor:'#f5f5f5',//海报的背景颜色
        useCORS:true, // 允许跨域 
        width:poster.value.offsetWidth, //生成海报的w  默认是px
        height:poster.value.offsetHeight, //生成海报的h 默认是px
    }).then(res=>{
        // res其实就是我们所讲的res 的意思 返回报文的意思
        let  baseImg = res.toDataURL("image/png");
        posterimg.value =baseImg;
        let save  = document.createElement('a');
        // <a href=''></a>
        save.href = baseImg;
        // 下载的名字
        save.download = 'yz'
        // 直接回调a的点击事件
        save.click()
 
    })
 
}
 </script>

  • 11
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值