自定义组件里canvas 2d生成的图片不完整?
在自定义组件里使用canvas 2d,在attached生命周期给组件节点赋值宽高后,绘制完整但生成的图片不完成。
const screen = wx.getSystemInfoSync().windowWidth / 750;
function isNumber(value) {
return /^-?\d+(\.\d+)?$/.test(value);
}
function toPx(value, baseSize) {
if (typeof value === 'number') {
return value
}
if (isNumber(value)) {
return value * 1
}
if (typeof value === 'string') {
const reg = /(em|rpx|px|%)$/g
const results = reg.exec(value);
if (!value || !results) {
return 0;
}
const unit = results[1];
value = parseFloat(value);
let res = 0;
if (unit === 'rpx') {
res = Math.floor(value * (screen || 0.5) * 1);
} else if (unit === 'px') {
res = Math.floor(value * 1);
}
return res;
}
}
Component({
data: {
width: '',
height: '',
url: '',
boundary: {
left: 0,
top: 0,
width: 0,
height: 0
}
},
lifetimes: {
attached() {
this.setData({
width: '480rpx',
height: '854rpx',
})
const dpr = wx.getSystemInfoSync().pixelRatio
const query = this.createSelectorQuery()
query.select('#canvas')
.fields({
node: true,
size: true
})
.exec((res) => {
const canvas = res[0].node
const ctx = canvas.getContext('2d')
canvas.width = res[0].width * dpr
canvas.height = res[0].height * dpr
this.setData({
canvas,
'boundary.width': res[0].width,
'boundary.height': res[0].height
})
ctx.scale(dpr, dpr)
ctx.fillStyle = '#00B2B6'
ctx.fillRect(0, 0, canvas.width, canvas.height)
ctx.fillStyle = 'red'
ctx.fillRect(toPx('20rpx'), toPx('20rpx'), toPx('440rpx'), toPx('600rpx'))
})
setTimeout(() => {
const {
left,
top,
width,
height
} = this.data.boundary
let destWidth = width * dpr
let destHeight = height * dpr
const copyArgs = {
x: left,
y: top,
width,
height,
destWidth,
destHeight,
canvas: this.data.canvas,
success: (res) => {
this.triggerEvent('success', res.tempFilePath)
},
}
wx.canvasToTempFilePath(copyArgs)
}, 200);
}
},
})