使用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>

画布(html5)版本

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

如果是:

  1. 在html中添加canvas标记
  2. 像上面的代码一样定义了drawCircle函数

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();
}
<button onclick="drawCircle()">Dreptunghi</button>
<br />
<canvas id="myCanvas" width="578" height="200"></canvas>

更新

SVG版本

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


对于使用SVG绘图,我建议使用svg.js 等库

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});
}
<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>

最新更新