日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

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

欄目分類
最近更新