小程序中的某些場景須要經過 canvas 繪製一些圖片, 其中包含一些文字、可能的二維碼等等。 而後實現時若是徹底手動的去定位元素在 canvas 中的位置,結果就會產生大量不能複用和難以維護的代碼。css
引入 utils 目錄下 utils/wxml2canvas.js
文件, 這個 repo 自己就是一個簡單的示例, 調整一些配置項能夠在開發者工具中打開。html
<!-- 1. wrapper id 2. 須要繪製的元素 className 3. 若是是文本,須要給元素添加加 data-text 屬性 -->
<view class="container" id="wrapper">
<text class="title draw" data-text="Hello there">Hello there</text>
<text class="info draw" data-text="小程序是一種新的開放能力,開發者能夠快速地開發一個小程序。">
小程序是一種新的開放能力,開發者能夠快速地開發一個小程序。
</text>
<view class="image-wrapper draw">
<image class="draw" src="../../assets/demo.jpg"/>
</view>
<button class="generate-btn" bindtap="drawCanvas">generate</button>
</view>
<canvas canvas-id="canvas-map" class="share-canvas"></canvas>
複製代碼
.container {
height: 100%;
box-sizing: border-box;
padding: 10px 20px;
display: flex;
flex-direction: column;
}
.container .title {
font-size:36px;
text-align: left;
margin-bottom: 10px;
}
.container .info {
font-size: 14px;
line-height: 18px;
color: grey;
text-align: left;
margin-bottom: 40px;
}
.container .image-wrapper image {
width: 100%;
}
複製代碼
Page({
drawCanvas: function() {
const wrapperId = '#wrapper'
const drawClassName = '.draw'
const canvasId = 'canvas-map'
wxml2canvas(wrapperId, drawClassName, canvasId).then(() => {
// canvas has been drawn here, you can save the canvas image with wx.canvasToTempFilePath
})
}
})
複製代碼
方式主要是使用小程序提供的接口 wx.createSelectorQuery() 來獲取節點信息, 而後進一步處理繪製到 canvas 上。目前僅覆蓋一些簡單的使用場景,支持基礎的 position,font-size, color, image, border-radius, background-color 等, 🌟🌟git
至於複雜的狀況,Maybe you can get some inspiration from github.com/niklasvh/ht…github
地址:github.com/gy134340/wx…canvas