学无先后,达者为师

网站首页 编程语言 正文

html2canvas 不支持图片的object-fit样式

作者:yunchong_zhao 更新时间: 2022-04-18 编程语言

我本来给图片设置了object-fit:cover;

但是 html2canvas画完之后 竟然消失了
这个就很奇怪了,包括图片的圆角也没有了,
我翻了翻一些文档说

  1. 子元素设置相对于父元素宽高 然后在设置object-fit (我试了试不行pass掉了)
  2. 就是通过设置父元素弹性布局。什么鬼我试了试也是不行
  3. 最后看一个博客是 修改源码 最后成功了。
    本来想找到那篇博客呢。后来找不到 但是代码我这边还有保存
    我的html2canvas和那个博主的版本还不相同但是代码 没变多少

找到你的项目中的node_modules/html2canvas/dist/html2canavs.js文件
然后搜索
CanvasRenderer.prototype.renderReplacedElement

 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();
			}
        };

最后保存就可以。
大功告成。
关注我 持续更新前端 知识。

原文链接:https://yunchong.blog.csdn.net/article/details/121756284

栏目分类
最近更新