Skip to content

Wxml2Json

关于 Wxml2Json 的前世今生,你可以阅读《我们如何从 Wxml2Canvas 迁移到 Painter》

简而言之,Wxml2Json 是一个可以将 Wxml 转换为 Painter 的 JSON 配置的解决方案,在项目开发中需要绘制分享海报时,使用 HTML + CSS 来实现布局显然要比手动编写 JSON 配置更加容易。

通常我们更推荐使用现成的分享海报组件,只有当现有组件无法满足需求时,才考虑直接使用 Wxml2Json 实现。

基本使用

下面提供一个示例,以便快速熟悉 Wxml2Json 的使用:

vue
<script setup>
import {ref, watchEffect, getCurrentInstance} from 'vue'
import {Wxml2Json, useElementSize} from '@ifanrx/uni-mp'

const instance = getCurrentInstance()

const template = ref(null)

async function wxml2Json() {
  // 获取容器的尺寸
  const {width, height} = await getElementSize(
    '.draw-container',
    instance.parent
  )

  // 传入容器尺寸,当前组件上下文, 以便获取元素
  const drawImage = new Wxml2Json({
    width,
    height,
    context: instance.parent,
    background: props.backgroundColor,
  })

  // 开始绘制,传入容器选择器、节点选择器
  const config = await drawImage.draw({
    container: '.draw-container',
    className: '.draw',
  })

  // eslint-disable-next-line no-console
  console.info('wxml2json -->', JSON.stringify(config))

  return config
}

async function draw() {
  return new Promise((resolve, reject) => {
    nextTick(async () => {
      try {
        template.value = await wxml2Json()
      } catch (err) {
        reject(err)
      }
    })
  })
}
</script>

<template>
  <button @click="draw">绘制海报</button>

  <view class="draw-container">
    <!-- 这里写需要绘制的内容 -->

    <!-- 绘制文字 -->
    <view class="draw title" data-text="自定义文字"> 自定义文字 </view>

    <!-- 绘制图片 -->
    <image
      class="draw bg"
      data-type="image"
      data-url="https://cloud-minapp-41177.cloud.ifanrusercontent.com/1qPEKMXsNudMRAtY.png"
      src="https://cloud-minapp-41177.cloud.ifanrusercontent.com/1qPEKMXsNudMRAtY.png"
    />
  </view>
</template>

inlineText

html
<view class="draw center" data-id="prize" data-type="inlineText">
  <view class="draw lucky-content" data-for="prize" data-text="抽中了"
    >抽中了</view
  >
  <view
    class="draw lucky-content lucky-content-emphasize"
    data-for="prize"
    :data-text="prize.extension.display_name || prize.name"
  >
    {{ `「${prize.extension.display_name || prize.name}」` }}
  </view>
  <view class="draw lucky-content" data-for="prize" data-text="晒晒我的福气">
    晒晒我的福气
  </view>
</view>

dataset 属性

  • data-id: 元素 id
  • data-type: rect | text | image | inlineText
  • data-color: 真机解析渐变颜色会有问题(会丢失百分比),需要通过该属性指定渐变颜色(带百分比)
  • data-for: inlineText 子文本,用于指定父元素 id
  • data-line-clamp: 文本行数
  • data-has-border: 是否有边框,当元素有边框样式时需要设置为 true
  • data-whitespace: wrap | nowrap 是否换行

相关文档