canvas绘图按照contain或者cover方式适配并居中显示

2020-04-24 19:16:43易采站长站整理

* @return {Object} {截取的图片信息},对应drawImage(imageResource, sx, sy, sWidth, sHeight, dx, dy, dWidth, dHeight)参数
*/
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';
//固定盒子的位置和大小--图片需要放在这个盒子内
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预加载模式下,onload应该放在为src赋值的上面,以避免已有缓存的情况下无法触发onload事件从而导致onload中的事件不执行的情况发生