小程序图片合成和h5合成的最大区别,就在于,小程序里面,没有dom元素的这个概念,而网上很多造好的轮子,很多都是基于dom的,所以,关于在小程序里面进行图片合成,只好自己写了,原本还以为挺麻烦的,没想到很简单,在这里给大家分享一下
<template>
<div class="photo">
<div @tap="images">
图片合成
</div>
<div class="canvas">
<canvas canvasId="canvasId" style="border:1px solid black;width:600rpx;height:800rpx;" />
</div>
<img :src="url" alt="">
</div>
</template>
<script>
import { image } from '../../utils/photo'
export default {
data() {
return {
url: null,
imgList: [
{
imgurl: 'http://n.sinaimg.cn/tech/5_img/upload/addfb8a1/779/w2048h2731/20180709/V-cP-hezpzwt7683324.jpg',
x: 0,
y: 0,
width: 300,
height: 400
},
{
imgurl: 'http://n.sinaimg.cn/tech/5_img/upload/addfb8a1/779/w2048h2731/20180709/V-cP-hezpzwt7683324.jpg',
x: 100,
y: 25,
width: 100,
height: 100
},
{
imgurl: 'http://n.sinaimg.cn/tech/5_img/upload/addfb8a1/779/w2048h2731/20180709/V-cP-hezpzwt7683324.jpg',
x: 100,
y: 75,
width: 100,
height: 100
},
{
imgurl: 'http://n.sinaimg.cn/tech/5_img/upload/addfb8a1/779/w2048h2731/20180709/V-cP-hezpzwt7683324.jpg',
x: 100,
y: 155,
width: 100,
height: 100
}
],
titleObject: {
fontSize: 30,
content: '水印文字',
x: 50,
y: 100
}
}
},
beforeMount() {
},
methods: {
images() {
let that = this
// 图片集合 水印文字对象 canvasid callback
image(that.imgList, that.titleObject, 'canvasId', function (res) {
that.url = res
})
}
}
}
</script>
<style lang="scss" scoped>
.photo {
position: relative;
background: white;
.canvas {
top: -500rpx;
left: 0;
position: absolute;
z-index: -10;
}
img {
width: 600rpx;
height: 800rpx;
}
}
</style>
下面是工具类
export const image = (imgList, titleObject, canvasIds, callback) => {
// 初始化画布,小程序里面一定要有canvasid,它是以这个为标识来识别的
const ctx = wx.createCanvasContext(canvasIds)
// 合成多张图片的时候,放到一个数组里面,进行遍历
imgList.forEach((item, index) => {
ctx.drawImage(
item.imgurl,
item.x,
item.y,
item.width,
item.height
)
})
// 写文字水印
ctx.setFontSize(titleObject.fontSize)
ctx.fillText(titleObject.content, titleObject.x, titleObject.y)
// 画出canvas上面的图片
ctx.draw(true, function () {
// wx.canvasToTempFilePath这个一定要写在ctx.draw里面的回调里面,是坑勿跳
wx.canvasToTempFilePath({
canvasId: canvasIds,
destWidth: 600,
destHeight: 800,
quality: 1,
success: function (res) {
console.log(res.tempFilePath)
callback(res.tempFilePath)
},
fail: function (res) {
console.log(res)
}
})
})
}