I am quite new to using HTML5 Canvas and KineticJS so please forgive me if this is an obvious error on my part.
My issue is that I am using a Group made up of Shapes. The Shapes use a drawFunc which does the drawing magic. All good stuff. However - I notice that the settings made in my Shape call seem to override the "global" context settings. This is best shown by a fiddle I created that adds some crosses (Shapes) to the standard "KineticJS drag and drop a group" 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);
You will notice that the stroke and fill settings made in the Shape stamp on the settings for the coloured boxes - apart from the last one which is created AFTER the last cross (Shape).
It feels like some sort of late evaluation thing because things are only done when the Group gets rendered.
Could someone give me a clue as to what I am doing wrong?
Context is global, so when you apply settings to it, they will persist for every shape that uses the context to draw.
You need to call context.beginPath()
and context.closePath()
in your drawFunc, around your other calls to context
, to indicate that this is a new and separate shape from the others.
So now, your code for shape would be like this:
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"
});
This will prevent your context settings from leaking to other shapes.