Skip to content Skip to sidebar Skip to footer

Kineticjs Fill With Pattern

I previously asked how to fill a shape with a checkerboard effect using html5 canvas. HTML5 Canvas Fill with two colours and i was given a jsfiddle to show how to do this. http://j

Solution 1:

Yes, you can use similar code to create a kinetic polygon filled with your pattern

enter image description here

Fill a canvas with your pattern just as you do in native html canvas:

// use a temp canvas to create a patternvar pattern = document.createElement('canvas');
    pattern.width = 40;
    pattern.height = 40;
    var pctx = pattern.getContext('2d');
    pctx.fillStyle = "rgb(188, 222, 178)";
    pctx.fillRect(0,0,20,20);
    pctx.fillRect(20,20,20,20);

Now use that temp canvas to create an image object

var img=newImage();
    img.onload=function(){
            // img now contains your pattern
    }
    img.src=pattern.toDataURL();

Finally, use fillPatternImage to fill a kinetic polygon with your pattern:

// make a kinetic polygon filled with the patternvar polyPattern = new Kinetic.Polygon({
          points: [30,30, 300,30, 400,60, 300,150, 200,50, 100,450],
          fillPatternImage: img,
          stroke: 'black',
          strokeWidth: 3
        });

Here is code and a Fiddle: http://jsfiddle.net/m1erickson/uW8xz/

<!DOCTYPE html><html><head><metacharset="utf-8"><title>Prototype</title><scripttype="text/javascript"src="http://code.jquery.com/jquery.min.js"></script><scriptsrc="http://d3lp1msu2r81bx.cloudfront.net/kjs/js/lib/kinetic-v4.7.0.min.js"></script><style>#container{
  border:solid 1px#ccc;
  margin-top: 10px;
  width:400px;
  height:400px;
}
</style><script>
$(function(){

    var stage = newKinetic.Stage({
        container: 'container',
        width: 450,
        height: 450
    });
    var layer = newKinetic.Layer();
    stage.add(layer);

    // use a temp canvas to create a patternvar pattern = document.createElement('canvas');
    pattern.width = 40;
    pattern.height = 40;
    var pctx = pattern.getContext('2d');
    pctx.fillStyle = "rgb(188, 222, 178)";
    pctx.fillRect(0,0,20,20);
    pctx.fillRect(20,20,20,20);

    // make an image from the temp canvas patternvar img=newImage();
    img.onload=function(){

        // make a kinetic polygon filled with the patternvar polyPattern = newKinetic.Polygon({
          points: [30,30, 300,30, 400,60, 300,150, 200,50, 100,450],
          fillPatternImage: img,
          stroke: 'black',
          strokeWidth: 3
        });
        // add the shape to the layer and layer.draw()
        layer.add(polyPattern);
        layer.draw();

    }
    img.src=pattern.toDataURL();


}); // end $(function(){});</script></head><body><divid="container"></div></body></html>

Post a Comment for "Kineticjs Fill With Pattern"