canvas将两张图片合并成一张图片并下载

用canvas将两张图片合并成一张图并下载(react)

  • 图片合成部分
generateCodePic = () => {
     
    this.downloadImg();
};
downloadImg() {
     
    var canvas = document.createElement('canvas');
    console.log(canvas);
    canvas.width = 600;
    canvas.height = 800;
    if (!canvas.getContext) return;
    var ctx = canvas.getContext('2d');
    var imgBack = this.bgImg; // 创建img元素
    imgBack.setAttribute('crossOrigin', 'anonymous');
    console.log(imgBack);
    ctx.drawImage(imgBack, 0, 0, 600, 800);
    var img = this.codeImg;
    img.setAttribute('crossOrigin', 'anonymous');
    ctx.drawImage(img, 100, 150, 400, 400);
    const canvasUrl = canvas.toDataURL('image/png');
    downLoad(canvasUrl);
    function downLoad(url) {
     
      var oA = document.createElement('a');
      oA.download = '二维码邀请函'; // 设置下载的文件名
      oA.href = url;
      document.body.appendChild(oA);
      oA.click();
      oA.remove(); // 下载之后把创建的元素删除
    }
  }

  • render函数内容
<img src={
     code} ref={
     ref => (this.codeImg = ref)} />
<img
	src={
     require('@/assets/img/invite.png')}
	ref={
     ref => (this.bgImg = ref)}
	style={
     {
      display: 'none' }}
/>
<Button type="primary" onClick={
     this.generateCodePic}>
点击生成二维码邀请函
</Button>

你可能感兴趣的:(React,canvas,react)