canvas繪圖時drawImage,需要繪制的圖片大小不同,比例各異,所以就需要像html+css布局那樣,需要contain和cover來滿足不同的需求。
contain
保持縱橫比縮放圖片,使圖片的長邊能完全顯示出來。也就是說,可以完整地將圖片顯示出來。
圖片按照contain模式放到固定盒子的矩形內(nèi),則需要對圖片進(jìn)行一定的縮放。
原則是:
如果圖片寬高不等,使圖片的長邊能完全顯示出來,則原圖片高的一邊縮放后等于固定盒子對應(yīng)的一邊,等比例求出另外一邊,
如果圖片寬高相等,則根據(jù)固定盒子的寬高來決定縮放后圖片的寬高,固定盒子的寬大于高,則縮放后的圖片高等于固定盒子的高度,對應(yīng)求出另外一邊即可,反之亦然。
/** * @param {Number} sx 固定盒子的x坐標(biāo),sy 固定盒子的y左標(biāo) * @param {Number} box_w 固定盒子的寬, box_h 固定盒子的高 * @param {Number} source_w 原圖片的寬, source_h 原圖片的高 * @return {Object} {drawImage的參數(shù),縮放后圖片的x坐標(biāo),y坐標(biāo),寬和高},對應(yīng)drawImage(imageResource, dx, dy, dWidth, dHeight) */ function containImg(sx, sy , box_w, box_h, source_w, source_h){ var dx = sx, dy = sy, dWidth = box_w, dHeight = box_h; if(source_w > source_h || (source_w == source_h && box_w < box_h)){ dHeight = source_h*dWidth/source_w; dy = sy + (box_h-dHeight)/2; }else if(source_w < source_h || (source_w == source_h && box_w > box_h)){ dWidth = source_w*dHeight/source_h; dx = sx + (box_w-dWidth)/2; } return{ dx, dy, dWidth, dHeight } } var c=document.getElementById("myCanvas"); var ctx=c.getContext("2d"); ctx.fillStyle = '#e1f0ff'; //固定盒子的位置和大小--圖片需要放在這個盒子內(nèi) ctx.fillRect(30, 30, 150, 200); var img = new Image(); img.onload = function () { console.log(img.width,img.height); var imgRect = containImg(30,30,150,200,img.width,img.height); console.log('imgRect',imgRect); ctx.drawImage(img, imgRect.dx, imgRect.dy, imgRect.dWidth, imgRect.dHeight); } img.src = "./timg2.jpg"; //注:img預(yù)加載模式下,onload應(yīng)該放在為src賦值的上面,以避免已有緩存的情況下無法觸發(fā)onload事件從而導(dǎo)致onload中的事件不執(zhí)行的情況發(fā)生
cover
保持縱橫比縮放圖片,只保證圖片的短邊能完全顯示出來。也就是說,圖片通常只在水平或垂直方向是完整的,另一個方向?qū)l(fā)生截取。
原理:
按照固定盒子的比例截取圖片的部分
/** * @param {Number} box_w 固定盒子的寬, box_h 固定盒子的高 * @param {Number} source_w 原圖片的寬, source_h 原圖片的高 * @return {Object} {截取的圖片信息},對應(yīng)drawImage(imageResource, sx, sy, sWidth, sHeight, dx, dy, dWidth, dHeight)參數(shù) */ function coverImg(box_w, box_h, source_w, source_h){ var sx = 0, sy = 0, sWidth = source_w, sHeight = source_h; if(source_w > source_h || (source_w == source_h && box_w < box_h)){ sWidth = box_w*sHeight/box_h; sx = (source_w-sWidth)/2; }else if(source_w < source_h || (source_w == source_h && box_w > box_h)){ sHeight = box_h*sWidth/box_w; sy = (source_h-sHeight)/2; } return{ sx, sy, sWidth, sHeight } } var c=document.getElementById("myCanvas"); var ctx=c.getContext("2d"); ctx.fillStyle = '#e1f0ff'; //固定盒子的位置和大小--圖片需要放在這個盒子內(nèi) ctx.fillRect(30, 30, 150, 200); var img = new Image(); img.onload = function () { console.log(img.width,img.height); var imgRect = coverImg(150,200,img.width,img.height); console.log('imgRect',imgRect); ctx.drawImage(img, imgRect.sx, imgRect.sy, imgRect.sWidth, imgRect.sHeight, 30, 30, 150, 200); } img.src = "./timg2.jpg"; //注:img預(yù)加載模式下,onload應(yīng)該放在為src賦值的上面,以避免已有緩存的情況下無法觸發(fā)onload事件從而導(dǎo)致onload中的事件不執(zhí)行的情況發(fā)生
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持武林網(wǎng)。
新聞熱點
疑難解答