index.js 11 KB
Newer Older
FE committed
1 2 3 4 5 6
import React, {Component} from 'react';
import './index.scss';
import {HeaderBar} from '@/common';
import {http, getParam} from '@/utils';
import QRCode from 'qrcode';
import { Toast} from 'antd-mobile';
xuzhenghua committed
7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23

class SharePoster extends Component {
    constructor(props) {
        super(props)
        this.state = {
            codeSrc: '',
            billSrc: '',         // 图片链接
            imgUrl: '',
            smallListImg: [],  // 小图片地址
            smallactive: 0,  // 小图选中标记
            distPrice: '',  // 分销价格
            name: '',       // 用户姓名
            bgImage: []          // 背景图
        }
    }

    componentDidMount() {
FE committed
24
        this.getCodeWe();
zhanghaozhe committed
25
        http.get(`${API.home}/m/dist/posters/${getParam('courseId')}/${getParam('uid')}`).then((res) => {
26
            // console.log(res);
xuzhenghua committed
27 28 29 30 31 32 33 34 35
            if (res.data.code === 200) {
                this.setState({
                    imgUrl: res.data.data.avatar,
                    smallListImg: res.data.data.list,
                    distPrice: res.data.data.dist_course,
                    bgImage: res.data.data.list,
                    name: res.data.data.username
                })
                this.initCanvas(this.state.bgImage, 0)
xuzhenghua committed
36 37
            } else {
                Toast.info(res.data.msg, 2)
xuzhenghua committed
38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
            }
        })
    }

    // 初始化海报
    initCanvas = (imgList, index) => {
        let _this = this;
        let imgSrc1 = imgList[index].poster;
        let $width = 450;
        let $height = 800;
        let avatarWidth = 50    // imgList[index].poster_width    // 头像宽度
        let avatarHeight = 50   // imgList[index].poster_height     // 头像高度
        let avatarPositionX = (imgList[index].header_position_x * $width)  // 头像x轴位置
        let avatarPositionY = (imgList[index].header_position_y * $height)   // 头像Y轴位置

        let qrCodePositionX = imgList[index].qr_code_x * $width // 二维码x轴位置
        let qrCodePositionY = imgList[index].qr_code_y * $height  // 二维码y轴位置
        let qrCodeWidth = (imgList[index].qr_code_width * $width)      // 二维码宽度
        let qrCodeHeight = (imgList[index].qr_code_height * $height) - avatarHeight / 2     // 二维码高度

FE committed
58
        let qrCodeLink = `https://m.julyedu.com/detail?id=${getParam('courseId')}&dist_code${getParam('dist_code')}`
xuzhenghua committed
59 60 61

        var canvas = document.getElementById("canvas"),
            context = canvas.getContext("2d");
62
        // console.log(_this);
xuzhenghua committed
63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87
        _this.getBase64(imgSrc1)
        // 背景图片合成
            .then((img) => {
                let bgImage = new Image();
                bgImage.src = img;
                let qrCodeImg = document.getElementById('qrcode');
                let ua = navigator.userAgent.toLowerCase();
                // Android终端
                let isAndroid = ua.indexOf('Android') > -1 || ua.indexOf('Adr') > -1;
                // Ios终端
                let isiOS = !!ua.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/);
                if (/(iPhone|iPad|iPod|iOS)/i.test(navigator.userAgent)) {
                    qrCodeImg = document.getElementById('qrcode');
                } else if (/(Android)/i.test(navigator.userAgent)) {
                    //Android终端
                    qrCodeImg = document.getElementById('qrcode');

                }

                bgImage.setAttribute('crossOrigin', 'anonymous');
                bgImage.onload = function () {
                    context.drawImage(bgImage, 0, 0, 450, 800);
                    context.drawImage(qrCodeImg, 320, 685, 100, 100);
                    context.fillStyle = imgList[index].username_color;
                    context.font = "16px serif";
FE committed
88
                    context.fillText('@' + _this.state.name, (avatarPositionX + avatarWidth) + 20, (avatarPositionY + avatarHeight / 2));
xuzhenghua committed
89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157
                    context.font = "14px serif";
                    context.fillText('正在学习该课程', (avatarPositionX + avatarWidth) + 20, (avatarPositionY + avatarHeight / 2) + 20);
                    context.restore();
                }

            })
            // 头像生成
            .then(() => {
                _this.getBase64(_this.state.imgUrl)
                    .then((img) => {
                        let bgImage = new Image();
                        bgImage.src = img;
                        bgImage.setAttribute('crossOrigin', 'anonymous');
                        bgImage.setAttribute('border-Radius', '50%');
                        bgImage.onload = function () {
                            _this.imgPosition(context, bgImage, avatarPositionX, avatarPositionY, 24);
                            context.drawImage(bgImage, avatarPositionX, avatarPositionY, 48, 48);
                            context.restore();
                            _this.setState({
                                billSrc: _this.convertCanvasToImage(canvas)
                            })

                        }
                    })

            })
    }
    children = (curEle, tagName) => {
        var nodeList = curEle.childNodes;
        var ary = [];
        if (/MSIE(6|7|8)/.test(navigator.userAgent)) {
            for (var i = 0; i < nodeList.length; i++) {
                var curNode = nodeList[i];
                if (curNode.nodeType === 1) {
                    ary[ary.length] = curNode;
                }
            }
        } else {
            ary = Array.prototype.slice.call(curEle.children);
        }

        // 获取指定子元素
        if (typeof tagName === "string") {
            for (var k = 0; k < ary.length; k++) {
                curEle = ary[k];
                if (curEle.nodeName.toLowerCase() !== tagName.toLowerCase()) {
                    ary.splice(k, 1);
                    k--;
                }
            }
        }

        return ary;
    }

    // 合成图片位置
    imgPosition = (ctx, img, x, y, r) => {
        ctx.save();
        var d = 2 * r;
        var cx = x + r;
        var cy = y + r;
        ctx.beginPath();
        ctx.arc(cx, cy, r, 0, 2 * Math.PI);
        ctx.clip();
    }

    // 获取二维码
    getCodeWe() {
        let _this = this
FE committed
158
        let qrCodeLink = `https://m.julyedu.com/detail?id=${getParam('courseId')}&dist_code=${getParam('dist_code')}`
xuzhenghua committed
159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222
        return new Promise(resolve => {
            QRCode.toDataURL(qrCodeLink, {}, function (err, url) {
                _this.setState({
                    codeSrc: url
                })
            })
            /*
                        let qrcode = new QRCode(document.getElementById('qrcode'), {
                            text: qrCodeLink,
                            width: 160,
                            height: 160,
                            colorDark: "#000000", // 生成的二维码的深色部分
                            colorLight: "#ffffff", //生成二维码的浅色部分
                        })
            */
            resolve()
        })
    }

    // 图片路径转成base64
    getBase64(img) {
        let _this = this;
        return new Promise(resolve => {
            let base64 = null;
            let image = new Image();
            let timeStamp = +new Date();
            image.setAttribute('crossOrigin', 'anonymous');
            image.src = img + '?' + timeStamp;
            image.onload = () => {
                base64 = _this.getBase64Image(image)
                resolve(base64)
            }
            image.onerror = function () {
                let timeStamp = +new Date();
                _this.getBase64(img + '?' + timeStamp);
            }
        })

    }

    // 图片路径放入canvas转成base64
    getBase64Image = (img) => {
        let canvas = document.createElement("canvas");
        canvas.width = img.width;
        canvas.height = img.height;

        let ctx = canvas.getContext("2d");
        ctx.drawImage(img, 0, 0, img.width, img.height);
        let ext = img.src.substring(img.src.lastIndexOf(".") + 1).toLowerCase();
        let dataURL = canvas.toDataURL("image/" + ext);
        return dataURL;
    }

    // canvas转换成img图片
    convertCanvasToImage = (canvas) => {
        let image = new Image();
        image.src = canvas.toDataURL("image/png");
        return image;
    }

    // 小图切换
    squareClick = (index) => {
        this.setState({
            smallactive: index
FE committed
223
        });
xuzhenghua committed
224 225 226 227
        this.initCanvas(this.state.bgImage, index);
    }

    render() {
FE committed
228
        const { distPrice={}, smallListImg=[], smallactive } = this.state;
xuzhenghua committed
229 230
        return (
            <div className='share-poster'>
FE committed
231 232 233 234 235
                <HeaderBar 
                    title='生成专属海报' 
                    arrow={true} 
                    cart={false}
                />
xuzhenghua committed
236 237
                <div className="total-container">
                    <div className='placard-img-container' id='imgWrapper'>
FE committed
238
                        <img src={this.state.billSrc.src} alt="" />
xuzhenghua committed
239
                    </div>
FE committed
240 241 242 243 244 245 246 247 248 249 250 251
                    <img 
                        src={this.state.codeSrc} 
                        alt="" 
                        id='qrcode' 
                        className='placard-code'
                    />
                    <canvas 
                        id='canvas' 
                        width='450' 
                        height='800'
                        className={this.state.billSrc === '' ? '' : 'hide'}
                    />
xuzhenghua committed
252 253 254 255 256
                </div>
                <div className='placard-desc'>
                    <span className='placard-sharetxt'>
                        长按保存海报分享给好友,每有一人通过您的分享购买该课程,您可以
                        {
FE committed
257 258 259 260
                            distPrice.count_type === 0 &&
                            <span className='placard-price'>
                                获得{distPrice.first_level_tip}元的佣金奖励。
                            </span>
xuzhenghua committed
261 262
                        }
                        {
FE committed
263 264 265 266
                            distPrice.count_type === 1 &&
                            <span className='placard-price'>
                                获得成交金额的{distPrice.first_level_scale}%作为佣金奖励。
                            </span>
xuzhenghua committed
267 268 269 270 271 272
                        }
                    </span>
                </div>
                <div className='placard-swiper'>
                    <ul className='placard-list'>
                        {
FE committed
273
                            smallListImg.length > 0 && smallListImg.map((item, index) => {
xuzhenghua committed
274
                                return (
FE committed
275 276 277 278 279 280
                                    <li 
                                        onClick={this.squareClick.bind(this, index)} 
                                        key={index}
                                        className={smallactive === index ? 'active' : ''}
                                    >
                                        <img src={item.square} alt="" />
xuzhenghua committed
281
                                    </li>
FE committed
282
                                );
xuzhenghua committed
283 284 285 286 287
                            })
                        }
                    </ul>
                </div>
            </div>
FE committed
288
        );
xuzhenghua committed
289 290 291
    }
}

FE committed
292
export default SharePoster;