drawImage(pic, this.data.imgInfo.width, this.data.imgInfo.height)
// 等比例图片方法
function drawImage(imgPath, imgWidth, imgHeight) {
let dWidth = bg_w/imgWidth; // canvas与图片的宽度比例
let dHeight = bg_h/imgHeight; // canvas与图片的高度比例
if (imgWidth > bg_w && imgHeight > bg_h || imgWidth < bg_w && imgHeight < bg_h) {
if (dWidth > dHeight) {
ctx.drawImage(imgPath, 0, (imgHeight - bg_h/dWidth)/2, imgWidth, bg_h/dWidth, 0, 0, bg_w, bg_h)
} else {
ctx.drawImage(imgPath, (imgWidth - bg_w/dHeight)/2, 0, bg_w/dHeight, imgHeight, 0, 0, bg_w, bg_h)
}
} else {
if (imgWidth < bg_w) {
ctx.drawImage(imgPath, 0, (imgHeight - bg_h/dWidth)/2, imgWidth, bg_h/dWidth, 0, 0, bg_w, bg_h)
} else {
ctx.drawImage(imgPath, (imgWidth - bg_w/dHeight)/2, 0, bg_w/dHeight, imgHeight, 0, 0, bg_w, bg_h)
}
}
}
微信小程序canvas 图片不变形的方法
最新推荐文章于 2023-10-08 17:35:42 发布