使用SVG的图形编辑器

时间:2016-01-12 00:25:57

标签: javascript html css svg

我有一个学校项目,必须使用SVG构建和图形编辑器(类似于绘画)。我发现JavaScript中的函数代码用于绘制圆,线等,但是当我尝试将它们添加到按钮onclick函数时,它不起作用。

function drawCircle(position) {
//     var radius = Math.sqrt(Math.pow((dragStartLocation.x - position.x), 2) + Math.pow((dragStartLocation.y - position.y), 2));
//     context.beginPath();
//     context.arc(dragStartLocation.x, dragStartLocation.y, radius, 0, 2 * Math.PI, false);
}

这是HTML

<button onclick="drawCircle()" class="button">Dreptunghi</button>

1 个答案:

答案 0 :(得分:1)

画布(html5)版本

您正在尝试使用html5-canvas但不是svg

如果是这样的话:

  1. 在html中添加canvas标记。
  2. 定义drawCircle函数,如上面的代码。
  3. &#13;
    &#13;
    function drawCircle() {
      var canvas = document.getElementById('myCanvas');
      var context = canvas.getContext('2d');
      var centerX = canvas.width / 2;
      var centerY = canvas.height / 2;
      var radius = 70;
    
      context.beginPath();
      context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
      context.fillStyle = 'green';
      context.fill();
      context.lineWidth = 5;
      context.strokeStyle = '#003300';
      context.stroke();
    }
    &#13;
    <button onclick="drawCircle()">Dreptunghi</button>
    <br />
    <canvas id="myCanvas" width="578" height="200"></canvas>
    &#13;
    &#13;
    &#13;

    <强>更新

    SVG版本

    &#13;
    &#13;
    function drawCircle() {
      document.getElementById('svg').innerHTML = '<circle cx="100" cy="100" r="70" stroke="black" stroke-width="5" fill="green" />';
    }
    &#13;
    <button onclick="drawCircle()">Dreptunghi</button>
    <br /><br />
    <svg height="200" width="578" id="svg"></svg>
    &#13;
    &#13;
    &#13;

    对于使用SVG进行绘制,我建议使用svg.js

    等库

    &#13;
    &#13;
    function drawCircle() {
      var draw = SVG('draw').size(578, 200);
      var circle = draw.circle(70).attr({fill:'green',stroke:'#003300', 'stroke-width': 5, cx:50, cy:50});
    }
    &#13;
    <script src="https://cdnjs.cloudflare.com/ajax/libs/svg.js/2.2.5/svg.js"></script>
    <button onclick="drawCircle()">Dreptunghi</button>
    <br /><br />
    <div id="draw"></div>
    &#13;
    &#13;
    &#13;