html2canvas 不支持图片的object-fit样式
在页面上面效果是实现了图片从中间向两边放大至全屏,保持纵横比,但是通过html2canvas截图之后会发现图片会以宽100%高100%,未保持纵横比呈现在新截的图上面,导致与预期效果不一致
我本来给图片设置了
js
.full-screen-image {
width: 100%;
height: 100%;
position: absolute;
top: 0;
left: 0;
object-fit: cover; /* 保持图片的纵横比 */
}
找到项目中的node_modules/html2canvas/dist/html2canavs.js
文件 然后搜索CanvasRenderer.prototype.renderReplacedElement
替换内容如下
js
CanvasRenderer.prototype.renderReplacedElement = function (container, curves, image) {
// 原来的代码 注释掉
// if (image && container.intrinsicWidth > 0 && container.intrinsicHeight > 0) {
// var box = contentBox(container);
// var path = calculatePaddingBoxPath(curves);
// this.path(path);
// this.ctx.save();
// this.ctx.clip();
// this.ctx.drawImage(image, 0, 0, container.intrinsicWidth, container.intrinsicHeight, box.left, box.top, box.width, box.height);
// this.ctx.restore();
// }
// 改成下面的代码
if (image && container.intrinsicWidth > 0 && container.intrinsicHeight > 0) {
var box = contentBox(container);
var path = calculatePaddingBoxPath(curves);
this.path(path);
this.ctx.save();
this.ctx.clip();
let newWidth;
let newHeight;
let newX = box.left;
let newY = box.top;
if(container.intrinsicWidth / box.width < container.intrinsicHeight / box.height) {
newWidth = box.width;
newHeight = container.intrinsicHeight * (box.width / container.intrinsicWidth);
newY = box.top + (box.height - newHeight) / 2;
} else {
newWidth = container.intrinsicWidth * (box.height / container.intrinsicHeight);
newHeight = box.height;
newX = box.left + (box.width - newWidth) / 2;
}
this.ctx.drawImage(image, 0, 0, container.intrinsicWidth, container.intrinsicHeight, newX, newY, newWidth, newHeight);
this.ctx.restore();
}
};
替换完记得重启项目,否则还是不生效