解決html2canvas不支持object-fit:cover問題

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

問題背景

當(dāng)要生成的html代碼中包含img標(biāo)簽,并且設(shè)置了object-fit:cover屬性后,通過html2canvas生成的圖片object-fit:cover屬性沒有生效,導(dǎo)致生成的圖片與通過樣式設(shè)置的不一樣。

解決方法

在項目中找到html2canvas源碼,路徑:/node_modules/html2canvas/dist/html2canvas.js,找到這個文件后,跳轉(zhuǎn)到6281行(1.0.0-rc.7版本,其他版本可能不太一樣),找到CanvasRenderer.prototype.renderReplacedElement = function (container, curves, image)這個方法的實現(xiàn),修改為下面的代碼:

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

這樣就大功告成了,保存后再測試就解決了生成的圖片與我們通過樣式設(shè)置的圖片不一樣的問題!

有用的話點個贊支持一下吧!??

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容