import Konva from 'konva';
const loadScript = (src) => {
  return new Promise((resolve, reject) => {
    const script = document.createElement('script');
    script.src = src;
    script.onload = resolve;
    script.onerror = reject;
    document.head.appendChild(script);
  });
};
const loadCSS = (href) => {
  const link = document.createElement('link');
  link.rel = 'stylesheet';
  link.href = href;
  document.head.appendChild(link);
};
const editorContainer = document.createElement('div');
editorContainer.id = 'editor-container';
editorContainer.style.height = '80px';
editorContainer.innerHTML = `
  That is <u>some</u> <span style="color: red"> styled text</span> on
  <strong>canvas</strong>!
  <h2>What do you think about it?</h2>
`;
document.body.appendChild(editorContainer);
Promise.all([
  loadScript('https://cdn.quilljs.com/1.3.6/quill.js'),
  loadScript('https://html2canvas.hertzen.com/dist/html2canvas.min.js'),
]).then(() => {
  loadCSS('https://cdn.quilljs.com/1.3.6/quill.snow.css');
  const quill = new Quill('#editor-container', {
    modules: {
      toolbar: [
        [{ header: [1, 2, false] }],
        ['bold', 'italic', 'underline'],
        ['image', 'code-block'],
      ],
    },
    placeholder: 'Compose an epic...',
    theme: 'snow',
  });
  const stage = new Konva.Stage({
    container: 'container',
    width: window.innerWidth,
    height: 200,
  });
  const layer = new Konva.Layer();
  stage.add(layer);
  const shape = new Konva.Image({
    x: 10,
    y: 10,
    draggable: true,
    stroke: 'red',
    scaleX: 1 / window.devicePixelRatio,
    scaleY: 1 / window.devicePixelRatio,
  });
  layer.add(shape);
  function renderText() {
    
    html2canvas(document.querySelector('.ql-editor'), {
      backgroundColor: 'rgba(0,0,0,0)',
    }).then((canvas) => {
      
      shape.image(canvas);
    });
  }
  
  let timeout = null;
  function requestTextUpdate() {
    if (timeout) {
      return;
    }
    timeout = setTimeout(function () {
      timeout = null;
      renderText();
    }, 500);
  }
  
  quill.on('text-change', requestTextUpdate);
  
  renderText();
});