【问题标题】:unable to print <path> fill color SVG无法打印 <path> 填充颜色 SVG
【发布时间】:2019-02-27 06:40:46
【问题描述】:

我正在尝试打印 svg,但未应用填充颜色。有没有办法做到这一点?

const winPrint = window.open('', '', 'width=900,height=650');
let el = document.getElementsByClassName('testing')[0]
winPrint.document.write(el.innerHTML);

// winPrint.document.write(this.globalMap.nativeElement.innerHTML);
winPrint.document.close();
winPrint.focus();
winPrint.print();
winPrint.close();
html, body, svg {
  height: 100%
}

path {
  fill: orange;
  background-color: orange;
}
<!-- Learn about this code on MDN: https://developer.mozilla.org/en-US/docs/Web/SVG/Element/path -->
<div class="testing">
  <svg viewBox="0 0 100 100" xmlns="http://www.w3.org/2000/svg">
  <path d="M 10,30
           A 20,20 0,0,1 50,30
           A 20,20 0,0,1 90,30
           Q 90,60 50,90
           Q 10,60 10,30 z"/>
</svg>
</div>

【问题讨论】:

    标签: javascript css svg


    【解决方案1】:

    SVG 中缺少颜色的原因是因为您正在打开一个新窗口并且只将元素写入所述窗口而不是 CSS 样式。您还需要将 CSS 复制到新窗口。有多种方法可以做到这一点。有些比其他的更简单。

    如果您只是想复制所有样式元素,您可以执行以下操作(很多情况下这不起作用):

    const winPrint = window.open('', '', 'width=900,height=650');
    let el = document.getElementsByClassName('testing')[0];
    winPrint.document.write(Array.from(document.querySelectorAll("style")).map(x => x.outerHTML).join("") + el.innerHTML);
    winPrint.document.close();
    winPrint.focus();
    winPrint.print();
    winPrint.close();
    

    另一种选择是遍历所有元素并复制它们计算出的 CSS 值。我建议您查看Get a CSS value with JavaScript 以了解如何实际执行此操作。下面我写了一个如何克隆元素及其计算的 CSS 值的示例。我只用你的例子对此进行了测试。因此,我不能保证它在任何地方都可以使用,但从头开始可能会很好。

    function cloneElement(el) {
      const clone = el.cloneNode(true);
      copyCSS(el, clone);
    
      return clone;
    }
    
    function copyCSS(source, dest) {
      const computedStyle = window.getComputedStyle(source);
      const cssProperties = Object.keys(computedStyle);
      for (const cssProperty of cssProperties) {
        dest.style[cssProperty] = computedStyle[cssProperty];
      }
    
      for (let i = 0; i < source.children.length; i++) {
        copyCSS(source.children[i], dest.children[i]);
      }
    }
    
    function printElement(el) {
      const clone = cloneElement(el);
    
      const winPrint = window.open('', '', 'width=900,height=650');
      winPrint.document.write(clone.outerHTML);
      winPrint.document.close();
      winPrint.focus();
      winPrint.print();
      winPrint.close();
    }
    
    printElement(document.querySelector(".testing"));
    

    【讨论】:

    • 非常感谢!嗯,如果是这种情况,我不知道该功能如何与我正在使用的 ngx-chart 一起使用。我正在做同样的事情,我只是将 ngx-charts 的 innerHTML 写入打开的文档,我认为这是使用 d3。
    猜你喜欢
    • 2023-03-19
    • 1970-01-01
    • 1970-01-01
    • 2018-11-12
    • 1970-01-01
    • 2019-05-27
    • 1970-01-01
    • 1970-01-01
    • 2015-08-06
    相关资源
    最近更新 更多