?需求:畫布寬高為686 * 686 的正方形(可以進(jìn)行調(diào)整根據(jù)自身需要來)
? ? ? ? ? ? 當(dāng)圖片寬度大于高度時,對圖片寬度進(jìn)行裁剪
? ? ? ? ? ? ?當(dāng)圖片高度大于寬度時,對圖片高度進(jìn)行裁剪
? ? ? ? ? ? ?我是用uniApp進(jìn)行開發(fā)的,如果是小程序原生,直接把“uni” 改為 “wx”’
<canvas style="width:686rpx, height:686rpx" type="2d" canvas-id="firstCanvas" id="firstCanvas"></canvas>
?文章來源:http://www.zghlxwxcb.cn/news/detail-701187.html
init() {
const query = uni.createSelectorQuery().select('#firstCanvas').fields({
node: true,
size: true
}).exec((res) => {
//這里的代碼不能少 適配start
const canvas = res[0].node;
const ctx = canvas.getContext('2d');
const dpr = wx.getSystemInfoSync().pixelRatio
canvas.width = res[0].width * dpr // 獲取寬
canvas.height = res[0].height * dpr // 獲取高
ctx.scale(dpr, dpr)
//這里的代碼不能少 適配end
// 繪制背景圖片 ,
ctx.beginPath();
let imgDrawWidth = this.rpxToPx(686); // 圖片繪制區(qū)域的寬度 (可以調(diào)整)
let imgDrawHeight = this.rpxToPx(686); // 圖片繪制區(qū)域的高度(可以調(diào)整)
let canvasRatio = imgDrawWidth / imgDrawHeight;// 圖片繪制區(qū)域的寬高比例
let image = canvas.createImage(); //創(chuàng)建iamge實(shí)例
image.src ='https://img0.baidu.com/it/u=1885009107,1276967789&fm=253&app=138&size=w931&n=0&f=JPEG&fmt=auto?sec=1677258000&t=6f5b311ecc21d4c80e5b932b95590ddd';
// 圖片的寬高比例
image.onload = (e) => {
console.log("height",image.height)
console.log("width",image.width)
let imgRatio = image.width / image.height;
let dx, dy, dw, dh;
if (imgRatio <= canvasRatio) {
dw = image.width;
dh = image.width;
dx = 0;
dy = (image.height - image.width) / 2;
} else {
dw = image.height;
dh = image.height;
dx = (image.width - image.height) / 2
dy = 0;
}
ctx.drawImage(image, dx, dy, dw, dh, 0,0,imgDrawWidth,imgDrawHeight) // 背景圖
}
})
},
?文章來源地址http://www.zghlxwxcb.cn/news/detail-701187.html
// rpx轉(zhuǎn)px
rpxToPx(rpx) {
const screenWidth = uni.getSystemInfoSync().screenWidth
return (screenWidth * Number.parseInt(rpx)) / 750
},
到了這里,關(guān)于微信小程序canvas繪制自適應(yīng)圖片,UniApp canvas繪制自適應(yīng)圖片的文章就介紹完了。如果您還想了解更多內(nèi)容,請?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!