美文网首页
解决html2canvas不支持object-fit:cover

解决html2canvas不支持object-fit:cover

作者: 冰点k | 来源:发表于2020-12-15 15:57 被阅读0次

使用的html2canvas版本是1.0.0-rc.7

问题背景

当要生成的html代码中包含img标签,并且设置了object-fit:cover属性后,通过html2canvas生成的图片object-fit:cover属性没有生效,导致生成的图片与通过样式设置的不一样。

解决方法

在项目中找到html2canvas源码,路径:/node_modules/html2canvas/dist/html2canvas.js,找到这个文件后,跳转到6281行(1.0.0-rc.7版本,其他版本可能不太一样),找到CanvasRenderer.prototype.renderReplacedElement = function (container, curves, image)这个方法的实现,修改为下面的代码:

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

这样就大功告成了,保存后再测试就解决了生成的图片与我们通过样式设置的图片不一样的问题!

有用的话点个赞支持一下吧!❤️

相关文章

网友评论

      本文标题:解决html2canvas不支持object-fit:cover

      本文链接:https://www.haomeiwen.com/subject/jlewgktx.html