问题
html代码中包含img标签,img样式设置了object-fit属性后,通过html2canvas生成的图片object-fit属性没有生效,导致生成的图片形变。
解决
修改依赖包中html2canvas源码,路径 /node_modules/html2canvas/dist/html2canvas.js
,搜索CanvasRenderer.prototype.renderReplacedElement = function (container, curves, image)
,修改该方法内部实现:
object:cover效果实现
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();
// }
// 修改后
// Start Custom Code
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();
}
// End Custom Code
};
object-fit:contain效果实现
修改部分代码,将上面的,if(container.intrinsicWidth / box.width < container.intrinsicHeight / box.height)
修改为if(box.width / container.intrinsicWidth < box.height / container.intrinsicHeight)
,即可实现object-fit:contain