Meteor - 使用订阅数据自动更新画布?

7za*_*rk7 11 meteor

我可能会遗漏一些东西,但似乎Meteor的"魔力"围绕着将数据绑定到DOM元素,并通过把手更新文本和HTML片段:http: //docs.meteor.com/#reactivity

这很好,但是,当试图编写一个在<canvas>元素中显示实时数据的流星应用程序时,我无法弄清楚当实时数据发生变化时更新我的​​画布的"流星方式",因为画布是通过JS填充的代码如:

var g = canvas.getContext('2d')
g.fillRect(x, y, w, h)
Run Code Online (Sandbox Code Playgroud)

而不是HTML模板中的数据支持文本.

我试图使用来自Meteor.Collection的数据在画布上绘图.

我唯一的想法是在由车把变量填充的脚本标签中将画布绘制JS代码嵌入到HTML模板中,但这似乎是错误的,因为meteor的事件和数据绑定代码已经是客户端JS.

有没有办法监听实时数据更改,这会触发通过JS而不是HTML元素/文本在画布上绘图?

如果我能以某种方式澄清问题,请告诉我

更新: Tom的回答让我注意到Meteor.deps,它看起来允许在被动上下文中执行任意代码:http://docs.meteor.com/#on_invalidate

如果有效,我会尝试这个并在这里更新.

Tom*_*man 7

也许您的问题的答案是使用Collection.observe(http://docs.meteor.com/#observe)并在各种回调中触发相关的重绘代码.

例如,类似于:

Rectangles.observe({
  added: function(rect) {
    var g = canvas.getContext('2d');
    g.fillRect(rect.x, rect.y, rect.w, rect.h);
  },
  // etc
})
Run Code Online (Sandbox Code Playgroud)


7za*_*rk7 5

这有效:

var Shapes = new Meteor.Collection('shapes')

if (Meteor.is_client) {
  // Function that redraws the entire canvas from shapes in Meteor.Collection
  function drawShapes() {
    var shapes = Shapes.find({})
    shapes.forEach(function(shape) {
      // draw each on canvas
    })
  }

  var startUpdateListener = function() {
    // Function called each time 'Shapes' is updated.
    var redrawCanvas = function() {
      var context = new Meteor.deps.Context()
      context.on_invalidate(redrawCanvas) // Ensures this is recalled for each update
      context.run(function() {
        drawShapes()
      })
    }
    redrawCanvas()
  }

  Meteor.startup(function() {
    startUpdateListener()
  })
}
Run Code Online (Sandbox Code Playgroud)