I've created a fabric custom class "VectorPlaceholder" that is basically a group that contains a Rectangle and a Vector:
// Fabric.js custom vector EPS object
fabric.VectorPlaceholder = fabric.util.createClass(fabric.Group, {
async: true,
type: 'vector-placeholder',
lockUniScalingWithSkew: false,
noScaleCache: true,
initialize: function (options) {
boundsRectangle = new fabric.Rect({
strokeDashArray: [10,10],
originX: 'center',
originY: 'center',
stroke: '#000000',
strokeWidth: 1,
width: options.width || 300,
height: options.height || 300,
fill: 'rgba(0, 0, 0, 0)',
});
this.setControlsVisibility({
ml: false,
mb: false,
mr: false,
mt: false,
});
this.originX = 'center',
this.originY = 'center',
this.callSuper('initialize', [boundsRectangle], options);
},
setVector: function (vector) {
//We remove any EPS that was in that position
var EPSGroup = this;
EPSGroup.forEachObject(function (object) {
if (object && object.type != "rect") {
EPSGroup.remove(object);
}
});
var scale = 1;
var xOffset = EPSGroup.getScaledWidth() / 2;
var yOffset = EPSGroup.getScaledHeight() / 2;
if (vector.height > vector.width) {
scale = EPSGroup.getScaledHeight() / vector.height;
xOffset = xOffset - (EPSGroup.getScaledWidth() - vector.width * scale) / 2
}
else {
scale = EPSGroup.getScaledWidth() / vector.width;
yOffset = yOffset - (EPSGroup.getScaledHeight() - vector.height * scale) / 2
}
vector.left = EPSGroup.left - xOffset;
vector.top = EPSGroup.top - yOffset;
vector.set('scaleY', scale);
vector.set('scaleX', scale);
var angle = 0;
if (EPSGroup.get('angle')) {
angle = EPSGroup.get('angle');
vector.setAngle(angle);
}
EPSGroup.addWithUpdate(vector);
EPSGroup.setCoords();
},
});
The idea of this class is to have a placeholder where users can upload SVGs.
This is done by calling to fabric.loadSVGFromString and then passing the result to the function in my custom class (setVector)
fabric.loadSVGFromString(svgString, function(objects, options) {
// Group the SVG objects to make a single element
var a = fabric.util.groupSVGElements(objects, options);
var EPSGroup = new fabric.VectorPlaceholder({});
EPSGroup.setVector(a);
This works perfectly when I create my custom object and don't rotate it. As you can see the group controls are aligned with the dashed rectangle.
The problem is when I create an empty VectorPlaceholder and I rotate it manually. After the manual rotation, when setVector is called this is what happens:
I can't understand why the group controls ignore the rotation, what I'm doing wrong? How can I make the group controls render aligned with the rotated rectangle?
You need to set the angle after you make setVector method
http://jsfiddle.net/2segrwx0/1/
// Fabric.js custom vector EPS object
fabric.VectorPlaceholder = fabric.util.createClass(fabric.Group, {
async: true,
type: 'vector-placeholder',
lockUniScalingWithSkew: false,
noScaleCache: true,
initialize: function (options) {
boundsRectangle = new fabric.Rect({
strokeDashArray: [10,10],
originX: 'center',
originY: 'center',
stroke: '#000000',
strokeWidth: 1,
width: options.width || 300,
height: options.height || 300,
fill: 'rgba(0, 0, 0, 0)',
});
this.setControlsVisibility({
ml: false,
mb: false,
mr: false,
mt: false,
});
this.originX = 'center',
this.originY = 'center',
this.callSuper('initialize', [boundsRectangle], options);
},
setVector: function (vector) {
//We remove any EPS that was in that position
var EPSGroup = this;
EPSGroup.forEachObject(function (object) {
if (object && object.type != "rect") {
EPSGroup.remove(object);
}
});
var scale = 1;
var xOffset = EPSGroup.getScaledWidth() / 2;
var yOffset = EPSGroup.getScaledHeight() / 2;
if (vector.height > vector.width) {
scale = EPSGroup.getScaledHeight() / vector.height;
xOffset = xOffset - (EPSGroup.getScaledWidth() - vector.width * scale) / 2
}
else {
scale = EPSGroup.getScaledWidth() / vector.width;
yOffset = yOffset - (EPSGroup.getScaledHeight() - vector.height * scale) / 2
}
vector.left = EPSGroup.left - xOffset;
vector.top = EPSGroup.top - yOffset;
vector.set('scaleY', scale);
vector.set('scaleX', scale);
/*var angle = 0;
if (EPSGroup.get('angle')) {
angle = EPSGroup.get('angle');
vector.setAngle(angle);
} */
EPSGroup.addWithUpdate(vector);
EPSGroup.setCoords();
},
});
canvas = new fabric.Canvas('c', {
});
fabric.loadSVGFromString('<svg height="210" width="500"><polygon points="100,10 40,198 190,78 10,78 160,198" style="fill:lime;stroke:purple;stroke-width:5;fill-rule:nonzero;" /></svg>', function(objects, options) {
// Group the SVG objects to make a single element
var a = fabric.util.groupSVGElements(objects, options);
var EPSGroup = new fabric.VectorPlaceholder({});
EPSGroup.left=200;
EPSGroup.top=200;
EPSGroup.setVector(a);
EPSGroup.angle=45;
canvas.add(EPSGroup);
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/2.4.5/fabric.js"></script>
<canvas id="c" width=500 height=300 ></canvas>
Related
I am new to Fabric and I have created a Rectangular shape and clipTo function for image and now i want to restrict the image in shape area. Top and left is working fine but right and bottom is not smooth. please help
https://jsfiddle.net/mg73n0eq/154/#&togetherjs=Qh6LnTRHFq
let canvas = new fabric.Canvas(
"ast",
{
width: 400,
height: 400,
selection: true,
id: "ast",
//selectionBorderColor: "green",
backgroundColor: "#ffffff",
preserveObjectStacking: true,
uniScaleTransform: true,
//cornerSize: 40,
lockScalingFlip: true,
controlsAboveOverlay: true,
subTargetCheck: true,
hoverCursor: "pointer",
stateful: true,
},
null,
"anonymous"
);
var Rect = new fabric.Rect({
width: 250,
height: 250,
fixed: true,
fill: "#000",
scaleX: 1,
scaleY: 1,
top:0,
left:0,
maskname: "rect",
absolutePositioned: true,
stroke: "1",
lockScalingFlip: true,
lockUniScaling: true,
minScaleLimit: 0.1,
});
canvas.add(Rect);
function rectMask(canvas) {
//Rect.viewportCenter();
let pugImg = new Image();
pugImg.crossOrigin = "anonymous";
pugImg.src ="https://posterapplab.com/api/images/photos/ZaJprCvDjVA.png";
//console.log(size.zoom);
pugImg.onload = function (img) {
let pug = new fabric.Image(pugImg, {
crossOrigin: "anonymous",
scaleX:0.3,
scaleY:0.3,
top: 20,
left: 10,
maskname: "rect",
clipPath: Rect,
clipTo: function (ctx) {
clipMyObject(this, ctx);
},
});
pug.crossOrigin = "anonymous";
pug.backgroundVpt = false;
pug.setControlsVisibility({
mt: false,
mb: false,
});
canvas.add(pug);
canvas.renderAll();
};
}
function clipMyObject(thisObj, ctx) {
if (thisObj.clipPath) {
ctx.save();
if (thisObj.clipPath.fixed) {
var retina = thisObj.canvas.getRetinaScaling();
ctx.setTransform(retina, 0, 0, retina, 0, 0);
// to handle zoom
ctx.transform.apply(ctx, thisObj.canvas.viewportTransform);
thisObj.clipPath.transform(ctx);
}
thisObj.clipPath._render(ctx);
ctx.restore();
ctx.clip();
var x = -thisObj.width / 2,
y = -thisObj.height / 2,
elementToDraw;
if (
thisObj.isMoving === false &&
thisObj.resizeFilter &&
thisObj._needsResize()
) {
thisObj._lastScaleX = thisObj.scaleX;
thisObj._lastScaleY = thisObj.scaleY;
thisObj.applyResizeFilters();
}
elementToDraw = thisObj._element;
elementToDraw &&
ctx.drawImage(
elementToDraw,
0,
0,
thisObj.width,
thisObj.height,
x,
y,
thisObj.width,
thisObj.height
);
thisObj._stroke(ctx);
thisObj._renderStroke(ctx);
}
}
rectMask(canvas);
canvas.on("object:moving", (e) => {
if (
e.target &&
e.target.type === "image" &&
e.target.maskname
) {
//obj.canvas.lastScaleY = obj.scaleY;
//obj.canvas.lastScaleX = obj.scaleX;
let bound = Rect.getBoundingRect();
let selectedBound = e.target.getBoundingRect();
//selectedObject.set("left", 0);
//console.log(bound.width);
// console.log(bound.height);
if (e.target.left > Rect.left) {
e.target.set("left", Rect.left);
}
if (e.target.top > Rect.top) {
e.target.set("top", Rect.top);
}
var right = Rect.left + Rect.getBoundingRect().width / 2;
var bottom = Rect.top + Rect.getBoundingRect().height / 2;
if (right > e.target.left + e.target.width / 2) {
//Solution one
e.target.set("left", Rect.left - Rect.width);
}
if (bottom > e.target.top + e.target.height / 2) {
e.target.set("top", Rect.top - Rect.height / 2);
}
// console.log(selectedObject);
/*if (selectedBound.left + selectedBound.width < bin.width) {
console.log("hjfhsafdhagsdf");
selectedObject.set("left", bin.left - bin.width / 2);
}*/
}
});
I am new to Fabric and I have created a Rectangular shape and clipTo function for image and now i want to restrict the image in shape area. Top and left is working fine but right and bottom is not smooth. please help
I have been using Konva for drawing, I would like the arrow to "snap" to the other groups or shapes when the tip of the arrow intersects them and the user lets up on the mouse. If the arrow does not interset one then it should automatically delete its self.
Then when the groups or shapes are moved I would like the tips of the arrow to move with it.
I found an example of something similar but I'm not sure how I can combine them to get what I want.
I will post my current code below.
Example link
Click here
Code
var width = height = 170;
var stage = new Konva.Stage({
container: 'container',
width: width,
height: height
});
var layer = new Konva.Layer();
var isDrawArrow;
var Startpos;
var Endpos;
var arrow = new Konva.Arrow({
points: [],
pointerLength: 10,
pointerWidth: 10,
fill: 'black',
stroke: 'black',
strokeWidth: 4
});
var circle = new Konva.Circle({
x: stage.getWidth() / 2,
y: stage.getHeight() / 2,
radius: 20,
fill: 'green'
});
var circleA = new Konva.Circle({
x: stage.getWidth() / 5,
y: stage.getHeight() / 5,
radius: 30,
fill: 'red',
draggable: true
});
circle.on('mouseover', function() {
document.body.style.cursor = 'pointer';
layer.draw()
});
circle.on('mouseout', function() {
document.body.style.cursor = 'default';
layer.draw()
});
circle.on('mousedown touchstart', function() {
isDrawArrow = true;
circleA.on('dragmove', adjustPoint);
Startpos = stage.getPointerPosition();
});
stage.addEventListener('mouseup touchend', function() {
isDrawArrow = false;
});
stage.addEventListener('mousemove touchmove', function() {
if (!isDrawArrow) return;
Endpos = stage.getPointerPosition()
var p = [Startpos.x, Startpos.y, Endpos.x, Endpos.y];
arrow.setPoints(p);
layer.add(arrow);
layer.batchDraw();
});
circle.on('mouseup', function() {
this.setFill('green');
layer.batchDraw();
});
function adjustPoint(e) {
var p = [circle.getX(), circle.getY(), circleA.getX(), circleA.getY()];
arrow.setPoints(p);
layer.draw();
stage.draw();
}
function haveIntersection(r1, r2) {
return !(
r2.x > r1.x + r1.width ||
r2.x + r2.width < r1.x ||
r2.y > r1.y + r1.height ||
r2.y + r2.height < r1.y
);
}
layer.add(circle);
layer.add(circleA);
stage.add(layer);
adjustPoint();
<script src="https://cdnjs.cloudflare.com/ajax/libs/konva/2.3.0/konva.js"></script>
<div id="container"></div>
To do the snap you needed a function to determine distance between 2 points.
Easily done with a pythagorean calculation, (if you need help with that read about it here).
On the mouse move when you detect that the distance between the end of the arrow and your point (on this case the center or the red cirle) is less than what you want you can "snap it" that is what you do on your function adjustPoint that was all good.
On the mouse up you also need to check the distance and if is too far just hide the arrow
Working Code below:
var width = height = 170;
var stage = new Konva.Stage({
container: 'container',
width: width,
height: height
});
var layer = new Konva.Layer();
var isDrawArrow, Startpos, Endpos;
var snapDistance = 20;
function distance(p, c) {
var dx = p.x - c.getX();
var dy = p.y - c.getY();
return Math.sqrt(dx * dx + dy * dy);
}
var arrow = new Konva.Arrow({
points: [],
pointerLength: 10,
pointerWidth: 10,
fill: 'black',
stroke: 'black',
strokeWidth: 4
});
var circle = new Konva.Circle({
x: stage.getWidth() - 25,
y: stage.getHeight() - 25,
radius: 20,
fill: 'green'
});
var circleA = new Konva.Circle({
x: stage.getWidth() / 5,
y: stage.getHeight() / 5,
radius: 25,
fill: 'red',
draggable: true
});
circle.on('mousedown touchstart', function() {
isDrawArrow = true;
circleA.on('dragmove', adjustPoint);
Startpos = stage.getPointerPosition();
});
stage.addEventListener('mouseup touchend', function() {
isDrawArrow = false;
if (distance(Endpos, circleA) > snapDistance) {
arrow.hide();
layer.batchDraw();
}
});
stage.addEventListener('mousemove touchmove', function() {
if (!isDrawArrow) return;
Endpos = stage.getPointerPosition()
var p = [Startpos.x, Startpos.y, Endpos.x, Endpos.y];
arrow.setPoints(p);
arrow.show();
layer.add(arrow);
layer.batchDraw();
if (distance(Endpos, circleA) <= snapDistance) {
adjustPoint();
isDrawArrow = false
}
});
function adjustPoint(e) {
var p = [circle.getX(), circle.getY(), circleA.getX(), circleA.getY()];
arrow.setPoints(p);
layer.draw();
stage.draw();
}
layer.add(circle);
layer.add(circleA);
stage.add(layer);
canvas {
border: 1px solid #eaeaea !IMPORTANT;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/konva/2.3.0/konva.js"></script>
<div id="container"></div>
WARNING: turn the volume down before you run the snippet!
I want to be able to click on the stage to add a 'module' shape. But I have found that a click on the 'module' shape itself creates another, meaning that the stage.click listener is being fired when it should not be.
How can I have a stage.click listener that does not fire incorrectly when I click on a shape ?
var width = window.innerWidth;
var height = window.innerHeight;
var rectButtonClicked = false;
var stage = new Konva.Stage({
container: 'container',
width: width,
height: height
});
var layer = new Konva.Layer();
var group = new Konva.Group({
draggable: true
});
stage.on('contentClick', function() {
createModule();
});
function createModule() {
var mouseX = stage.getPointerPosition().x;
var mouseY = stage.getPointerPosition().y;
var rect = new Konva.Rect({ //module rect
x: mouseX,
y: mouseY,
width: 100,
height: 50,
cornerRadius: 5,
fill: '#BEDBDD',
stroke: '#807C7B',
strokeWidth: 2,
draggable: true
});
group.add(rect);
var buttonRect = new Konva.Rect({ //button
x: mouseX+80,
y: mouseY+20,
width: 10,
height: 10,
cornerRadius: 1,
fill: 'blue',
stroke: '#807C7B',
strokeWidth: 1,
});
group.add(buttonRect)
var text = new Konva.Text({ //text on module
x: mouseX + 20,
y: mouseY + 20,
//fontFamily: 'Calibri',
fontSize: 16,
text: 'OSC',
fill: 'black'
});
group.add(text);
var randomFreq = getRandomInt();
var osc = new Tone.Oscillator(randomFreq, "sawtooth");
layer.add(group);
stage.add(layer);
buttonRect.on('click', function() {
rectButtonClicked = !rectButtonClicked;
if(rectButtonClicked){
osc.toMaster().start();
this.setFill('red');
} else {
osc.stop();
this.setFill('blue');
}
});
}
function getRandomInt() {
min = Math.ceil(100);
max = Math.floor(1000);
return Math.floor(Math.random() * (max - min)) + min;
}
var width = window.innerWidth;
var height = window.innerHeight;
//var drag = false;
var rectButtonClicked = false;
var stage = new Konva.Stage({
container: 'container',
width: width,
height: height
});
var layer = new Konva.Layer();
var group = new Konva.Group({
draggable: true
});
stage.on('contentClick', function() {
createModule();
});
function createModule() {
var mouseX = stage.getPointerPosition().x;
var mouseY = stage.getPointerPosition().y;
var rect = new Konva.Rect({ //module rect
x: mouseX,
y: mouseY,
width: 100,
height: 50,
cornerRadius: 5,
fill: '#BEDBDD',
stroke: '#807C7B',
strokeWidth: 2,
draggable: true
});
group.add(rect);
var buttonRect = new Konva.Rect({ //button
x: mouseX+80,
y: mouseY+20,
width: 10,
height: 10,
cornerRadius: 1,
fill: 'blue',
stroke: '#807C7B',
strokeWidth: 1,
});
group.add(buttonRect)
var text = new Konva.Text({ //text on module
x: mouseX + 20,
y: mouseY + 20,
//fontFamily: 'Calibri',
fontSize: 16,
text: 'OSC',
fill: 'black'
});
group.add(text);
var randomFreq = getRandomInt();
var osc = new Tone.Oscillator(randomFreq, "sawtooth");
layer.add(group);
stage.add(layer);
buttonRect.on('click', function() {
rectButtonClicked = !rectButtonClicked;
if(rectButtonClicked){
osc.toMaster().start();
this.setFill('red');
} else {
osc.stop();
this.setFill('blue');
}
});
}
function getRandomInt() {
min = Math.ceil(100);
max = Math.floor(1000);
return Math.floor(Math.random() * (max - min)) + min;
}
<script src="https://tonejs.github.io/build/Tone.min.js"></script>
<script src="https://cdn.rawgit.com/konvajs/konva/1.7.6/konva.min.js"></script>
<div id="container"></div>
The stage.contentClick() listener is a special case to be used when you want the stage to listen to events on the stage content. However, the cancelBubble() function does not stop events bubbling from say a click on a shape to the stage.contentClick() listener.
To get the effect that you want, which is to give the impression that a click on the stage has happened, you need to add a rect that fills the stage and listen for events on that rect instead of the stage.
Below is a working example. The red background I added deliberately so you know there is something else above the stage. To remove this take out the fill color on the clickRect.
I also fixed up your buttons so that the contents are correctly grouped and drag together. You were almost correct but you needed the group to be created within in the createModule() function. You can see that I also made the group elements dragabble = false to complete the process.
I added a couple of console writes to show when the events fire.
[Also I got quite a shock when I switched on the tone for tone].
var width = window.innerWidth;
var height = window.innerHeight;
//var drag = false;
var rectButtonClicked = false;
var stage = new Konva.Stage({
container: 'container',
width: width,
height: height
});
var layer = new Konva.Layer();
stage.add(layer);
var clickRect = new Konva.Rect({
x:0,
y:0,
width: width,
height: height,
fill: 'red',
stroke: '#807C7B',
strokeWidth: 2,
listening: 'true'
})
layer.add(clickRect);
clickRect.on('click', function() {
console.log('Stage click');
createModule();
});
function createModule() {
var group = new Konva.Group({ // move group create into createModule
draggable: true // we will make the elements not draggable - we drag the group
});
var mouseX = stage.getPointerPosition().x;
var mouseY = stage.getPointerPosition().y;
var rect = new Konva.Rect({ //module rect
x: mouseX,
y: mouseY,
width: 100,
height: 50,
cornerRadius: 5,
fill: '#BEDBDD',
stroke: '#807C7B',
strokeWidth: 2,
draggable: false // make the element not draggable - we drag the group
});
group.add(rect);
rect.on('click', function(evt){
console.log('Clicked on button');
})
var buttonRect = new Konva.Rect({ //button
x: mouseX+80,
y: mouseY+20,
width: 10,
height: 10,
cornerRadius: 1,
fill: 'blue',
stroke: '#807C7B',
strokeWidth: 1,
listening: true,
draggable: false // make the element not draggable - we drag the group
});
group.add(buttonRect)
var text = new Konva.Text({ //text on module
x: mouseX + 20,
y: mouseY + 20,
//fontFamily: 'Calibri',
fontSize: 16,
text: 'OSC',
fill: 'black',
draggable: false // make the element not draggable - we drag the group
});
group.add(text);
var randomFreq = getRandomInt();
var osc = new Tone.Oscillator(randomFreq, "sawtooth");
layer.add(group);
stage.add(layer);
buttonRect.on('click', function(evt) {
rectButtonClicked = !rectButtonClicked;
if(rectButtonClicked){
osc.toMaster().start();
this.setFill('red');
} else {
osc.stop();
this.setFill('blue');
}
});
}
function getRandomInt() {
min = Math.ceil(100);
max = Math.floor(1000);
return Math.floor(Math.random() * (max - min)) + min;
}
stage.draw(); // draw so we can see click rect.
<script src="https://tonejs.github.io/build/Tone.min.js"></script>
<script src="https://cdn.rawgit.com/konvajs/konva/1.7.6/konva.min.js"></script>
<div id="container" style="background-color: gold;"></div>
I have designed a ruler using fabric.js and when the user mouses over the specific part of the ruler I want to print to the screen the X-coordinate of the ruler (i.e. not the screen coordinate). Right now the ruler canvas starts at position 37 and ends at 726 relative to the ruler, but the ruler goes from 1 to 4600 (it will always start at 1 but the length of the ruler can change). How to transform the mouse coordinates to accurately reflect it's position on the ruler? Here is the code:
var canvas = new fabric.Canvas('canvas');
line_length = input_len;
adjusted_length = (line_length / 666) * 100;
canvas.add(new fabric.Line([0, 0, adjusted_length, 0], {
left: 30,
top: 0,
stroke: '#d89300',
strokeWidth: 3
}));
$('#canvas_container').css('overflow-x', 'scroll');
$('#canvas_container').css('overflow-y', 'hidden');
drawRuler();
function drawRuler() {
$("#ruler[data-items]").val(line_length / 200);
$("#ruler[data-items]").each(function () {
var ruler = $(this).empty(),
len = Number($("#ruler[data-items]").val()) || 0,
item = $(document.createElement("li")),
i;
ruler.append(item.clone().text(1));
for (i = 1; i < len; i++) {
ruler.append(item.clone().text(i * 200));
}
ruler.append(item.clone().text(i * 200));
});
}
canvas.add(new fabric.Text('X-cord', {
fontStyle: 'italic',
fontFamily: 'Hoefler Text',
fontSize: 12,
left: 0,
top: 0,
hasControls: false,
selectable: false
}));
canvas.on('mouse:move', function (options) {
getMouse(options);
});
function getMouse(options) {
canvas.getObjects('text')[0].text =
"X-coords: " + options.e.clientX ; //+ " Y: " + options.e.clientY;
canvas.renderAll();
}
Use the getPointer merthod on canvas Instance.
In your case it should be canvas.getPointer(options.e)which returns an object with x and y properties which represent pointer coordinates relative to canvas.
I need help only having the anchors for rotating. Right now there is five anchors and I don't know how to get rid of all of them except the rotate one. I would also only like the anchors to show when the user hovers over the image
Here is my code
<html>
<head>
<style>
body {
margin: 0px;
padding: 0px;
}
</style>
</head>
<body>
<body onmousedown="return false;">
<div id="container"></div>
<script src="http://d3lp1msu2r81bx.cloudfront.net/kjs/js/lib/kinetic-v4.7.4.min.js">
</script>
<script>
function update(activeAnchor) {
var group = activeAnchor.getParent();
var topLeft = group.get('.topLeft')[0];
var topRight = group.get('.topRight')[0];
var bottomRight = group.get('.bottomRight')[0];
var bottomLeft = group.get('.bottomLeft')[0];
var rotateAnchor = group.get('.rotateAnchor')[0];
var image = group.get('Image')[0];
var anchorX = activeAnchor.getX();
var anchorY = activeAnchor.getY();
var imageWidth = image.getWidth();
var imageHeight = image.getHeight();
var offsetX = Math.abs((topLeft.getX() + bottomRight.getX() + 10) / 2);
var offsetY = Math.abs((topLeft.getY() + bottomRight.getY() + 10) / 2);
// update anchor positions
switch (activeAnchor.getName()) {
case 'rotateAnchor':
group.setOffset(offsetX, offsetY);
break;
case 'topLeft':
topRight.setY(anchorY);
bottomLeft.setX(anchorX);
break;
case 'topRight':
topLeft.setY(anchorY);
bottomRight.setX(anchorX);
break;
case 'bottomRight':
topRight.setX(anchorX);
bottomLeft.setY(anchorY);
break;
case 'bottomLeft':
topLeft.setX(anchorX);
bottomRight.setY(anchorY);
break;
}
rotateAnchor.setX(topRight.getX() + 5);
rotateAnchor.setY(topRight.getY() + 20);
image.setPosition((topLeft.getPosition().x + 20), (topLeft.getPosition().y + 20));
var width = topRight.getX() - topLeft.getX() - 30;
var height = bottomLeft.getY() - topLeft.getY() - 30;
if (width && height) {
image.setSize(width, height);
}
}
function addAnchor(group, x, y, name, dragBound) {
var stage = group.getStage();
var layer = group.getLayer();
var anchor = new Kinetic.Circle({
x: x,
y: y,
stroke: '#666',
fill: '#ddd',
strokeWidth: 2,
radius: 8,
name: name,
draggable: true,
dragOnTop: false
});
if (dragBound == 'rotate') {
anchor.setAttrs({
dragBoundFunc: function (pos) {
return getRotatingAnchorBounds(pos, group);
}
});
}
anchor.on('dragmove', function() {
update(this);
layer.draw();
});
anchor.on('mousedown touchstart', function() {
group.setDraggable(false);
this.moveToTop();
});
anchor.on('dragend', function() {
group.setDraggable(true);
layer.draw();
});
// add hover styling
anchor.on('mouseover', function() {
var layer = this.getLayer();
document.body.style.cursor = 'pointer';
this.setStrokeWidth(4);
layer.draw();
});
anchor.on('mouseout', function() {
var layer = this.getLayer();
document.body.style.cursor = 'default';
this.setStrokeWidth(2);
layer.draw();
});
group.add(anchor);
}
function loadImages(sources, callback) {
var images = {};
var loadedImages = 0;
var numImages = 0;
for(var src in sources) {
numImages++;
}
for(var src in sources) {
images[src] = new Image();
images[src].onload = function() {
if(++loadedImages >= numImages) {
callback(images);
}
};
images[src].src = sources[src];
}
}
function getRotatingAnchorBounds(pos, group) {
var topLeft = group.get('.topLeft')[0];
var bottomRight = group.get('.bottomRight')[0];
var topRight = group.get('.topRight')[0];
var absCenterX = Math.abs((topLeft.getAbsolutePosition().x + 5 + bottomRight.getAbsolutePosition().x + 5) / 2);
var absCenterY = Math.abs((topLeft.getAbsolutePosition().y + 5 + bottomRight.getAbsolutePosition().y + 5) / 2);
var relCenterX = Math.abs((topLeft.getX() + bottomRight.getX()) / 2);
var relCenterY = Math.abs((topLeft.getY() + bottomRight.getY()) / 2);
var radius = distance(relCenterX, relCenterY, topRight.getX() + 5, topRight.getY() + 20);
var scale = radius / distance(pos.x, pos.y, absCenterX, absCenterY);
var realRotation = Math.round(degrees(angle(relCenterX, relCenterY, topRight.getX() + 5, topRight.getY() + 20)));
var rotation = Math.round(degrees(angle(absCenterX, absCenterY, pos.x, pos.y)));
rotation -= realRotation;
group.setRotationDeg(rotation);
return {
y: Math.round((pos.y - absCenterY) * scale + absCenterY),
x: Math.round((pos.x - absCenterX) * scale + absCenterX)
};
}
function radians(degrees) { return degrees * (Math.PI / 180); }
function degrees(radians) { return radians * (180 / Math.PI); }
// Calculate the angle between two points.
function angle(cx, cy, px, py) {
var x = cx - px;
var y = cy - py;
return Math.atan2(-y, -x);
}
// Calculate the distance between two points.
function distance(p1x, p1y, p2x, p2y) {
return Math.sqrt(Math.pow((p2x - p1x), 2) + Math.pow((p2y - p1y), 2));
}
function initStage(images) {
var stage = new Kinetic.Stage({
container: 'container',
width: 578,
height: 400
});
var darthVaderGroup = new Kinetic.Group({
x: 270,
y: 100,
draggable: true
});
var yodaGroup = new Kinetic.Group({
x: 100,
y: 110,
draggable: true
});
var layer = new Kinetic.Layer();
/*
* go ahead and add the groups
* to the layer and the layer to the
* stage so that the groups have knowledge
* of its layer and stage
*/
layer.add(darthVaderGroup);
layer.add(yodaGroup);
stage.add(layer);
// darth vader
var darthVaderImg = new Kinetic.Image({
x: 0,
y: 0,
image: images.darthVader,
width: 200,
height: 138,
name: 'image'
});
darthVaderGroup.add(darthVaderImg);
addAnchor(darthVaderGroup, -20, -20, 'topLeft', 'none');
addAnchor(darthVaderGroup, 220, -20, 'topRight', 'none');
addAnchor(darthVaderGroup, 220, 158, 'bottomRight', 'none');
addAnchor(darthVaderGroup, -20, 158, 'bottomLeft','none');
addAnchor(darthVaderGroup, 225, 0, 'rotateAnchor','rotate');
darthVaderGroup.on('dragstart', function() {
this.moveToTop();
});
stage.draw();
}
var sources = {
darthVader: 'http://www.html5canvastutorials.com/demos/assets/darth-vader.jpg'
};
loadImages(sources, initStage);
</script>
</body>
</html>
You can use each anchors show/hide methods inside the images mouseenter/mouseleave events to display the anchors when the mouse enters the image:
image.on("mouseleave",function(){ anchor1.hide(); }
image.on("mouseenter",function(){ anchor1.show(); layer.draw(); }
Problem is that since your anchors are partly outside your image, so hiding the anchors when the mouse leaves the image might make the anchors "disappear" when the user intends to use them.
The ideal solution would be to listen for mouseenter/mouseleave events on the group which contains the image but also extends to include the outside part of the anchors. Unfortunately, a Kinetic.Group will not respond to mouseenter/mouseleave events.
A workaround is to create a Kinetic.Rect background to the group which includes the images plus the anchors. The rect will listen for mouseenter/mouseleave events and will show/hide the anchors. If you don't want the background rect to be visible, just set it's opacity to .001. The rect will still listen for events, but will be invisible.
groupBackgroundRect.on("mouseleave",function(){ anchor1.hide(); }
groupBackgroundRect.on("mouseenter",function(){ anchor1.show(); layer.draw(); }
A related note:
With KineticJS, combining rotation with resizing is made more difficult than it needs to be because KineticJS uses offsetX/offsetY as both an object's rotation point and as an offset to its position. Your key to making it work will be to re-center the offset point after resizing so that your rotation takes place around the new centerpoint--not the previous centerpoint. (or reset the offset reference point to any other point that you want to rotate around).