ctx.drawImage(res.path, x, y, w, h) API载入图片,IOS显示安卓不显示?
封装绘图的方法如下
/**
* @description: 绘制正方形(可以定义圆角),并且有图片地址的话填充图片
* @param {CanvasContext} ctx canvas上下文
* @param {number} x 圆角矩形选区的左上角 x坐标
* @param {number} y 圆角矩形选区的左上角 y坐标
* @param {number} w 圆角矩形选区的宽度
* @param {number} h 圆角矩形选区的高度
* @param {number} r 圆角的半径
* @param {String} url 图片的url地址
*/
export function drawSquarePic(ctx, x, y, w, h, r, url) {
ctx.save()
ctx.beginPath()
// 绘制左上角圆弧
ctx.arc(x + r, y + r, r, Math.PI, Math.PI * 1.5)
// 绘制border-top
// 画一条线 x终点、y终点
ctx.lineTo(x + w - r, y)
// 绘制右上角圆弧
ctx.arc(x + w - r, y + r, r, Math.PI * 1.5, Math.PI * 2)
// 绘制border-right
ctx.lineTo(x + w, y + h - r)
// 绘制右下角圆弧
ctx.arc(x + w - r, y + h - r, r, 0, Math.PI * 0.5)
// 绘制左下角圆弧
ctx.arc(x + r, y + h - r, r, Math.PI * 0.5, Math.PI)
// 绘制border-left
ctx.lineTo(x, y + r)
// 填充颜色(需要可以自行修改)
// #ifndef MP-TOUTIAO
// ctx.setFillStyle('transparent')
ctx.setFillStyle('#FFFFFF')
// #endif
// #ifdef MP-TOUTIAO
ctx.setFillStyle('#5E92EF')
// #endif
ctx.fill()
// 剪切,剪切之后的绘画绘制剪切区域内进行,需要save与restore 这个很重要 不然没办法保存
ctx.clip()
// 绘制图片
return new Promise((resolve, reject) => {
if (url) {
wx.getImageInfo({
src: url,
success(res) {
ctx.drawImage(res.path, x, y, w, h)
ctx.restore() //恢复之前被切割的canvas,否则切割之外的就没办法用
ctx.draw(true)
resolve()
},
fail(res) {
console.log('fail -> res', res)
uni.showToast({
title: '图片下载异常',
duration: 2000,
icon: 'none'
})
}
})
} else {
ctx.draw(true)
resolve()
}
})
}
实际上不是ctx.drawImage API无效,
而是安卓机ctx.setFillStyle 这个API设置透明无效,不要用这个API就好了,否则canvas就不显示了。