ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • dom element를 이미지로 변환할때 문제점 (CSS가 적용이 안된다.)
    카테고리 없음 2024. 10. 15. 23:35

    dom을 이미지로 변환할 때 convas 테그는 dom Element와 독립적으로 존재히기 때문에 css를 가져오지 못한다. 

    css파일에 있는 css style을 가져오지 못하기 때문에 css를 className으로 적용하는것이 아닌 인라인으로 style을 적용해야 한다. 

     

    처음부터 인라인으로 작성할 수도 있지만 너무 비효율 적이기 때문에 dom API를 이용해보도록 한다. 

     

      const computedStyle = window.getComputedStyle(element);

     

    getComputeStyle()은 이미 브라우저에 생성된 Style을 가져오는 dom API이다. 

     

     

    Array.from(computedStyle).forEach((key) => {
      element.style[key] = computedStyle.getPropertyValue(key);
    });

    그 이후 dom.style에 window에서 가져온 css style을 주입한다. 

     

    Array.from(element.children).forEach((child: Element) => applyInlineStyles(child as HTMLElement));

    dom의 자식 dom까지 style이 적용되도록 한다. 

     

     

    문제점

     

    이미지로 변환하는 속도가 너무 느리고 화면이 멈추는 이수가 발생하였다. 

     

    이유는 dom을 하나하나 순회하면서 style을 주입하기 때문에 성능이슈가 발생한다. 

     

    해결법

    문자열로 변환 후 한번에 주입한다. 

    let inlineStyles = '';
    
      Array.from(computedStyle).forEach(key => {
        inlineStyles += `${key}: ${computedStyle.getPropertyValue(key)}; `;
      });
      
        element.setAttribute('style', inlineStyles);

     

    이렇게 하면 dom을 하나하나 순회하지 않고도 한번에 주입해 주기 때문에 성능이 개선되고 html2canvas대비 10배, domtoimage대비 1.7배 성능이 향상되었다. 

Designed by Tistory.