您现在的位置是:网站首页>软件开发>前端技术栈>vuevue

vue中使用html2canvas的坑(3)画图片时不支持object-fit:cover的问题

风口下的猪2022-09-03vue

简介

问题背景

当要生成的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
        };


很赞哦! (0)

  • 软件开发
  • 素质要求
  • 计算机基础
  • 架构
  • 安全
  • 性能
  • 运维
  • 尾页
  • 数据库
  • 开发终端
  • 语言基础
  • 项目管理
  • 产品设计
  • 系统
  • 工作规范
  • 计算机网络
  • 前端技术栈
  • 数据结构
  • 计算机组成原理
  • 后端技术栈
  • 性能优化
  • 安全设计
  • 常见模块
  • 计算机操作系统
  • 服务器
  • python
  • MySQL
  • thinkphp
  • PHP
  • Java
  • JavaScript
  • Windows
  • Linux
  • 特效
  • indexedDB
  • vue
  • 淘宝联盟
  • Ionic
  • Angular
  • 微信小程序
  • 支付宝小程序
  • uni-app
  • css/sass/less
  • 支付
  • socket
  • 爬虫
  • web性能优化
  • 消息推送
  • CVM
  • sqlite
  • Redis
  • 前端基础
  • 基础
  • element
  • Nginx
  • yii2
  • /ponder/index.php/index/catelist/catelist/cateid/10.html

    相关阅读 (同一栏目)

    << /

    标签云

    站点信息

    • 文章统计:528篇
    • 移动端访问:扫码进入SQ3R