web保存分享图片并保存的图片附带后端提供的地址生成的二维码Canvas画布实现

随声附和 提交于 2020-03-05 15:39:26

首先需要html2canvas 这个库:http://html2canvas.hertzen.com/

因为前端框架是react,下载了html2canvas库后接下来上代码

import html2canvas from 'html2canvas';
import SharePoster from '@/pages/share/index';

const [shareLink, setShareLink] = useState('');

//获取后台url
 useEffect(() => {
    const fetchShareLink = async () => {
      try {
        const res = await request.get(`/api/client/lessons/lesson/share-url?lesson=${lessonID ? lessonID : ''}`)
        setShareLink(res.share_url)
      } catch (error) {
        toast.fail('获取分享链接失败,请刷新重试')
        console.log(error)
      }
    }
    if (token) {
      fetchShareLink()
    }
  }, [token]);

//生成图片的方法
const saveImage = async () => {
    try {
      const canvas = await html2canvas(document.getElementById('share-poster'), { useCORS: true })
      let elem = document.createElement("a");
      elem.href = canvas.toDataURL("image/png");;
      elem.download = "image.png";
      elem.click();
    } catch (error) {
      console.log(error)
    }
  }

return (
<Modal>
	{!--生成二维码的组件--}
	<SharePoster inviteURL={shareLink} />
	{!--保存图片的按钮--}
	<div className="save-img">
        <button className="btn-care" onClick={saveImage}>保存分享图片到本地</button>
    </div>
</Modal>
)

//生成二维码的组件

import React, { useState } from 'react';
import './style.less';
import { useSelector } from 'react-redux';
import QRCode from 'qrcode.react';

const SharePoster = ({ inviteURL }) => {
  const profile = useSelector(state => state.user.profile);
  const statistics = useSelector(state => state.user.statistics);

  return (
    <div className="personal" id="share-poster">
      <div className="header">
        <div className="header-logo">
          <img
            src={require('@/assets/images/obby-logo.png')}
            alt="obbycode"
          />
        </div>
      </div>
      <div className="body">
        <img src={require('./images/scan-wxbg.png')} alt="" />
        <div className="body-container">
          <div className="personal-content">
            <div className="personal-avatar">
              <img src={profile.avatar ? profile.avatar.url : ''} alt="用户头像" />
            </div>
            <div className="personal-name">{profile.nickname}</div>
            <div className="personal-study">已在奥比编程</div>
            <div className="personal-score">
              <div className="score-content">
                学习
                <span className="score-content-count">25</span>
                <span className="score-content-count-unit">天</span>
              </div>
              <div className="score-icon">
                <img
                  className="score-icon-bg"
                  src={require('./images/scan-icon.png')}
                  alt="图标背景"
                />
                <img
                  className="score-icon-icon"
                  src={require('./images/scan-study.svg')}
                  alt="小图标"
                />
              </div>
            </div>
            <div className="personal-score">
              <div className="score-content">
                完成作品
                <span className="score-content-count">12</span>
                <span className="score-content-count-unit">个</span>
              </div>
              <div className="score-icon">
                <img
                  className="score-icon-bg"
                  src={require('./images/scan-icon.png')}
                  alt="图标背景"
                />
                <img
                  className="score-icon-icon"
                  src={require('./images/scan-questions.svg')}
                  alt="小图标"
                />
              </div>
            </div>
          </div>
          <div className="give">
            <div className="give-title">送你1个月VIP会员</div>
            <div className="give-invite">邀你与我一起学习</div>
          </div>
        </div>
      </div>
      <div className="footer">
        <div className="recommend">
          <div className="name">{profile.nickname}</div>
          <div className="recommend-content">推荐你加入奥比编程</div>
          <div className="recommend-content">长按扫码,领取VIP会员</div>
        </div>
        <div className="qrcode">
          <img
            className="qrcode-fake"
            src={require('./images/transparent-fake.png')}
            alt=""
          />
          <QRCode
            value={inviteURL}
            size={160}
            imageSettings={{
              src: require('@/assets/images/obbyLogo.png'),
              x: null,
              y: null,
              height: 36,
              width: 36,
              excavate: true
            }}
          />
        </div>
      </div>
    </div>
  );
}

export default SharePoster;

// const Personal = ({user}) => {
//   const [qrSize, serQrSize] = useState(64);
//   const [qrIcon, setQRIncon] = useState(0);
//   const [inviteURL, setInviteURL] = useState('http://www.baidu.com');

//   // 计算二维码和icon尺寸
//   // useEffect(() => {
//   //   const width = document.body.clientWidth;
//   //   serQrSize(width * 0.228);
//   //   setQRIncon(width * 0.03);
//   // }, [document.body.clientWidth]);
//   // 设置邀请链接

//   // useState(() => {
//   //   const URL = `${
//   //     window.location.origin
//   //   }/receive?from=${'3213543'}&invite=qrcode`;
//   //   setInviteURL(URL);
//   // }, []);

// };

// export default Personal;

react框架可用,仅作参考

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!