本文介绍了JavaScript和SVG:createElement()出错的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我所拥有的是一个没有HTML的SVG文档,并且在< defs> ...< / defs> -section我有我的JavaScript。在其中,有一个创建椭圆弧的功能(虽然我只将它用于圆弧,在本例中,仅用于圆)和另一个使用前一种方法创建圆的功能。这可能不是现在最优雅的方式,但我稍后会考虑......

So what I have is an SVG-Document with no HTML what-so-ever and in the <defs>...</defs>-section I have my JavaScript. In it, there is a function to create elliptical arcs (although I will only use it for circular arcs and, in this example, solely for a circle) and another function to create a circle using the former method. That might not be the most elegant way for now, but I'll look into that later...

然而,现在尝试通过<$创建一个新元素c $ c> createElement()我在Chrome和Firefox中都遇到了SVG-DOM-Object不包含该方法的错误。

Now however, while trying to create a new Element via createElement() I get in both Chrome and Firefox the error that the SVG-DOM-Object does not contain that method.

这是代码:

var SVGObj = document.getElementById('canvas');
function Point(x, y) {
  this.x = x;
  this.y = y;
}

var ids =  new Array();
ids.nextID = nextID;
function nextID() {
  this.push(this.length);
  return this.length;
}

function hypot(pointA, pointB) {
  return Math.sqrt((pointA.x - pointB.x) * (pointA.x - pointB.x) + (pointA.y - pointB.y) * (pointA.y - pointB.y))
}

function arc(center, from, to, fill) {
  if (hypot(center, from) == hypot(center, to))
    radius = hypot(center, from);
  else
    return false;
  var arch = SVGObj.createElement('path');
  arch.setAttribute('d', 'M ' + center.x + ',' + center.y + //Mittelpunkt
                        ' A ' + radius + ' ' + radius + //Radius
                        ' ' +  (Math.atan((from.y - center.y) / (from.x - center.x)) * 180 / Math.PI) + ' 1 0 ' + //from
                        to.x + ',' + to.y); //to
  arch.setAttribute('id', ids.nextID());
  if(fill) arch.setAttribute('style', 'fill: black');
  SVGObj.appendChild(arch);
  return true;
}

function fullCircle(center, radius, fill) {
  return arc(center, new Point(center.x + radius, center.y + radius), new Point(center.x + radius, center.y + radius), fill);
}


if(!fullCircle(new Point(100, 50), 40, true)) alert("Fehler");


推荐答案

您需要使用文件.createElementNS('http://www.w3.org/2000/svg','path')在SVG命名空间中创建路径元素。

You need to use document.createElementNS('http://www.w3.org/2000/svg', 'path') to create a path element in the SVG namespace.

这篇关于JavaScript和SVG:createElement()出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-30 23:58