【问题标题】:Can I override a draw function in SVG.js?我可以覆盖 SVG.js 中的绘图函数吗?
【发布时间】:2017-12-05 05:08:15
【问题描述】:

例如,如果我在使用 SVG.js 绘制圆时,是否可以覆盖 .circle() 或 .ellipse() 函数,以便绘制像图像一样的半径线?

我想要类似 SVG.Ellipse = SVG.extend(SVG.Ellipse, {...})

(假设当前由其他人编写的项目中的实现过于复杂和抽象,无法尝试扩展内容,因此我只想尝试覆盖它)。

【问题讨论】:

  • 你能提供一个小提琴吗?为什么不直接创建一个新的 svg?
  • @AlanSutherland 我希望...我正在尝试将其添加到现有项目中。谁编写了实现所有 SVG 的代码,谁就把它抽象出来了。所以在这一点上,经过几天尝试修改已经存在的内容,我决定尝试覆盖 SVG.Ellipse
  • 我们可以看看你的代码吗?
  • @itcropper 不,你不能——绘制原生 SVG 元素的代码是 native 浏览器代码

标签: javascript svg svg.js


【解决方案1】:

您似乎对 svg.js 项目的节拍感到不知所措;)

玩笑不谈:做自己想做的事其实并不复杂。您可以选择以下几种路径:

  • line() 方法添加到SVG.Circle
  • 发明一个新对象SVG.LinedCircle
  • 用新的构造方法扩展SVG.Parent()

line() 方法添加到SVG.Circle

SVG.extend(SVG.Circle, {
    line: function() {
        var r = this.radius()
          , cx = this.cx() 
          , cy = this.cy()

        this.parent().line(cx, cy, cx + r)
    }
}

用法:

draw.circle(20).line()

发明一个新对象SVG.LinedCircle

SVG.LinedCircle = SVG.invent({
    create: function() { SVG.Circle.call(this) },
    inherit: SVG.Circle,
    line: function() {
        var r = this.radius()
          , cx = this.cx() 
          , cy = this.cy()

        this.parent().line(cx, cy, cx + r)
    },
    construct: {
      linedCircle: function(size) {
          return this.put(new SVG.LinedCircle().size(size).line())
      }
    }
})

用法

draw.linedCircle()

用新的构造方法扩展SVG.Parent()

SVG.extend(SVG.Parent, {
    linedCircle: function(size) {
        var g = this.group()
          , c = g.circle(size)
          , r = c.radius()
          , cx = c.cx() 
          , cy = c.cy()

        g.line(cx, cy, cx + r
        return this.put(g)
    }
})

用法:

draw.linedCircle(50)

这次我将圆和线包裹成一个组。因此,您在调用它时会返回一个组。海事组织那是最好的解决方案。 您可以通过多种方式实现您想要的。当您阅读 svg.js 源代码时,您将很快了解事情是如何工作的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-05
    相关资源
    最近更新 更多