【问题标题】:SVG.js - How to delete previously drawn elements in Angular?SVG.js - 如何删除以前在 Angular 中绘制的元素?
【发布时间】:2019-07-30 21:54:37
【问题描述】:

我是一名初级全栈 Web 开发人员。

我帮助使用 MEAN 堆栈、SVG.js 和套接字构建了一个用于乒乓球的游戏播放应用程序。 GitHub链接:https://github.com/ChristopherRoySchneider/pingpong

在应用程序中,“游戏施法者”负责通过网站的其他用户可以实时看到的套接字发送“游戏事件”。这些游戏事件可以包含在 SVG 矩形元素(代表乒乓球台)上绘制的 SVG 圆形元素以及其他数据位,该元素显示乒乓球最后落在得分上的位置。

观看比赛的用户可以通过下拉菜单选择他或她想观看的特定比赛的哪场比赛。然后,该应用会为所选游戏绘制桌面上所有先前的球。

当用户更改查看的游戏时,我无法弄清楚如何从桌子上删除之前绘制的乒乓球。目前,所有先前绘制的球都保留在桌面上。

当用户选择不同的游戏时,我尝试使用 SVG.js clear() 方法来清除表格。这可行,但随后会在旧表格所在的位置重新绘制表格。

这是我试图解决这个错误的分支: https://github.com/ChristopherRoySchneider/pingpong/tree/table-redraw

在 ngOnChanges 中,我有以下代码:

ngOnChanges() {
  this.draw.clear();
  this.makeTable();
  this.game = this.match.games[this.gameIndex];
  this.drawPreviousBalls(this.game);
}

这里是makeTable函数:

  makeTable() {
    this.draw = SVG('drawing').size(640, 356);
    this.table = this.draw.rect(640, 356).attr({
      'fill': '#022b6d',
      'stroke': '#fff',
      'stroke-width': 10
    });
    this.centerLine = this.draw.line([[0, 178], [640, 178]]).stroke({
      'color': '#fff',
      'width': 5
    })
    this.net = this.draw.line([[320, 0], [320, 356]]).stroke({
      'color': '#fff',
      'width': 5
    })
  }

还有我的 drawPreviousBalls 函数,它调用了一个 drawBall 函数:

  drawPreviousBalls(game: Game) {
    for (let gameEvent of game.game_events) {
      if (gameEvent.x) {
        this.drawBall(gameEvent.x, gameEvent.y);
      }
    }
  }

  drawBall(x: number, y: number) {
    this.x = x;
    this.y = y;

    if(this.draw){
      this.ball = this.draw.circle(10).attr({
        cx: this.x,
        cy: this.y,
        fill: '#fff'
      });
    }
  }

任何帮助将不胜感激!

【问题讨论】:

  • 您在每次抽奖时创建一个新的 svg 文档。所以请只是remove()旧的

标签: javascript angular svg mean-stack svg.js


【解决方案1】:

您无需不断重绘表格。这是一个静态大小,所以只需绘制一次并保留它。

我要做的是制作一个 SVG 组元素 (<g>),您可以将所有球元素保存在其中。

this.balls = this.draw.group();

然后,在你将所有球重新绘制到新位置之前,只需这样做

this.balls.clear();

即。

drawPreviousBalls(game: Game) {
  this.balls.clear();
  for (let gameEvent of game.game_events) {
    if (gameEvent.x) {
      this.drawBall(gameEvent.x, gameEvent.y);
    }
  }
}


drawBall(x: number, y: number) {
  this.x = x;
  this.y = y;

  if (this.draw) {
    this.ball = this.balls.circle(10).attr({
      cx: this.x,
      cy: this.y,
      fill: '#fff'
    });
  }
}

【讨论】:

  • 我按照您的建议运行并得到了它的工作!再次感谢,保罗。我赞成你的答案,但我太新了,无法显示。
猜你喜欢
  • 2021-03-31
  • 1970-01-01
  • 2014-12-03
  • 2019-05-04
  • 2012-02-20
  • 2020-12-13
  • 2013-05-04
  • 1970-01-01
  • 2019-10-23
相关资源
最近更新 更多