Html2canvas: Div. Preenchido com imagem definido para ajuste ao objeto: capa;

Criado em 27 fev. 2017  ·  13Comentários  ·  Fonte: niklasvh/html2canvas

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

A imagem 1 é a divisão que desejo capturar, após a captura da imagem mude seu tamanho * Foto 2.

Alguém pode consertar isso?

Feature

Comentários muito úteis

Olá, só para avisar que eu precisava disso e hackeado para funcionar no meu projeto. Eu forneço o código que funciona para mim abaixo. No entanto, este é um hack, não tenho o conhecimento para integrar isso ao seu projeto de uma maneira mais adequada:

`` `
chave: 'drawImage',
valor: função drawImage (imagem, origem, 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 comentários

Olá, só para avisar que eu precisava disso e hackeado para funcionar no meu projeto. Eu forneço o código que funciona para mim abaixo. No entanto, este é um hack, não tenho o conhecimento para integrar isso ao seu projeto de uma maneira mais adequada:

`` `
chave: 'drawImage',
valor: função drawImage (imagem, origem, 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**/
    }

`` `

Pegue a solução da LanderBeeuwsaert (baixando html2canvas.js para que você possa editar seu código como eles fizeram) e substitua

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

com

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

Isso deve gerar os resultados desejados. Funcionou para mim, pelo menos.

alguma atualização disso?

@LanderBeeuwsaert muito obrigado funcionou perfeitamente, você deveria adicioná-lo ao master é uma contribuição muito boa

@niklasvh Parece que você está atualizando o projeto.
Eu ficaria ansioso para obter este aqui. Informe-me se você precisa de um código mais exato do que este de alguma forma.

@LanderBeeuwsaert onde

@SamuraiPetrus
Ei, sim, a estrutura do projeto foi completamente alterada de 0,5 para 1.0.0 devido à conversão para texto digitado.
Eu pesquisei um tempo atrás onde deveria ir no 1.0.0 então eu poderia fazer um PR, mas não encontrei. Então, ainda estou usando 0,5 com este hack.

Use a versão 1.0.0-alpha.9 e adicione um patch-package com o 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',

Não se esqueça de importar a versão que não está minimizada, fornecendo o caminho completo:

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

Não consigo instalar o alpha build e o patch-package não está funcionando para mim. Não existe uma maneira de implementar isso?

Uma solução alternativa adequada para minha situação é usar apenas imagens de fundo.

Olá, só para avisar que eu precisava disso e hackeado para funcionar no meu projeto. Eu forneço o código que funciona para mim abaixo. No entanto, este é um hack, não tenho o conhecimento para integrar isso ao seu projeto de uma maneira mais adequada:

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

Onde devo colar este código?

Depois de mexer um pouco, consegui fazer com que funcionasse para meus propósitos na versão atual.

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

Procure as primeiras linhas no arquivo não reduzido. Agradecimentos a @LanderBeeuwsaert pelo código base.

@canoncarlson é um prazer, obrigado pela atualização. Vamos integrá-lo e poderemos atualizá-lo nas próximas semanas por causa disso.

Também consegui fazê-lo funcionar, altere CanvasRenderer.prototype.renderReplacedElement em node_modules / html2canvas / dist / html2canvas.js em torno da linha 6274, estou usando a versão RC 5, é basicamente o mesmo código de @canoncarlson , apenas para confirme se a tampa de ajuste do objeto está funcionando com esta modificação

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

Obrigado a @LanderBeeuwsaert pela solução inicial, e espero que essa correção

Esta página foi útil?
0 / 5 - 0 avaliações