2

Здравствуйте! Возникла задача - нарисовать и скачать svg, вот такой структуры

<svg id="canv" style="width: 220px; height: 220px;">       
  <g id="grid">
    <line x1="22" y1="0" x2="22" y2="220" stroke="black"></line>
    <line x1="44" y1="0" x2="44" y2="220" stroke="black"></line>
    <line x1="66" y1="0" x2="66" y2="220" stroke="black"></line>
    <line x1="88" y1="0" x2="88" y2="220" stroke="black"></line>
    <line x1="110" y1="0" x2="110" y2="220" stroke="black"></line>
    <line x1="132" y1="0" x2="132" y2="220" stroke="black"></line>
    <line x1="154" y1="0" x2="154" y2="220" stroke="black"></line>
    <line x1="176" y1="0" x2="176" y2="220" stroke="black"></line>
    <line x1="198" y1="0" x2="198" y2="220" stroke="black"></line>
    <line x1="0" y1="22" x2="220" y2="22" stroke="black"></line>
    <line x1="0" y1="44" x2="220" y2="44" stroke="black"></line>
    <line x1="0" y1="66" x2="220" y2="66" stroke="black"></line>
    <line x1="0" y1="88" x2="220" y2="88" stroke="black"></line>
    <line x1="0" y1="110" x2="220" y2="110" stroke="black"></line>
    <line x1="0" y1="132" x2="220" y2="132" stroke="black"></line>
    <line x1="0" y1="154" x2="220" y2="154" stroke="black"></line>
    <line x1="0" y1="176" x2="220" y2="176" stroke="black"></line>
    <line x1="0" y1="198" x2="220" y2="198" stroke="black"></line>
  </g>

  <line x1="165" y1="187" x2="121" y2="33" stroke="black"></line>
  <line x1="121" y1="33" x2="187" y2="55" stroke="black"></line>
  <line x1="187" y1="55" x2="99" y2="165" stroke="black"></line>
  <line x1="99" y1="165" x2="165" y2="187" stroke="black"></line>
</svg>

(есть несколько линий в группе grid, и линии вне этой группы, цвета могут быть какие угодно)

Для этого, я написал такой код:

function download()
{
  var temp = document.createElement('canvas');

  temp.style.width = canvas.width*cellSize;
  temp.style.height = canvas.height*cellSize;

  var ctx = temp.getContext('2d');

  for(var i=0; i<canv.getElementById('grid').children.length; i++)
  {
    var el = canv.getElementById('grid').children[i];
    console.log(el);

    ctx.strokeStyle = el.getAttribute('stroke');

    var x1 = el.getAttribute('x1'),
        x2 = el.getAttribute('x2'),
        y1 = el.getAttribute('y1'),
        y2 = el.getAttribute('y2');


    ctx.moveTo(x1, y1);
    ctx.lineTo(x2, y2);
    ctx.stroke();
  }

  for(var i=1; i<canv.children.length; i++)
  {
    var el = canv.children[i];
    console.log(el);
    ctx.strokeStyle = el.getAttribute('stroke');

    var x1 = el.getAttribute('x1'),
        x2 = el.getAttribute('x2'),
        y1 = el.getAttribute('y1'),
        y2 = el.getAttribute('y2');


    ctx.moveTo(x1, y1);
    ctx.lineTo(x2, y2);
    ctx.stroke();
  }

  document.body.appendChild(temp);

  var link = document.createElement('a');
  link.setAttribute('download', '');
  link.setAttribute('href', temp.toDataURL());
  link.click();
}

В итоге скачивается вот такое изображение:

введите сюда описание изображения

Ссылка на Jsfiddle (нужно нажать на картинку).

Помогите пожалуйста исправить.

3 ответа 3

3

Добрый день! Я думаю, что Вы усложнили себе задачу. Данную задачу можно решить двумя путями:

  1. Скачать картинку в формате svg. Можно посмотреть здесь: https://stackoverflow.com/questions/2483919/how-to-save-svg-canvas-to-local-filesystem Среди ответов есть решение, которое должно работать без сервера.
  2. Скачать картинку в формате png. Для этого потребуется библиотека canvg:

    var canvas = document.createElement('canvas');
    var svg = document.getElementById('canv');
    var svgWider = svg.innerHTML;
    canvg(canvas, svgWider);
    // Ваш код, который скачивает canvas как png файл.
    
2
+50

Дело в том, что по умолчанию размер канваса 150x300

удалите

temp.style.width = canvas.width*cellSize;
temp.style.height = canvas.height*cellSize;

и после

var ctx = temp.getContext('2d');

добавьте

ctx.canvas.height = canvas.height * cellSize;
ctx.canvas.width = canvas.width * cellSize;

jsFiddle

-2
  1. А кто будет указывать атрибуты width и height у канваса и у svg?
  2. Для svg лучше указать viewBox вместо width и height.
  3. А чем картинка в формате svg не устраивает?
2
  • Если у вас возник новый вопрос, пожалуйста, задайте его при помощи кнопки «Задать вопрос». Если нужно указать контекст, дайте ссылку на этот вопрос. - Из очереди проверок
    – iluxa1810
    14 ноя 2016 в 21:01
  • @iluxa1810, вообще-то это ответ.
    – Qwertiy
    14 ноя 2016 в 21:39

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.