1.0.3 • Published 2 years ago

cross-2canvas v1.0.3

Weekly downloads
-
License
MIT
Repository
-
Last release
2 years ago

跨平台使用canvas

原理

  1. 传入根据定义的json-schema,和已经创建的canvas,返回画布画好的canvas

json 定义

declare interface TextView {
    x: number,
    y: number,
    content: string,
    type: 'text',
    color: string,
    fontWeight: string,
    fontSize: number,
    lineHeight?: number,
    textContainerWidth?: number,
    textBaseline?: string,
    fontStyle?: string,
    fontVariant?: 'normal',
    textAlign?: 'left' | 'center' | 'right',
    fontFamily?: 'pfennigFont'
}
{
  width: 345, // 画布宽
  height: 600, // 画布高
  scale: 1.5, // 画布缩小宽高比
  views: [
    {
      type: 'image', // 类型图片
      url: '', // 图片地址
      x: 0, // 开始x坐标
      y: 0, // 开始y坐标
      width: 345, // 图片宽
      height: 600, // 图片高
      radius: 16 // 图片圆角
    },
    {
      type: 'text',
      content: '02.21-02.27',
      x: 0,
      y: 13,
      fontSize: 13,
      color: '#fff',
      textAlign: 'center'
    },
    {
      type: 'line',
      x: 172,
      y: 110,
      lineWidth: 1,
      strokeStyle: '#fff',
      targetX: 172,
      targetY: 130
    }
  ]
}

web使用

import { CreateImg } from 'cross-json-2canvas'
const width = nodeJson.width * nodeJson.scale
const height = nodeJson.height * nodeJson.scale
const canvas = document.createElement('canvas')
canvas.width = width
canvas.height = height
const result = await createCrossCanvas(canvas, nodeJson).draw()
this.shareImgUrl = result.toDataURL('image/png')

node使用

import { CreateImg } from 'cross-json-2canvas'
const { createCanvas, registerFont } = require('canvas')
const path = require('path')
const { CreateImg } = require('./../../common/canvas')
function fontFile (name) {
  return path.join(__dirname, '../pfennigFont/', name)
}
registerFont(fontFile('Pfennig.ttf'), { family: 'pfennigFont' })

const canvas = createCanvas(canvasJson.width, canvasJson.height)
createCrossCanvas(canvas, canvasJson, 'node')
  .draw().then((result) => {
    let resultUrl = result.toDataURL('image/png')
  })

wechat-progarm试用

import { createCrossCanvas } from 'cross-2canvas'
 wx.createSelectorQuery()
    .select('#myCanvas') // 在 WXML 中填入的 id
    .fields({ node: true, size: true })
    .exec(async (res) => {
        // Canvas 对象
        const canvas = res[0].node
        const width = res[0].width * (nodeJson.scale || 1)
        const height = res[0].height * (nodeJson.scale || 1)
        canvas.width = width
        canvas.height = height
        const result = await new createCrossCanvas(canvas, nodeJson, 'wx').draw()
        console.log('result-----', result)
    })
1.0.3

2 years ago

1.0.3-alpha.3

2 years ago

1.0.1

2 years ago