Search code examples
javascriptanimationcanvaskineticjs

Line patterns with Kineticjs


Ok, so I'm trying to draw a line which takes a patterned image as its stroke instead of a solid color. I know it's possible to fill a Rect or other shape with a pattern, but that's not what I'm trying to do, I'm working strictly with lines. So my question is. Is it possible to pass an image into a pattern and use that pattern as a line's stroke? Or should I just create a Rect and fill each one with my pattern?

var line = new Kinetic.Line({
points: [0, 0, 0, 500],
stroke: /Here's where I want the pattern to go\,
strokeWidth: strokeWidth

});


Solution

  • Html Canvas allows a pattern to be used to draw a stroke.

    KineticJS does not allow a patterned stroke.

    But you can use a Kinetic.Shape and grab a real html canvas context like this:

    Demo: http://jsfiddle.net/m1erickson/hTP5J/

    enter image description here

    var triangle = new Kinetic.Shape({
      sceneFunc: function(context) {
        var ctx=this.getContext()._context;
        ctx.save();
        ctx.beginPath();
        ctx.moveTo(100, 50);
        ctx.lineTo(320, 80);
        ctx.quadraticCurveTo(200, 100, 160, 170);
        ctx.closePath();
        var pattern=context.createPattern(img, 'repeat');
        ctx.strokeStyle=pattern;
        ctx.lineWidth=20;
        ctx.stroke();
        ctx.restore();
      },
    });