Reputation: 325
I want to make this dynamic pattern in fabric js interactive with the user for example if he presses Ctrl and selects the object with the mouse I want the pattern properties to change, so I can move and scale the image inside pattern. http://fabricjs.com/dynamic-patterns any ideas thanks
Upvotes: 1
Views: 1146
Reputation: 2417
This should do it (hold down Ctrl key and select the object with the mouse):
(function() {
var canvas = this.__canvas = new fabric.Canvas('c');
fabric.Object.prototype.transparentCorners = false;
var polygon;
var padding = 0;
fabric.Image.fromURL('http://fabricjs.com/assets/pug.jpg', function(img) {
img.scaleToWidth(100);
var patternSourceCanvas = new fabric.StaticCanvas();
patternSourceCanvas.add(img);
var pattern = new fabric.Pattern({
source: function() {
patternSourceCanvas.setDimensions({
width: img.getWidth() + padding,
height: img.getHeight() + padding
});
return patternSourceCanvas.getElement();
},
repeat: 'repeat'
});
polygon = new fabric.Polygon([
{x: 185, y: 0},
{x: 250, y: 100},
{x: 385, y: 170},
{x: 0, y: 245} ], {
left: 0,
top: 70,
angle: -15,
fill: pattern,
objectCaching: false
});
canvas.add(polygon);
controlKeyDown = false;
document.getElementById('c').focus();
//setInterval only used in case you go "Full page" in the code snippet demo tool
setInterval(function() {
document.getElementById('c').focus();
}, 1500);
document.addEventListener('keydown', function(event) {
var keyCode = ('which' in event) ? event.which : event.keyCode;
controlKeyDown = (keyCode == 17);
});
document.addEventListener('keyup', function(evn) {
controlKeyDown = false;
});
var mouseX;
var mouseY;
canvas.on('mouse:move', function(evn) {
mouseX = evn.e.offsetX;
mouseY = evn.e.offsetY;
});
canvas.on('object:selected', function(e) {
if (controlKeyDown) {
var obj = e.target;
//pattern position change
polygon.points[0].x += mouseX;
polygon.points[0].y += mouseY;
polygon.points[1].x += 80;
polygon.points[1].y -= 80;
polygon.points[2].x += 60;
polygon.points[2].y += 60;
polygon.points[3].x += 80;
polygon.points[3].y -= 80;
}
});
});
})();
canvas {
outline: none;
}
<script src="//cdnjs.cloudflare.com/ajax/libs/fabric.js/1.4.0/fabric.min.js"></script>
<canvas tabindex="1" id="c" width="440" height="440"></canvas>
Let me know if you have any further questions.
Upvotes: 2