index.js 8.73 KB
Newer Older
zhanghaozhe committed
1 2 3 4 5 6
import React, { Component } from "react"
import "./index.scss"
import { HeaderBar } from "src/common"
import { http, getParam } from "src/utils"
import QRCode from "qrcode"
import { Toast } from "antd-mobile"
xuzhenghua committed
7 8

class SharePoster extends Component {
zhanghaozhe committed
9 10 11 12 13 14 15 16 17 18 19
  constructor(props) {
    super(props)
    this.state = {
      codeSrc: "",
      billSrc: "", // 图片链接
      imgUrl: "",
      smallListImg: [], // 小图片地址
      smallactive: 0, // 小图选中标记
      distPrice: "", // 分销价格
      name: "", // 用户姓名
      bgImage: [], // 背景图
xuzhenghua committed
20
    }
zhanghaozhe committed
21
  }
xuzhenghua committed
22

zhanghaozhe committed
23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
  componentDidMount() {
    this.getCodeWe()
    http
      .get(
        `${API.home}/m/dist/posters/${getParam("courseId")}/${getParam("uid")}`
      )
      .then((res) => {
        // console.log(res);
        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)
        } else {
          Toast.info(res.data.msg, 2)
        }
      })
  }
xuzhenghua committed
45

zhanghaozhe committed
46 47 48 49 50 51 52 53 54 55
  // 初始化海报
  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 - 18 // 头像Y轴位置
xuzhenghua committed
56

zhanghaozhe committed
57 58
    let qrCodePositionX = imgList[index].qr_code_x * $width // 二维码x轴位置
    let qrCodePositionY = imgList[index].qr_code_y * $height + 7 // 二维码y轴位置
xuzhenghua committed
59

zhanghaozhe committed
60 61 62 63 64 65 66 67 68 69 70 71 72 73 74
    var canvas = document.getElementById("canvas"),
      context = canvas.getContext("2d")
    _this
      .getBase64(imgSrc1)
      // 背景图片合成
      .then((img) => {
        let bgImage = new Image()
        bgImage.src = img
        let qrCodeImg = document.getElementById("qrcode")
        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")
        }
xuzhenghua committed
75

zhanghaozhe committed
76 77 78 79 80 81 82 83 84 85 86 87 88 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
        bgImage.setAttribute("crossOrigin", "anonymous")
        bgImage.onload = function () {
          context.drawImage(bgImage, 0, 0, 450, 800)
          context.drawImage(
            qrCodeImg,
            qrCodePositionX,
            qrCodePositionY,
            100,
            100
          )
          context.fillStyle = imgList[index].username_color
          context.font = "16px serif"
          context.fillText(
            "@" + _this.state.name,
            avatarPositionX + avatarWidth + 20,
            avatarPositionY + avatarHeight / 2
          )
          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),
xuzhenghua committed
121
            })
zhanghaozhe committed
122 123 124 125 126 127 128 129 130 131 132 133
          }
        })
      })
  }
  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
xuzhenghua committed
134
        }
zhanghaozhe committed
135 136 137 138
      }
    } else {
      ary = Array.prototype.slice.call(curEle.children)
    }
xuzhenghua committed
139

zhanghaozhe committed
140 141 142 143 144 145 146
    // 获取指定子元素
    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--
xuzhenghua committed
147
        }
zhanghaozhe committed
148
      }
xuzhenghua committed
149 150
    }

zhanghaozhe committed
151 152
    return ary
  }
xuzhenghua committed
153

zhanghaozhe committed
154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176
  // 合成图片位置
  imgPosition = (ctx, img, x, y, r) => {
    ctx.save()
    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
    let qrCodeLink = `https://m.julyedu.com/detail?id=${getParam(
      "courseId"
    )}&dist_code=${getParam("dist_code")}`
    return new Promise((resolve) => {
      QRCode.toDataURL(qrCodeLink, {}, function (err, url) {
        _this.setState({
          codeSrc: url,
        })
      })
      /*
xuzhenghua committed
177 178 179 180 181 182 183 184
                        let qrcode = new QRCode(document.getElementById('qrcode'), {
                            text: qrCodeLink,
                            width: 160,
                            height: 160,
                            colorDark: "#000000", // 生成的二维码的深色部分
                            colorLight: "#ffffff", //生成二维码的浅色部分
                        })
            */
zhanghaozhe committed
185 186 187
      resolve()
    })
  }
xuzhenghua committed
188

zhanghaozhe committed
189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207
  // 图片路径转成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)
      }
    })
  }
xuzhenghua committed
208

zhanghaozhe committed
209 210 211 212 213
  // 图片路径放入canvas转成base64
  getBase64Image = (img) => {
    let canvas = document.createElement("canvas")
    canvas.width = img.width
    canvas.height = img.height
xuzhenghua committed
214

zhanghaozhe committed
215 216 217
    let ctx = canvas.getContext("2d")
    ctx.drawImage(img, 0, 0, img.width, img.height)
    let ext = img.src.substring(img.src.lastIndexOf(".") + 1).toLowerCase()
zhanghaozhe committed
218
    return canvas.toDataURL("image/" + ext)
zhanghaozhe committed
219
  }
xuzhenghua committed
220

zhanghaozhe committed
221 222 223 224 225 226
  // canvas转换成img图片
  convertCanvasToImage = (canvas) => {
    let image = new Image()
    image.src = canvas.toDataURL("image/png")
    return image
  }
xuzhenghua committed
227

zhanghaozhe committed
228 229 230 231 232 233 234
  // 小图切换
  squareClick = (index) => {
    this.setState({
      smallactive: index,
    })
    this.initCanvas(this.state.bgImage, index)
  }
xuzhenghua committed
235

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

zhanghaozhe committed
294
export default SharePoster