Html2canvas: Изображение заполнено, даже для div задано значение object-fit: cover;

Созданный на 27 февр. 2017  ·  13Комментарии  ·  Источник: niklasvh/html2canvas

http://imgur.com/3Zl6oRA | Рис 1
http://imgur.com/Wr006qF | Рис 2

Рис 1 - это div, который я хочу захватить, после того, как он сделал снимок, измените его размер * Рис 2.

Кто-нибудь мог это исправить?

Самый полезный комментарий

Здравствуйте, просто чтобы вы знали, что мне это нужно, и я взломал его для работы в моем проекте. Ниже я привожу код, который у меня работает. Однако это взлом, у меня нет знаний, чтобы интегрировать это в ваш проект более подходящим способом:

`` ''
ключ: 'drawImage',
значение: функция drawImage (изображение, источник, место назначения) {
/ НАЧАТЬ ТАМОЖЕННЫЙ КОД /

        var newWidth = 30;
        var newHeight = 30;
        var newX = destination.left;
        var newY = destination.top;

        // console.log(image, source, destination);
        if (source.width/destination.width > source.height/destination.height) {
            newWidth = destination.width;
            newHeight = source.height * (destination.width / source.width);
            newY = destination.top + (destination.height - newHeight) / 2;
        } else {
            newWidth = source.width * (destination.height / source.height);
            newHeight = destination.height;
            newX = destination.left + (destination.width - newWidth) / 2;
        }
      // console.log(newWidth, newHeight);

        this.ctx.drawImage(image, source.left, source.top, source.width, source.height,
          newX, newY,
          newWidth, newHeight);
        // destination.width,
        // destination.height * (source.height / source.width)
        //   destination.width, destination.height);

      /**END CUSTOM CODE**/
    }

`` ''

Все 13 Комментарий

Здравствуйте, просто чтобы вы знали, что мне это нужно, и я взломал его для работы в моем проекте. Ниже я привожу код, который у меня работает. Однако это взлом, у меня нет знаний, чтобы интегрировать это в ваш проект более подходящим способом:

`` ''
ключ: 'drawImage',
значение: функция drawImage (изображение, источник, место назначения) {
/ НАЧАТЬ ТАМОЖЕННЫЙ КОД /

        var newWidth = 30;
        var newHeight = 30;
        var newX = destination.left;
        var newY = destination.top;

        // console.log(image, source, destination);
        if (source.width/destination.width > source.height/destination.height) {
            newWidth = destination.width;
            newHeight = source.height * (destination.width / source.width);
            newY = destination.top + (destination.height - newHeight) / 2;
        } else {
            newWidth = source.width * (destination.height / source.height);
            newHeight = destination.height;
            newX = destination.left + (destination.width - newWidth) / 2;
        }
      // console.log(newWidth, newHeight);

        this.ctx.drawImage(image, source.left, source.top, source.width, source.height,
          newX, newY,
          newWidth, newHeight);
        // destination.width,
        // destination.height * (source.height / source.width)
        //   destination.width, destination.height);

      /**END CUSTOM CODE**/
    }

`` ''

Возьмите решение LanderBeeuwsaert (загрузив html2canvas.js, чтобы вы могли редактировать его код, как они) и замените

if (source.width/destination.width > source.height/destination.height) {

с участием

if (source.width/destination.width < source.height/destination.height) {

Это должно дать вам желаемый результат. По крайней мере, у меня это сработало.

Есть новости по этому поводу?

@LanderBeeuwsaert, большое спасибо, он сработал отлично, вы должны добавить его в мастер, это очень хороший вклад

@niklasvh Похоже, вы обновляли проект.
Я с нетерпением жду этого. Дайте мне знать, если вам как-то понадобится более точный код, чем этот.

@LanderBeeuwsaert, где я могу реализовать этот ваш взлом?

@SamuraiPetrus
Эй, да, структура проекта полностью изменена с 0.5 на 1.0.0 в связи с преобразованием в машинописный текст.
Некоторое время назад я искал, где это должно быть в 1.0.0, поэтому я мог, возможно, сделать пиар, но не нашел. Так что я все еще использую 0.5 с этим хаком.

Используйте версию 1.0.0-alpha.9 и добавьте patch-package с кодом @LanderBeeuwsaert, например этот html2canvas+1.0.0-alpha.9.patch :

diff --git a/node_modules/html2canvas/dist/html2canvas.js b/node_modules/html2canvas/dist/html2canvas.js
index 5f34081..66d1909 100644
--- a/node_modules/html2canvas/dist/html2canvas.js
+++ b/node_modules/html2canvas/dist/html2canvas.js
@@ -2443,7 +2443,22 @@ var CanvasRenderer = function () {
     }, {
         key: 'drawImage',
         value: function drawImage(image, source, destination) {
-            this.ctx.drawImage(image, source.left, source.top, source.width, source.height, destination.left, destination.top, destination.width, destination.height);
+            var newWidth = 30;
+            var newHeight = 30;
+            var newX = destination.left;
+            var newY = destination.top;
+
+            if (source.width/destination.width < source.height/destination.height) {
+                newWidth = destination.width;
+                newHeight = source.height * (destination.width / source.width);
+                newY = destination.top + (destination.height - newHeight) / 2;
+            } else {
+                newWidth = source.width * (destination.height / source.height);
+                newHeight = destination.height;
+                newX = destination.left + (destination.width - newWidth) / 2;
+            }
+
+            this.ctx.drawImage(image, source.left, source.top, source.width, source.height, newX, newY, newWidth, newHeight);
         }
     }, {
         key: 'drawShape',

Не забудьте импортировать версию, которая не минимизирована, указав полный путь:

const html2canvas = require('html2canvas/dist/html2canvas.js');

Я не могу установить альфа-сборку, и пакет исправлений у меня не работает. Есть ли способ реализовать это?

Подходящий обходной путь для моей ситуации - просто использовать фоновые изображения.

Здравствуйте, просто чтобы вы знали, что мне это нужно, и я взломал его для работы в моем проекте. Ниже я привожу код, который у меня работает. Однако это взлом, у меня нет знаний, чтобы интегрировать это в ваш проект более подходящим способом:

    key: 'drawImage',
      value: function drawImage(image, source, destination) {
        /**START CUSTOM CODE**/

          var newWidth = 30;
          var newHeight = 30;
          var newX = destination.left;
          var newY = destination.top;

          // console.log(image, source, destination);
          if (source.width/destination.width > source.height/destination.height) {
              newWidth = destination.width;
              newHeight = source.height * (destination.width / source.width);
              newY = destination.top + (destination.height - newHeight) / 2;
          } else {
              newWidth = source.width * (destination.height / source.height);
              newHeight = destination.height;
              newX = destination.left + (destination.width - newWidth) / 2;
          }
        // console.log(newWidth, newHeight);

          this.ctx.drawImage(image, source.left, source.top, source.width, source.height,
            newX, newY,
            newWidth, newHeight);
          // destination.width,
          // destination.height * (source.height / source.width)
          //   destination.width, destination.height);

        /**END CUSTOM CODE**/
      }

Куда мне нужно вставить этот код?

После небольшой игры мне удалось заставить его работать для моих целей в текущей версии.

        CanvasRenderer.prototype.renderReplacedElement = function (container, curves, image) {
        if (image && container.intrinsicWidth > 0 && container.intrinsicHeight > 0) {
            var box = contentBox(container);
            /*CUSTOM CODE*/
            var newWidth = 30;
            var newHeight = 30;
            var newX = box.left;
            var 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;
            }
            var path = calculatePaddingBoxPath(curves);
            this.path(path);
            this.ctx.save();
            this.ctx.clip();
            this.ctx.drawImage(image, 0, 0, container.intrinsicWidth, container.intrinsicHeight, newX, newY, newWidth, newHeight);
            this.ctx.restore();
        }
    };

Найдите первые несколько строк в неминифицированном файле. Спасибо @LanderBeeuwsaert за базовый код.

@canoncarlson, с удовольствием, спасибо за обновление. Мы интегрируем его и сможем обновлять в ближайшие недели из-за этого.

Мне также удалось заставить его работать, измените CanvasRenderer.prototype.renderReplacedElement в node_modules / html2canvas / dist / html2canvas.js около строки 6274, я использую версию RC 5, это в основном тот же код, что и @canoncarlson , просто для Подтвердите, что крышка Object-Fit работает с этой модификацией

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

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

Спасибо @LanderBeeuwsaert за первоначальное решение и надеюсь, что это исправление скоро появится в основной версии.

Была ли эта страница полезной?
0 / 5 - 0 рейтинги