如何用代码生成图片

1,731 阅读2分钟

前言

技术围绕业务开发。随着获取新用户的成本越来越高。拉新的方式有很多种,而分享却是低成本且有效的方式之一。

分享的形式有很多,大多以内容为驱动,链接形式分享出去。今天我们介绍如何通过代码生成图片让用户进行分享。包括web端小程序端

web端

web端使用html2canvas组件来生成图片,它可以让我们编写的html代码转成base64位格式的图片进行显示。

文档地址http://html2canvas.hertzen.com/configuration/

.box为需要生成图片的父节点

useCORS: true是允许图片跨域

生成的出来的是base64位格式的图片

var main = document.querySelector('.box');
html2canvas(main, {
    useCORS: true
}).then((canvas) => {
    var dataUrl = canvas.toDataURL();
   console.log(dataUrl)
})

注意!!!

html2canvas新版本对ios兼容性不是很好

最好安装1.0.0-rc.4版本

小程序端

小程序主要通过绘制canvas来生成图片,但是canvas对我来说很抽象

想着是在开源社区上找插件进行处理

找到了Painter组件,JSON驱动帮助我们生成图片

文档地址https://github.com/Kujiale-Mobile/Painter

把开源项目目录components/painter的文件下载,放置到自己的components/painter文件夹中

页面json文件进行引入

{
  "usingComponents": {
    "painter": "../../components/painter/painter"
  }
}

image用来放图片链接的容器

<painter customStyle='position: absolute; left: -9999rpx;' palette="{{template}}" bind:imgOK="canvasSuc" />
<image mode="widthFix" src="{{image}}" />
Page({
  data: {
    template: {},
    image: "",
    width: 750,
    height: 900,
    name: "wePanda",
    avatar: "https://sucai.suoluomei.cn/sucai_zs/images/20201125135948-1.png",
    code: "https://sucai.suoluomei.cn/sucai_zs/images/20201125135949-2.jpg",
  },

  onLoad() {
    this.getDraw()
  },

  getDraw() {
    this.setData({
      template: {
        background: '#74C7D7',
        width: this.data.width + 'px',
        height: this.data.height + 'px',
        views: [{
          type: 'rect',
          css: {
            top: '30px',
            left: this.data.width / 2 + "px",
            width: '690px',
            height: '840px',
            borderRadius: '10px',
            color: '#fff',
            align: 'center',
          },
        }, {
          type: 'image',
          url: this.data.avatar,
          css: {
            top: '100px',
            left: this.data.width / 2 + "px",
            width: '150px',
            height: '150px',
            borderRadius: '100px',
            mode: "aspectFill",
            align: 'center',
          },
        }, {
          type: 'image',
          url: this.data.code,
          css: {
            top: '300px',
            left: this.data.width / 2 + "px",
            width: '300px',
            height: '300px',
            mode: "aspectFill",
            align: 'center',
          },
        }, {
          type: 'text',
          text: "长按扫描二维码关注公众号",
          css: {
            top: '700px',
            left: this.data.width / 2 + 'px',
            fontSize: '28px',
            color: "#666666",
            align: 'center',
          },
        }],
      }
    })
  },

  // 生成成功的回调
  canvasSuc(e) {
    this.setData({
      image: e.detail.path
    })
    wx.saveImageToPhotosAlbum({
      filePath: e.detail.path
    })
  },
})

复制代码可直接查看效果