How to convert SVG text element with @font-face to canvas using html2canvas.js?

隐身守侯 提交于 2019-12-11 02:13:16

问题


I'm trying to use html2canvas.js (https://html2canvas.hertzen.com/) to take screenshots with JavaScript. However, I have a problem when the page contains SVG text elements.

As you can see on the screenshots below, the text element is duplicated (and only one of the copies keep the right font family).

Original body

Canvas copy

Here is my code

HTML

<svg width="600" height="200" style="background-color:lightblue;">
  <text transform="translate(100, 100)" style="font-size:60px; font-family: 'Oswald'">Hello world</text>
</svg>

<br/>
<button id="createCanvasButton">Create canvas !</button>

CSS

@import url(//fonts.googleapis.com/css?family=Oswald);

JS

$('#createCanvasButton').on('click', function() {
  html2canvas(document.body).then(function(canvas) {
    document.body.appendChild(canvas);
  });
});

jsFiddle
https://jsfiddle.net/AndreLovichi/571t86u4/

Note
I've been looking for a similar issue, and I've found this one: SVG Text attribute is doubling - HTML2CANVAS.
However, the patch on NodeParser.prototype.getChildren didn't work for me: the remaining text element had the wrong font family.

Thanks a lot!


回答1:


note

I updated on your code. Please add font base64 in svg. Maybe I answered too late :),This is the first answer I use stackoverflow The font need change dataURI insert in SVG

JS

const request = new XMLHttpRequest();
request.open("get", './xxx/demo.woff');
request.responseType = "blob";
request.onloadend = () => { let fontDemoDataURI = reader.result }

html

    <svg>
         <style>
          @font-face {
          font-family: 'Oswald';
              src: url(data:application/font-woff;base64,d09GRgABAAAAOtXY........ED==);
          </style>
    </svg>

LINKS

enter image description here

https://jsfiddle.net/571t86u4/93/



来源:https://stackoverflow.com/questions/40469672/how-to-convert-svg-text-element-with-font-face-to-canvas-using-html2canvas-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!