使用LiterallyCanvas在Javascript中将图像保存为Base64字符串

问题描述 投票:0回答:1

我从开源LiterallyCanvas中获取了一个演示,您可以从桌面上获取图像并在其上绘图,然后单击“保存”将其作为base64字符串。我已经修改了一些代码,它目前允许我绘制箭头,省略号和自由绘图。但由于代码将图像设置为背景图像,因此当我点击保存时,base64字符串仅保存我制作的图形,而不是我选择的图像。

谁能告诉我哪里出错了?我认为这是因为我只是设置背景,但我不知道如何保存它。我基本上希望程序加载图像,在其上绘制一个箭头,然后用箭头保存图像。作为Base64字符串。

这是当前的代码:

<html><head>
<title>Canvas</title>
<link href="../_assets/literallycanvas.css" rel="stylesheet">
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, user-scalable=no">
</head>
<body>
<div class="fs-container">
  <div class="literally toolbar-hidden toolbar-hidden toolbar-hidden toolbar-hidden toolbar-hidden">

  <div class="lc-drawing" style="background-color: transparent;">
  <canvas width="1158" height="600" style="width: 1158px; height: 600;"></canvas>   
  <canvas width="1158" height="600" style="background-color: transparent; width: 1158px; height: 600;"></canvas>

  </div>
  </div>

  <div class="toolset">
    <span class="toolLabel">Actions:</span>
    <input type='file' id='getval' name="background-image" onchange="readURL(event)" /><br/><br/>
    <a href="javascript:void(0);" class="tool" id="open-image">Save</a>     
    <a href="javascript:void(0);" class="tool" id="clear-lc">Cancel</a>
  </div>
  <div class="toolset">
    <span class="toolLabel">Tools:</span>
    <a href="javascript:void(0);" class="tool current" id="tool-pencil">Pencil</a>
    <a href="javascript:void(0);" class="tool" id="tool-arrow">Arrow</a>        
    <a href="javascript:void(0);" class="tool" id="tool-ellipse">Ellipse</a>
  </div>
  <div class="toolset" id="tools-colors">
    <span class="toolLabel">Colors:</span>
    <a href="javascript:void(0);" class="tool" id="colorTool-red">Red</a>
  </div>
<script src="../_js_libs/jquery-3.0.0.js"></script>
<script src="../_js_libs/literallycanvas-core.js"></script>

<script type="text/javascript">
  var lc = null;
  var tools;
  var strokeWidths;
  var colors;

  var setCurrentByName;
  var findByName;

  function readURL(event){
     var getImagePath = URL.createObjectURL(event.target.files[0]);
     $('.lc-drawing').css('background-image', 'url(' + getImagePath + ')'),
     $('.lc-drawing').css('background-repeat', 'no-repeat');
    }

  // the only LC-specific thing we have to do
  var containerOne = document.getElementsByClassName('literally')[0];

  var showLC = function() {
    lc = LC.init(containerOne, {
      snapshot: JSON.parse(localStorage.getItem('drawing')),
      defaultStrokeWidth: 10,
      strokeWidths: [10, 20, 50],
      secondaryColor: 'transparent'
    });
    window.demoLC = lc;

    var save = function() {
      localStorage.setItem('drawing', JSON.stringify(lc.getSnapshot()));
    }

    lc.on('drawingChange', save);
    lc.on('pan', save);
    lc.on('zoom', save);

    $("#open-image").click(function() {
      window.open(lc.getImage({
        scale: 1, margin: {top: 10, right: 10, bottom: 10, left: 10}
      }).toDataURL());
    });         

    $("#change-size").click(function() {
      lc.setImageSize(null, 200);
    });

    $("#reset-size").click(function() {
      lc.setImageSize(null, null);
    });

    $("#clear-lc").click(function() {
      lc.clear();
    });

    tools = [
      {
        name: 'pencil',
        el: document.getElementById('tool-pencil'),
        tool: new LC.tools.Pencil(lc)
      },{
        name: 'arrow',
        el: document.getElementById('tool-arrow'),
        tool: function() {
          arrow = new LC.tools.Line(lc);
          arrow.hasEndArrow = true;
          return arrow;
        }()
      },{
        name: 'ellipse',
        el: document.getElementById('tool-ellipse'),
        tool: new LC.tools.Ellipse(lc)
      },{
        name: 'tool-rectangle',
        el: document.getElementById('tool-rectangle'),
        tool: new LC.tools.Rectangle(lc)
      }
    ];

    colors = [
      {
        name: 'black',
        el: document.getElementById('colorTool-black'),
        color: '#000000'
      },{
        name: 'red',
        el: document.getElementById('colorTool-red'),
        color: '#ff0000'
      }
    ];

    setCurrentByName = function(ary, val) {
      ary.forEach(function(i) {
        $(i.el).toggleClass('current', (i.name == val));
      });
    };

    findByName = function(ary, val) {
      var vals;
      vals = ary.filter(function(v){
        return v.name == val;
      });
      if ( vals.length == 0 )
        return null;
      else
        return vals[0];
    };

    // Wire tools
    tools.forEach(function(t) {
      $(t.el).click(function() {
        var sw;

        lc.setTool(t.tool);
        setCurrentByName(tools, t.name);
        setCurrentByName(strokeWidths, t.tool.strokeWidth);
        $('#tools-sizes').toggleClass('disabled', (t.name == 'text'));
      });
    });
    setCurrentByName(tools, tools[0].name);

    // Wire Stroke Widths

    strokeWidths.forEach(function(sw) {
      $(sw.el).click(function() {
        lc.trigger('setStrokeWidth', sw.size);
        setCurrentByName(strokeWidths, sw.name);
      })
    })
    setCurrentByName(strokeWidths, strokeWidths[0].name);

    // Wire Colors
    colors.forEach(function(clr) {
      $(clr.el).click(function() {
        lc.setColor('primary', clr.color)
        setCurrentByName(red, red);
      })
    })
    setCurrentByName(red, red);

  };



  $(document).ready(function() {

    $(document).bind('touchmove', function(e) {
      if (e.target === document.documentElement) {
        return e.preventDefault();
      }
    });
    showLC();
  });

  $('#hide-lc').click(function() {
    if (lc) {
      lc.teardown();
      lc = null;
    }
  });

  $('#show-lc').click(function() {
    if (!lc) { showLC(); }
  });
</script>

javascript html5 canvas base64
1个回答
0
投票

使用Literallycanvas实例中的getImage()函数获取绘制的画布,然后可以调用toDataURL()来获取base64字符串。

在他们的文档中阅读更多内容:http://literallycanvas.com/examples/export.html

无论视口中显示的是什么,您都可以使用getImage()导出完整的图形或图形的任何子集。这些示例将绘图导出为新窗口中的PNG。转换为PNG由内置的canvas函数toDataURL()处理。要了解有关可用图像格式的更多信息,请参阅Mozilla的canvas元素参考。

我个人使用文件保护程序下载图像而不是自己使用base64:

lc.getImage().toBlob(
  blob => {
    saveAs(blob, fileName);
  },
  "image/jpeg",
  1
);
© www.soinside.com 2019 - 2024. All rights reserved.