Html2canvas: Imagen llena incluso div establecido en object-fit: cover;

Creado en 27 feb. 2017  ·  13Comentarios  ·  Fuente: niklasvh/html2canvas

http://imgur.com/3Zl6oRA | Imagen 1
http://imgur.com/Wr006qF | Imagen 2

La imagen 1 es el div que quiero capturar, después de que capturó la imagen, cambie su tamaño * Imagen 2.

¿Alguien podría arreglar esto?

Feature

Comentario más útil

Hola, solo para hacerte saber que necesitaba esto y lo pirateé para que funcione en mi proyecto. Proporciono el código que me funciona a continuación. Sin embargo, esto es un truco, no tengo el conocimiento para integrar esto en su proyecto de una manera más adecuada:

''
clave: 'drawImage',
valor: función drawImage (imagen, origen, destino) {
/ INICIAR CÓDIGO PERSONALIZADO /

        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**/
    }

''

Todos 13 comentarios

Hola, solo para hacerte saber que necesitaba esto y lo pirateé para que funcione en mi proyecto. Proporciono el código que me funciona a continuación. Sin embargo, esto es un truco, no tengo el conocimiento para integrar esto en su proyecto de una manera más adecuada:

''
clave: 'drawImage',
valor: función drawImage (imagen, origen, destino) {
/ INICIAR CÓDIGO PERSONALIZADO /

        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**/
    }

''

Tome la solución de LanderBeeuwsaert (descargando html2canvas.js para que pueda editar su código como lo hicieron) y reemplace

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

con

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

Eso debería darte los resultados deseados. Funcionó para mí, al menos.

¿Algún avance en esto?

@LanderBeeuwsaert muchas gracias funciono perfecto , deberian agregarlo a la master es un muy buen aporte

@niklasvh Parece que ha estado actualizando el proyecto.
Estaría ansioso por obtener este. Avíseme si necesita un código más exacto que este de alguna manera.

@LanderBeeuwsaert, ¿ dónde se supone que

@SamuraiPetrus
Oye, sí, la estructura del proyecto ha cambiado por completo de 0.5 a 1.0.0 debido a la conversión a mecanografiado.
Busqué hace un tiempo dónde debería ir en 1.0.0, así que posiblemente podría hacer un PR, pero no lo encontré. Así que sigo usando 0.5 con este truco.

Use la versión 1.0.0-alpha.9 y agregue un patch-package con el código @LanderBeeuwsaert como este 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',

No olvide importar la versión que no está minimizada proporcionando la ruta completa:

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

No puedo instalar la compilación alfa y el paquete de parche no me funciona. ¿No hay una manera de implementar esto?

La solución alternativa adecuada para mi situación es usar imágenes de fondo.

Hola, solo para hacerte saber que necesitaba esto y lo pirateé para que funcione en mi proyecto. Proporciono el código que me funciona a continuación. Sin embargo, esto es un truco, no tengo el conocimiento para integrar esto en su proyecto de una manera más adecuada:

    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**/
      }

¿Dónde debo pegar este código?

Después de un poco de manipulación, logré que funcionara para mis propósitos en la versión actual.

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

Busque las primeras líneas en el archivo no minificado. Gracias a @LanderBeeuwsaert por el código base.

@canoncarlson es un placer, gracias por la actualización. Lo integraremos y podremos actualizar en las próximas semanas debido a esto.

Me las arreglé para que funcione también, cambie CanvasRenderer.prototype.renderReplacedElement en node_modules / html2canvas / dist / html2canvas.js alrededor de la línea 6274, estoy usando la versión RC 5, es básicamente el mismo código que @canoncarlson , solo para Confirme que la cubierta de ajuste a objetos funciona con esta modificació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();

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

Gracias a @LanderBeeuwsaert por la solución inicial, y espero que esta solución termine pronto en la versión principal.

¿Fue útil esta página
0 / 5 - 0 calificaciones