当前位置:   article > 正文

react APP内置移动端h5 canvas画布二维码转成base64链接_react 图片转base64 canvas显示

react 图片转base64 canvas显示

有这么一个需求,保存图片到手机相册,真正的保存是调用的sdk原生的接口,这个不是我想讲的重点

我想说的是,如何使用qrcode.react 生成二维码之后再将以canvas画布形式渲染的二维码转成base64链接!

参考自react二维码qrcode.react以及点击二维码的下载二维码图片_ou得之的博客-CSDN博客这位博主

  1. /* global APPID */
  2. import React from 'react'
  3. import { connect } from 'dva'
  4. import { Flex, Button } from 'antd-mobile'
  5. import LoadWrap from '@/components/LoadWrap'
  6. import QRCode from 'qrcode.react'
  7. import NavBar from '@/components/NavBar'
  8. import Bridge from '@/utils/bridge'
  9. import styles from './qrcode.less'
  10. import APIENV from '../env'
  11. import $ from 'jquery';
  12. @connect(({ signIn }) => ({
  13. detail: signIn.detail
  14. }))
  15. class QRCodePage extends React.Component {
  16. constructor(props) {
  17. super(props)
  18. this._inThisPage = true
  19. this.vid = props.location.query.id;
  20. if (this.vid) {
  21. props.dispatch({
  22. type: 'signIn/fetchDetail',
  23. payload: { vid: this.vid }
  24. })
  25. }
  26. this.handleBack = this.handleBack.bind(this)
  27. this.handleNativeBack = this.handleNativeBack.bind(this)
  28. this.handleNativeBack()
  29. }
  30. componentWillUnmount() {
  31. this._inThisPage = false
  32. }
  33. _downLoad = () => {
  34. var Qr = document.getElementById('qrid');
  35. let imgBase64 = Qr.toDataURL("image/png");
  36. console.log('Qr.toDataURL("image/png")', Qr.toDataURL("image/png"));
  37. this.saveToAlbum(imgBase64);
  38. }
  39. // getBase64Image = (img) => {
  40. // var canvas = document.createElement("canvas");
  41. // canvas.width = img.width;
  42. // canvas.height = img.height;
  43. // var ctx = canvas.getContext("2d");
  44. // ctx.drawImage(img, 0, 0, img.width, img.height);
  45. // var dataURL = canvas.toDataURL("image/png");//修改图片后缀
  46. // return dataURL
  47. // }
  48. // main = () => {
  49. // var img = document.createElement('img');
  50. // img.src = $("#h5qrcodeimg").attr('src');//赋予二维码src
  51. // img.onload = function () {
  52. // var data = this.getBase64Image(img);
  53. // console.log(data);
  54. // $("#down_qrcode").attr("href", data);//转码后赋予下载按钮(a标签)的href
  55. // };
  56. // }
  57. handleBack() {
  58. if (this.props.location.query.backto === 'list') {
  59. this.props.history.push('/electric')
  60. } else {
  61. this.props.history.goBack();
  62. }
  63. }
  64. handleNativeBack() {
  65. Bridge.onMessage(msg => {
  66. if (!this._inThisPage) return;
  67. msg = JSON.parse(msg)
  68. if (msg && msg.type === 'back') {
  69. this.handleBack();
  70. }
  71. })
  72. }
  73. saveToAlbum = (imgBase64) => {
  74. // 图片预览, 可选参数 saveable:是否显示保存图片按钮, index: 多图情况下指定当前浏览的序号
  75. if (window.mbBridge) {
  76. window.mbBridge.mb.image({
  77. index: 1,
  78. saveable: true,
  79. urls: [imgBase64]
  80. });
  81. }
  82. }
  83. render() {
  84. const { detail, location } = this.props;
  85. const info = detail.data || {}
  86. const query = location.query;
  87. const src = `${APIENV}/down/app/signin/?name=${query.signInName}&num=${query.index || 1}&signInId=${query.signInId}#/`;
  88. return (
  89. <Flex direction="column" align="stretch" className={`${styles.qrcodePage} flex100`}>
  90. <NavBar
  91. title="二维码展示"
  92. handleBack={this.handleBack}
  93. />
  94. <Flex.Item className="flex100">
  95. <div className={styles.headPlace}></div>
  96. <div className={styles.card}>
  97. <div id="QR" style={{ padding: '50px 0 45px 0' }}>
  98. <QRCode id='qrid' value={src} onClick={this._downLoad} size={191} />
  99. </div>
  100. </div>
  101. <div className={styles.saveBtn}>
  102. <div type="primary" className={styles.btnCss} onClick={this._downLoad}>保存到手机</div>
  103. </div>
  104. {/* <LoadWrap data={{err: {message: '缺少ID参数'}}}/> */}
  105. </Flex.Item>
  106. </Flex>
  107. );
  108. }
  109. }
  110. export default QRCodePage

问题来了,如果我想把文案也一起作为图片存储为base64那要怎样做呢?(效果图如下)

关键是yarn add html2canvas

利用html2canvas将div生成base64(html2canvas这边有一个神坑!!!在IOS上,如果你的html2canvas版本不是1.0.0-rc.4,会导致在ios真机上调试时,不执行promise.then回调函数!!!

比如:

再比如:

...无语凝噎 

  1. /* global APPID */
  2. import React from 'react'
  3. import { connect } from 'dva'
  4. import { Flex, Button } from 'antd-mobile'
  5. import LoadWrap from '@/components/LoadWrap'
  6. import QRCode from 'qrcode.react'
  7. import NavBar from '@/components/NavBar'
  8. import Bridge from '@/utils/bridge'
  9. import styles from './qrcode.less'
  10. import APIENV from '../env'
  11. import $ from 'jquery';
  12. import html2canvas from 'html2canvas';
  13. @connect(({ signIn }) => ({
  14. detail: signIn.detail
  15. }))
  16. class QRCodePage extends React.Component {
  17. constructor(props) {
  18. super(props)
  19. this._inThisPage = true
  20. this.vid = props.location.query.id;
  21. if (this.vid) {
  22. props.dispatch({
  23. type: 'signIn/fetchDetail',
  24. payload: { vid: this.vid }
  25. })
  26. }
  27. this.canvas = React.createRef();
  28. this.handleBack = this.handleBack.bind(this)
  29. this.handleNativeBack = this.handleNativeBack.bind(this)
  30. this.handleNativeBack()
  31. }
  32. componentDidMount() {
  33. html2canvas(document.querySelector("#capture")).then(canvas => {
  34. // document.body.appendChild(canvas);
  35. let dataImg = canvas.toDataURL();
  36. this.newImgBase64 = dataImg;
  37. });
  38. }
  39. componentWillUnmount() {
  40. this._inThisPage = false
  41. }
  42. _downLoad = () => {
  43. console.log('this.newImgBase64===>:', this.newImgBase64);
  44. this.saveToAlbum(this.newImgBase64);
  45. }
  46. handleBack() {
  47. if (this.props.location.query.backto === 'list') {
  48. this.props.history.push('/electric')
  49. } else {
  50. this.props.history.goBack();
  51. }
  52. }
  53. handleNativeBack() {
  54. Bridge.onMessage(msg => {
  55. if (!this._inThisPage) return;
  56. msg = JSON.parse(msg)
  57. if (msg && msg.type === 'back') {
  58. this.handleBack();
  59. }
  60. })
  61. }
  62. saveToAlbum = (imgBase64) => {
  63. // window.mbBridge不是一个通用api 它是在我们app外壳通过webview注入到h5页面的window里的,需要根据自己的情况进行修改
  64. // 图片预览, 可选参数 saveable:是否显示保存图片按钮, index: 多图情况下指定当前浏览的序号
  65. if (window.mbBridge && window.mbBridge.mb) {
  66. console.log('保存图片被触发了!!!');
  67. window.mbBridge.mb.saveImage(imgBase64);
  68. }
  69. }
  70. render() {
  71. const { detail, location } = this.props;
  72. const info = detail.data || {}
  73. const query = location.query;
  74. const src = `${APIENV}/down/app/signin/?name=${query.signInName}&num=${query.index || 1}&signInId=${query.signInId}#/`;
  75. return (
  76. <Flex direction="column" align="stretch" className={`${styles.qrcodePage} flex100`} style={{ overflow: 'auto' }}>
  77. <NavBar
  78. title="二维码展示"
  79. handleBack={this.handleBack}
  80. />
  81. <Flex.Item className={`${styles.column} flex100`} style={{ background: '#F6F6F6', paddingBottom: 30 }}>
  82. <div id="capture">
  83. <div className={`${styles.card} ${styles.column}`}>
  84. <div className={`${styles.column}`} style={{ alignItems: 'flex-start', padding: '25px 25px 0 25px' }}>
  85. <span className={`${styles.title}`}>{query.signInName}</span>
  86. <span className={`${styles.date}`}>{query.createAt}</span>
  87. </div>
  88. <div id="QR" style={{ padding: '30px 0 35px 0', alignItems: 'center' }} className={styles.column}>
  89. <QRCode id='qrid' value={src} onClick={this._downLoad} size={260} />
  90. </div>
  91. <span className={`${styles.noticeText}`} >使用OA或党建APP扫描二维码签到</span>
  92. </div>
  93. </div>
  94. <div className={styles.saveBtn}>
  95. <div type="primary" className={styles.btnCss} onClick={this._downLoad}>保存到手机</div>
  96. </div>
  97. </Flex.Item>
  98. </Flex>
  99. );
  100. }
  101. }
  102. export default QRCodePage

可以在base64图片在线转换工具 - 站长工具该站点进行转换查看base64是否有效

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Gausst松鼠会/article/detail/215478
推荐阅读
相关标签
  

闽ICP备14008679号