2016-01-12 53 views
-1

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

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> 
+0

您的标签应该只是'button',而不是'button1'。这里预期的结果是什么? 'dragStartLocation'的值来自哪里? – Pabs123

+0

我在互联网上找到的功能。我必须使用svg来制作一个grafic编辑器。添加形状如圆形,椭圆形,矩形,添加和编辑文本,选择/删除/移动/更改已绘制的形状。 –

+1

我会说它不起作用,因为你所有的代码都被注释掉了。 –

回答

1

画布(HTML5)版本

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

如果是这样的:

  1. 添加canvas标签在HTML。
  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>

+0

好的,谢谢。但如果我想使用SVG?我需要它在svg –

+0

我刚刚更新了我的答案。 –

+0

o.Pup是你寻找的答案吗? –