【问题标题】:KineticJS - use of drawFunc in Shape overwrite context settings when using GroupKineticJS - 使用 Group 时在 Shape 覆盖上下文设置中使用 drawFunc
【发布时间】:2012-11-05 03:52:23
【问题描述】:

我对使用 HTML5 Canvas 和 KineticJS 很陌生,所以如果这是我的明显错误,请原谅我。

我的问题是我正在使用由形状组成的组。 Shapes 使用 drawFunc 来实现绘图魔法。都是好东西。但是 - 我注意到在我的 Shape 调用中所做的设置似乎覆盖了“全局”上下文设置。我创建的fiddle 最好地展示了这一点,它向标准的“KineticJS 拖放组”demo 添加了一些十字(形状)。

  // ----------------------------------------------------------[ my bit starts ]
        var tmp_x = i * 30 + 100
        var tmp_y = i * 30 + 40
        var shape = new Kinetic.Shape({

            drawFunc: function(context) {

                context.moveTo(tmp_x-10, tmp_y);
                context.lineTo(tmp_x + 10, tmp_y);
                context.moveTo(tmp_x, tmp_y - 10);
                context.lineTo(tmp_x, tmp_y + 10);

                this.fill(context);
                this.stroke(context);
            } ,
            fill: "#0FD2FF",
            stroke: "orange"
        });
        group.add(shape);
        // ----------------------------------------------------------[ my bit ends ]

        var box = new Kinetic.Rect({
            x: i * 30 + 210,
            y: i * 18 + 40,
            width: 100,
            height: 50,
            name: colors[i],
            fill: colors[i],
            stroke: 'black',
            strokeWidth: 4
        });

        group.add(box);

您会注意到,在形状标记中对彩色框的设置进行描边和填充设置 - 除了在最后一个十字(形状)之后创建的最后一个。

感觉像是某种后期评估的事情,因为只有在渲染组时才完成。

有人可以告诉我我做错了什么吗?

【问题讨论】:

标签: html5-canvas kineticjs shape


【解决方案1】:

上下文全局的,因此当您对其应用设置时,它们将持续存在于使用上下文进行绘制的每个形状中。

您需要在您的drawFunc 中调用context.beginPath()context.closePath(),围绕您对context 的其他调用,以表明这是一个与其他形状分开的新形状。

所以现在,你的形状代码应该是这样的:

var shape = new Kinetic.Shape({
    drawFunc: function(context) {
        context.beginPath();
        context.moveTo(tmp_x-10, tmp_y);
        context.lineTo(tmp_x + 10, tmp_y);
        context.moveTo(tmp_x, tmp_y - 10);
        context.lineTo(tmp_x, tmp_y + 10);
        context.closePath();

        this.fill(context);
        this.stroke(context);
    },
    fill: "#0FD2FF",
    stroke: "orange"
});

这将防止您的上下文设置泄漏到其他形状。

【讨论】:

  • 谢谢。我还在这里找到了答案html5canvastutorials.com/kineticjs/… 对我有用的位是由“maiconio”发布的,涉及在 drawFunc 内部使用“this.variableName”以及 shapeInstance.variableName outside 的实例化的设置形状。
猜你喜欢
  • 2013-11-14
  • 2014-04-04
  • 2022-01-12
  • 1970-01-01
  • 2019-05-25
  • 1970-01-01
  • 2023-01-28
  • 2011-08-27
  • 1970-01-01
相关资源
最近更新 更多