kinetic fillPattern of polygon
by Gustavo Carvalho
HTML
<script src="http://d3lp1msu2r81bx.cloudfront.net/kjs/js/lib/kinetic-v4.5.1.min.js"></script>
<button id="save">Save</button>
<br>
<br>
<p>Drag the Polygon to your desired clip</p>
<br>
<div id="container"></div>
<br>
<p>Saved results without background</p>
<img id="saved" width=300 height=300/>
CSS
body {
background-color: ivory;
padding:20px;
}
img {
border:1px solid red;
}
JavaScript
// this just generates a sample image
var canvas = document.createElement("canvas");
var ctx = canvas.getContext("2d");
var count = 0;
canvas.width = 300;
canvas.height = 300;
for (var x = 0; x < 10; x++) {
for (var y = 0; y < 10; y++) {
ctx.beginPath();
ctx.arc(x * 30 + 15, y * 30 + 15, 15, 0, Math.PI * 2, false);
ctx.fillText(count++, x * 30 + 11, y * 30 + 18);
ctx.stroke();
}
}
var img = new Image();
img.onload = function () {
draw();
}
img.src = canvas.toDataURL();
function draw() {
var stage = new Kinetic.Stage({
container: 'container',
width: 300,
height: 300
});
var layer = new Kinetic.Layer();
stage.add(layer);
var background = new Kinetic.Image({
x: 0,
y: 0,
image: img,
width: 300,
height: 300,
opacity: .25
});
layer.add(background);
var hexagon = new Kinetic.RegularPolygon({
x: 50,
y: 50,
sides: 6,
radius: 50,
fillPatternImage: img,
fillPatternRepeat: "no-repeat",
fillPatternOffset: [-50, -50],
stroke: 'black',
strokeWidth: 3,
draggable: true
});
layer.add(hexagon);
layer.draw();
hexagon.on('dragmove', function () {
var position = this.getAbsolutePosition();
var x = position.x;
var y = position.y
this.setFillPatternOffset(x, y);
layer.draw();
});
$("#save").click(function () {
background.hide();
...