html
<canvas canvas-id="firstCanvas" :style="{width:canvasWidth +'px',height:canvasHeight +'px'}" style="border:1px solid #000000;" class="canvas"></canvas>
方法
// 分享图为 5:4
var width = res.width,
height = res.height;
//创建canvas
const ctx = uni.createCanvasContext('firstCanvas');
var xw = width, //最终的宽
yh = height; //最终的高
var catX = 0, //截取x坐标
catY = 0; //截取y坐标
var scale = 5/4;
// 判断当前图片是横图还是纵图
if(width > height){
xw = scale * yh;
catX = (width - xw) / 2;
}
// 2.竖向图片,求高
else{
yh = (width / 5) * 4;
catY = (height - yh) / 2;
}
this.canvasWidth = xw; //动态设置canvas宽
this.canvasHeight = yh; //动态设置canvas高
ctx.drawImage(res.path,catX, catY, xw, yh, 0, 0, xw, yh);
本文介绍如何将不同尺寸的图片适配到5:4比例的画布上,并通过调整坐标来确保图片完整显示。利用HTML5 Canvas API实现图片的绘制,包括确定图片在画布上的位置及大小。
156

被折叠的 条评论
为什么被折叠?



