在近期工作中需要完成一个需求微信小程序使用camera拍摄照片并添加水印。
- 拿到需求先分析,首先是调用相机拍摄照片。这个就很简单了直接使用微信开放文档中所提供的camera实现。
- 主要是对相机拍摄的照片添加水影。在这里我是用的是微信开放文档中所提供的wxml-to-canvas实现。
以下是我的实现过程 调用相机拍摄照片设置全屏显示
<camera style="width: 100vw;height: 100vh;" binderror="bindCameraError"></camera>bindCameraError点击事件(拍摄照片)
bindCameraError点击事件() {
const ctx = wx.createCameraContext()
ctx.takePhoto({
quality: 'high',
success: (res) => {
this.setData({
src: res.tempImagePath
})
}
})
},
error(e) {
console.log(e.detail)
照片拍摄成功后返回图片路径,定义参数接收返回的图片路径(wxml-to-canvas需要使用到这个路径)。
接下来是使用wxml-to-canvas绘制图片和微信开放文档中的demo类似,主要是自定义一下水印内容。
在需要绘图的界面添加如下代码
<wxml-to-canvas class="widget" style="z-index: -999; position: absolute; bottom: -50;"></wxml-to-canvas>
由于我不需要在页面中展示,使用使用了定位。不要使用wx:if或overflow: hidden;隐藏wxml-to-canvas。
在onLoad中执行
this.widget = this.selectComponent('.widget')
在文件加下添加demo.js并引入(根据自己的路径来,demod的内容可以参考微信开放文档)
要注意demo中的渲染顺序把图片设置在最上边。
由于自定义内容所以在页面的js文件的data中需要添加
wxml: { week: "", time: "", specificDate: "", address: "", src: "", },
这是在demo.js展示的内容
对应的renderToCanvas方法中
const p1 = this.widget.renderToCanvas({ wxml: wxml(this.data.wxml), style })
也要进行变动,想要具体了解renderToCanvas方法的可以参考微信开放文档
renderToCanvas() {
const p1 = this.widget.renderToCanvas({ wxml, style })
p1.then((res) => {
this.container = res
this.extraImage()
})
},
extraImage() {
const p2 = this.widget.canvasToTempFilePath()
p2.then(res => {
this.setData({
src: res.tempFilePath,
width: this.container.layoutBox.width,
height: this.container.layoutBox.height
})
})
}
extraImage方法就是绘制图片,extraImage方法所返回的src就是带有水影的照片。
wxml-to-canvas文档链接
(第一次在掘金更文,有不对的地方欢迎指正~~~~~)