d3plus с Svelte: Uncaught TypeError: Невозможно прочитать документ свойства undefined

Цель

Я пытаюсь реализовать это…

<!doctype html>

<html>
  <head>
    <meta charset="utf-8">
    <script src="https://d3plus.org/js/d3.js"></script>
    <script src="https://d3plus.org/js/d3plus.js"></script>
    <style>
      html {
        height: 100%;
      }
      
      body {
        margin: 0;
        height: 100%;
        background: linear-gradient(to top, #ddfdff, #6DD5FA, #2980B9);
      }

      svg {
        font-family: "Helvetica", "Arial", sans-serif;
        height: 100%;
        width: 100%;
        background: transparent;
      }

      .type {
        fill: #888;
        text-anchor: middle;
      }

      .shape {
        fill: red;
        stroke: black;
      }

      .invis {
        fill: transparent;
        stroke: transparent;
      }

      .title {
        fill: #ffebeb;
      }
    </style>
  </head>
  <body>
    <svg>
      <path id="Union" fill-rule="evenodd" clip-rule="evenodd" d="M584.924 352C566.379 596.253 442.233 717.371 312.762 721.625C314.849 722.912 315.945 724.404 315.439 725.873C314.85 727.582 313.363 728.819 311.349 729.634C313.835 731.14 315.947 732.306 317.185 732.541C324.33 733.901 329.242 736.83 328.72 740.738C326.639 756.297 285.436 758.859 279.246 744.483C277.43 740.263 282.545 736.546 290.185 734.22C291.876 733.706 291.976 731.183 291.936 728.476C288.699 727.054 286.268 725.043 285.663 722.579C285.504 721.933 285.607 721.353 285.928 720.839C157.97 709.163 31.5609 584.211 2.92421 352C-23.4665 138 133.209 0 293.924 0C454.639 0 600.034 153 584.924 352Z" fill="#C80E0E"/>

      <!-- 'd3plus' uses this circle as a text mask. -->
      <!-- Honestly, I don't fully understand how this works; -->
      <!-- Changing the circle's radius yields strange effects. -->
      <circle class="shape invis" r="15px" cx="0px" cy="0px"></circle>

      <text id="circleResize" class="wrap title" x="0px" y="110px" font-size="2rem">
        Why is it so difficult to center text in a shape like this while specifying curved outer bounds?
      </text>

    </svg>

    <script>
      // Wrap text in a circle, and size the text to fit.
      d3plus.textwrap()
        .container(d3.select("#circleResize"))
        .width(620)
        .height(1000)
        .resize(true)
        .draw();
    </script>
  </body>
</html>

… В Svelte.

Эта проблема

Кажется, я не могу заставить d3plus работать со Svelte.

Сначала я попытался использовать <svelte:head> для размещения <script src="https://d3plus.org… строк. Я не помню, что произошло, когда я это пробовал, но подозреваю, что <svelte:head> работает только с CSS или другими файлами, содержимое которых не нужно анализировать Svelte. ¯_ (ツ) _ / ¯?

Во всяком случае, мой следующий подход представлен (частично) ниже. Сначала я сохранил d3.js и d3plus.js в src, а затем, как показано, импортирую символы напрямую.

Однако во втором сценарии я продолжаю получать эту консольную ошибку:

Uncaught TypeError: Cannot read property 'document' of undefined
    at d3.js:8
    at d3.js:9553
    at createCommonjsModule (index.mjs:1328)
    at index.mjs:1328
    at main.js:8

Предположительно, здесь происходит то, что источник d3 запускается до того, как приложение успевает загрузиться, и поэтому document остается неопределенным? Тем не менее, я застрял!

Вот (сломанный) код, fwiw:

<script>
  import d3 from './d3.js';
  import d3plus from './d3plus.js'

  d3plus.textwrap()
    .container(d3.select("#circleResize"))
    .resize(true)
    .draw();

</script>

<style>
  svg {
    font-family: "Helvetica", "Arial", sans-serif;
    height: 100%;
    width: 100%;
    background: transparent;
  }

  .type {
    fill: #888;
    text-anchor: middle;
  }

  .shape {
    fill: red;
    stroke: black;
  }

  .invis {
    /* Fill will be transparent in final outlay */
    fill: #10ef3394;
    stroke: transparent;
    stroke-width: .1rem;
  }

  .title {
    fill: #ffebeb;
  }
</style>

<svg>
  <path id="Union" fill-rule="evenodd" clip-rule="evenodd" d="M584.924 352C566.379 596.253 442.233 717.371 312.762 721.625C314.849 722.912 315.945 724.404 315.439 725.873C314.85 727.582 313.363 728.819 311.349 729.634C313.835 731.14 315.947 732.306 317.185 732.541C324.33 733.901 329.242 736.83 328.72 740.738C326.639 756.297 285.436 758.859 279.246 744.483C277.43 740.263 282.545 736.546 290.185 734.22C291.876 733.706 291.976 731.183 291.936 728.476C288.699 727.054 286.268 725.043 285.663 722.579C285.504 721.933 285.607 721.353 285.928 720.839C157.97 709.163 31.5609 584.211 2.92421 352C-23.4665 138 133.209 0 293.924 0C454.639 0 600.034 153 584.924 352Z" fill="#C80E0E"/>

  <circle class="shape invis" r="15px" cx="0px" cy="0px"></circle>

  <text id="circleResize" class="wrap title" x="0px" y="110px" font-size="2rem">
    Why is it so difficult to center text in a shape like this while specifying curved outer bounds?
  </text>

</svg>

Как мне заставить это работать в Svelte ??? ????


person clozach    schedule 19.07.2019    source источник
comment
Попробуйте обернуть d3plus.textwrap()... в onMount обратный вызов   -  person CD..    schedule 19.07.2019
comment
К сожалению нет. Добавление onMount не помогло. Fwiw, если я удалю d3plus.textwrap()..., но сохраню операторы import, ошибка не исчезнет.   -  person clozach    schedule 19.07.2019
comment
Фактически, вы сделали это на полпути, @CD ... Оказалось, что onMount был необходим, но только после первого импорта сценариев d3 & d3plus в обычные теги <script> в / public / index.html.   -  person clozach    schedule 20.07.2019


Ответы (1)


Рабочий код

(С ???? to @CD.. здесь, на S.O., и @primos на Discord, за их помощь!)

???? Ползунок диапазона и связанные переменные - это просто немного реактивного развлечения для тестирования перемещения текста и выноски вместе.

/public/index.html

<!doctype html>
<html>
<head>
  <meta charset='utf8'>
  <meta name='viewport' content='width=device-width'>

  <title>Svelte app</title>

  <link rel='icon' type='image/png' href='/favicon.png'>
  <link rel='stylesheet' href='/global.css'>
  <link rel='stylesheet' href='/bundle.css'>

  <script src="https://d3plus.org/js/d3.js"></script>     <!-- ???? -->
  <script src="https://d3plus.org/js/d3plus.js"></script> <!-- ???? -->

  <script defer src='/bundle.js'></script>
</head>

<body>
</body>
</html>

App.svelte

<script>
  import { onMount } from 'svelte';               // ????

  onMount(() => {                                 // ????
    d3plus.textwrap()
      .container(d3.select("#circleResize"))
      .resize(true)
      .draw();
  });

  export let name;
  let i = 0;
  const minX = 293;
  let windowWidth;
  let skyHeight;
</script>

<svelte:window bind:innerWidth={windowWidth}/>

<style>
  svg {
    font-family: "Helvetica", "Arial", sans-serif;
    height: 90%;
    width: 100%;
    background: transparent;
  }

  .type {
    fill: #888;
    text-anchor: middle;
  }

  .shape {
    fill: red;
    stroke: black;
  }

  .invis {
    fill: transparent;
    stroke: transparent;
    stroke-width: .1rem;
  }

  .title {
    fill: #ffebeb;
  }
</style>

<label>
    <input type="range" bind:value={i} max={windowWidth - (2 * minX)}>
</label>

<div>{i}</div>

<svg>
  <path id="Union" fill-rule="evenodd" clip-rule="evenodd" transform="translate({i},0)" d="M584.924 352C566.379 596.253 442.233 717.371 312.762 721.625C314.849 722.912 315.945 724.404 315.439 725.873C314.85 727.582 313.363 728.819 311.349 729.634C313.835 731.14 315.947 732.306 317.185 732.541C324.33 733.901 329.242 736.83 328.72 740.738C326.639 756.297 285.436 758.859 279.246 744.483C277.43 740.263 282.545 736.546 290.185 734.22C291.876 733.706 291.976 731.183 291.936 728.476C288.699 727.054 286.268 725.043 285.663 722.579C285.504 721.933 285.607 721.353 285.928 720.839C157.97 709.163 31.5609 584.211 2.92421 352C-23.4665 138 133.209 0 293.924 0C454.639 0 600.034 153 584.924 352Z" fill="#C80E0E"/>

  <circle class="shape invis" r="280px" cx="{minX}" cy="300px"></circle>

  <text id="circleResize" class="wrap title" x="0px" y="110px" font-size="2rem" transform="translate({i},0)">
    Why is it so difficult to center text in a shape like this while specifying curved outer bounds?
  </text>

</svg>
person clozach    schedule 20.07.2019