Giving a canvas using kinetic an id - javascript

I am trying to download a canvas to my computer as an image, I can get this working fine while inspecting the element within chrome by editing the generated html via kinetic.js, simply adding id="canvas" to the canvas. However I cannot find how to do this through the code itself.
I know that each time I create a new kinetic layer I am essentially creating a new canvas class but am unsure of how to add an id or if it is do-able.
Any help would be greatly appreciated,
Melissa
HTML:
<!DOCTYPE HTML>
<html>
<head>
<title>Test Page</title>
<style>
body {
margin: 0px;
padding: 0px;
}
canvas {
border: 1px solid #9C9898;
}
</style>
<script src="kinetic-v3.9.7.min.js"></script>
<script src="canvas2image.js"></script>
<script src="base64.js"></script>
<script src="script.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"> </script>
<script>
$( document ).ready(function() {
function downloadCanvas(link, canvasId, filename) {
link.href = document.getElementById(canvasId).toDataURL();
link.download = filename;
}
document.getElementById('download').addEventListener('click', function() {
downloadCanvas(this, 'canvas', 'test.png');
}, false);
});
$(function() {
$("canvas").attr("id","canvas");
});
</script>
</head>
<body onmousedown="return false;">
<div id="right" style="float: right;">
<a id="download" href="#">Download as image</a>
<input type='file' onchange="readURL(this);" />
<img src="#" name="addimg" id="addimg" onClick="addClickedImage('addimg')" /><br /><br />
download<br /><br />
clear
</div><!-- #right -->
<div role="main">
<div id="container">
</div><!-- #container -->
</div><!-- main -->
</body>
JS
var stage;
var layer;
var selected;
var wasSelected;
var haveBackground; // first dragged image sets stage size
/*
* Set up canvas stage and layer
*/
function initCanvas(canvas) {
stage = new Kinetic.Stage({
container: canvas,
width: 850,
height: 500
});
layer = new Kinetic.Layer();
stage.add(layer);
stage.draw();
}
/*
* Clear canvas, start again
*/
function clearCanvas() {
layer.removeChildren();
layer.draw();
haveBackground = false;
}
/*
* Resize
*/
function resize(group, activeAnchor) {
var tl = group.get(".tl")[0];
var tr = group.get(".tr")[0];group
var br = group.get(".br")[0];
var bl = group.get(".bl")[0];
var handle = group.get(".handle")[0];
var ghost = group.get(".ghost")[0];
var flip = group.get(".flip")[0];
var image = group.get(".image")[0];
switch (activeAnchor.attrs.name) {
case "tl":
bl.setPosition(tl.attrs.x, br.attrs.y);
tr.setPosition(br.attrs.x, tl.attrs.y);
break;
case "tr":
br.setPosition(tr.attrs.x, bl.attrs.y);
tl.setPosition(bl.attrs.x, tr.attrs.y);
break;
case "bl":
br.setPosition(tr.attrs.x, bl.attrs.y);
tl.setPosition(bl.attrs.x, tr.attrs.y);
break;
case "br":
bl.setPosition(tl.attrs.x, br.attrs.y);
tr.setPosition(br.attrs.x, tl.attrs.y);
break;
}
handle.setPosition((tr.attrs.x + tl.attrs.x) / 2, tl.attrs.y - 20);
ghost.setPosition(handle.getPosition());
flip.setPosition((tr.attrs.x + tl.attrs.x) / 2, bl.attrs.y + 20);
image.setPosition(tl.attrs.x, tl.attrs.y);
image.attrs.width = tr.attrs.x - tl.attrs.x;
image.attrs.height = bl.attrs.y - tl.attrs.y;
}
/*
* Rotate
*/
function rotate(group) {
var c = group.getAbsolutePosition();
var p0 = {x: c.x, y: c.y - 50};
var p1 = stage.getUserPosition();
var p0c = Math.sqrt(Math.pow(c.x-p0.x,2) + Math.pow(c.y-p0.y,2)); // p0->c (b)
var p1c = Math.sqrt(Math.pow(c.x-p1.x,2) + Math.pow(c.y-p1.y,2)); // p1->c (a)
var p0p1 = Math.sqrt(Math.pow(p1.x-p0.x,2) + Math.pow(p1.y-p0.y,2)); // p0->p1 (c)
var deg = Math.acos((p1c*p1c+p0c*p0c-p0p1*p0p1)/(2*p1c*p0c));
// fix for negative rotation
if(p1.x < c.x) {
deg = (360 * (Math.PI/180)) - deg;
}
group.setRotation(deg);
}
/*
* Flip
*/
function flip(group) {
group.attrs.scale.x = group.attrs.scale.x * -1;
}
/*
* Fix center offset (due to resizing from a corner)
*/
function fixCenterOffset(group) {
var image = group.get(".image")[0]
var currentOffset = group.getCenterOffset();
var currentPosition = group.getPosition();
var newOffset = {x: image.attrs.width /2, y: image.attrs.height /2};
var newPosition = {
x: currentPosition.x - (currentOffset.x - newOffset.x),
y: currentPosition.y - (currentOffset.y - newOffset.y)
}
group.setCenterOffset(newOffset);
group.setPosition(newPosition);
layer.draw();
}
/*
* Add an image plus anchors to the canvas using group
*/
function initImage(img, type) {
var kimggroup = initNormalImage(img);
layer.add(kimggroup);
stage.add(layer);
// Draw the img
stage.draw();
}
/*
* Add normal image
*/
function initNormalImage(img) {
var kimggroup = new Kinetic.Group({
x: stage.attrs.width / 2,
y: stage.attrs.height / 2,
draggable: true,
centerOffset: [img.width/2, img.height/2]
});
// Make the img and add it to the group
var kimg = new Kinetic.Image({
x: 0,
y: 0,
image: img,
width: img.width,
height: img.height,
name: "image"
});
kimggroup.add(kimg);
// Add anchors for resizing and rotation
addAnchor(kimggroup, 0, 0, "tl");
addAnchor(kimggroup, img.width, 0, "tr");
addAnchor(kimggroup, img.width, img.height, "br");
addAnchor(kimggroup, 0, img.height, "bl");
addAnchor(kimggroup, img.width / 2, -20, "handle");
addAnchor(kimggroup, img.width / 2, -20, "ghost");
addAnchor(kimggroup, img.width / 2, img.height +20, "flip");
// On click make the image selected
kimggroup.on("mousedown", function() {
wasSelected = selected;
selected = this;
updateSelected();
this.moveToTop();
stage.draw();
});
kimg.on("mouseover", function() {
document.body.style.cursor = "move";
});
kimg.on("mouseout", function() {
document.body.style.cursor = "default";
});
// Double click to remove
kimg.on("dblclick dbltap", function() {
layer.remove(kimggroup);
layer.draw();
});
return kimggroup;
}
/*
* Create anchor and add to group
*/
function addAnchor(group, x, y, name) {
var config = {
x: x,
y: y,
stroke: "#000",
fill: "#000",
strokeWidth: 1,
radius: 4,
name: name,
draggable: true
}
switch (name) {
case "handle":
config.draggable = false;
var anchor = addRotateAnchor(group, config);
break;
case "ghost":
config.stroke = "#993333";
var anchor = addRotateGhostAnchor(group, config);
break;
case "flip":
config.stroke = "#0000ff";
config.draggable = false;
var anchor = addFlipAnchor(group, config);
break;
default:
var anchor = addResizeAnchor(group, config);
break;
}
anchor.hide();
group.add(anchor);
}
/*
* Set up resize anchor
*/
function addResizeAnchor(group, config) {
var anchor = new Kinetic.Circle(config);
anchor.on("dragmove", function() {
resize(group, this);
layer.draw();
});
anchor.on("mousedown touchstart", function() {
group.draggable(false);
this.moveToTop();
});
anchor.on("dragend", function() {
fixCenterOffset(group);
group.draggable(true);
layer.draw();
});
anchor.on("mouseover", function() {
var layer = this.getLayer();
document.body.style.cursor = "pointer";
this.setStrokeWidth(3);
layer.draw();
});
anchor.on("mouseout", function() {
var layer = this.getLayer();
document.body.style.cursor = "default";
this.setStrokeWidth(2);
layer.draw();
});
return anchor;
}
/*
* Set up rotation anchor
*/
function addRotateAnchor(group, config) {
var anchor = new Kinetic.Circle(config);
anchor.on("mouseover", function() {
var layer = this.getLayer();
document.body.style.cursor = "pointer";
this.setStrokeWidth(3);
layer.draw();
});
anchor.on("mouseout", function() {
var layer = this.getLayer();
document.body.style.cursor = "default";
this.setStrokeWidth(2);
layer.draw();
});
return anchor;
}
/*
* Set up rotation ghost anchor
*/
function addRotateGhostAnchor(group, config) {
var anchor = new Kinetic.Circle(config);
anchor.on("dragmove", function() {
rotate(group);
layer.draw();
});
anchor.on("mousedown touchstart", function() {
group.draggable(false);
this.moveToTop();
});
anchor.on("dragend", function() {
var handle = group.get(".handle")[0];
this.setPosition(handle.getPosition());
group.draggable(true);
layer.draw();
});
anchor.on("mouseover", function() {
var layer = this.getLayer();
document.body.style.cursor = "pointer";
this.setStrokeWidth(3);
layer.draw();
});
anchor.on("mouseout", function() {
var layer = this.getLayer();
document.body.style.cursor = "default";
this.setStrokeWidth(2);
layer.draw();
});
return anchor;
}
/*
* Set up flip anchor
*/
function addFlipAnchor(group, config) {
var anchor = new Kinetic.Circle(config);
anchor.on("mousedown touchstart", function() {
flip(group);
layer.draw();
});
anchor.on("mouseover", function() {
var layer = this.getLayer();
document.body.style.cursor = "pointer";
this.setStrokeWidth(3);
layer.draw();
});
anchor.on("mouseout", function() {
var layer = this.getLayer();
document.body.style.cursor = "default";
this.setStrokeWidth(2);
layer.draw();
});
return anchor;
}
/*
* Show anchors only when group selected
*/
function updateSelected() {
// Deselect the old img if there was any
if (wasSelected) {
wasSelected.get(".tl")[0].hide();
wasSelected.get(".tr")[0].hide();
wasSelected.get(".br")[0].hide();
wasSelected.get(".bl")[0].hide();
wasSelected.get(".handle")[0].hide();
wasSelected.get(".ghost")[0].hide();
wasSelected.get(".flip")[0].hide();
}
// Select the new image
selected.get(".tl")[0].show();
selected.get(".tr")[0].show();
selected.get(".br")[0].show();
selected.get(".bl")[0].show();
selected.get(".handle")[0].show();
selected.get(".ghost")[0].show();
selected.get(".flip")[0].show();
}
/*
* Add clicked images to the canvas
*/
function addClickedImage(name) {
console.log(document.getElementById(name).getAttribute("src"));
var newImg = new Image();
newImg.src = document.getElementById(name).getAttribute("src");
//var img = document.getElementById(name);
initImage(newImg, "normal");
}
/*
* Listen for images dragged into canvas and add them
*/
function setupDragAndDrop() {
stage.content.addEventListener("dragover", function (evt) {
evt.preventDefault();
}, false);
// Handle dropped image file - only Firefox and Google Chrome
stage.content.addEventListener("drop", function (evt) {
dragImg = new Image();
var files = evt.dataTransfer.files;
if (files.length > 0) {
var file = files[0];
if (typeof FileReader !== "undefined" && file.type.indexOf("image") != -1) {
var reader = new FileReader();
reader.onload = function (evt) {
dragImg.src = evt.target.result;
};
reader.readAsDataURL(file);
dragImg.onload = function(){
var type = "normal";
initImage(this, type);
}
}
}
evt.preventDefault();
}, false);
}
window.onload = function() {
initCanvas("container");
setupDragAndDrop();
};
//upload images
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#addimg')
.attr('src', e.target.result)
.width(150)
.height(200);
};
reader.readAsDataURL(input.files[0]);
}
}

Related

Konva how to transform image

I follow the Documentation that Konva have.
https://konvajs.github.io/docs/select_and_transform/Basic_demo.html
and
https://konvajs.github.io/docs/sandbox/Image_Resize.html
But the problem is they only have transform demo for rectangle shape. My plan is to have it on image. But so far I cant get it right. Here's my example code.
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://rawgit.com/konvajs/konva/master/konva.min.js"></script>
<meta charset="utf-8">
<title>Konva Image Resize Demo</title>
<style>
body {
margin: 0;
padding: 0;
overflow: hidden;
background-color: #F0F0F0;
}
</style>
</head>
<body class="col-md-12">
<div id="container" class="col-md-10">
</div>
<script>
var width = window.innerWidth;
var height = window.innerHeight;
function testFunction() {
addCanvas();
}
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 image = group.get('Image')[0];
var anchorX = activeAnchor.getX();
var anchorY = activeAnchor.getY();
// update anchor positions
switch (activeAnchor.getName()) {
case 'topLeft':
topRight.setY(anchorY);
bottomLeft.setX(anchorX);
break;
case 'topRight':
topLeft.setY(anchorY);
bottomRight.setX(anchorX);
break;
case 'bottomRight':
bottomLeft.setY(anchorY);
topRight.setX(anchorX);
break;
case 'bottomLeft':
bottomRight.setY(anchorY);
topLeft.setX(anchorX);
break;
}
image.position(topLeft.position());
var width = topRight.getX() - topLeft.getX();
var height = bottomLeft.getY() - topLeft.getY();
if (width && height) {
image.width(width);
image.height(height);
}
}
var stage = new Konva.Stage({
container: 'container',
width: width,
height: height
});
var layer = new Konva.Layer();
stage.add(layer);
// darth vader
var darthVaderImg = new Konva.Image({
width: 200,
height: 137,
name: 'imgs'
});
// yoda
var yodaImg = new Konva.Image({
width: 93,
height: 104,
name: 'imgs'
});
var darthVaderGroup = new Konva.Group({
x: 180,
y: 50,
draggable: true,
id: 'test1',
name: 'Imgs'
});
var num = 0;
function addCanvas() {
var test = new Konva.Group({
x: 200,
y: 100,
draggable: true
});
var testImg = new Konva.Image({
width: 93,
height: 104
});
layer.add(test);
test.add(testImg);
console.log('test');
var imageObjs = new Image();
imageObjs.onload = function() {
testImg.image(imageObjs);
layer.draw();
};
imageObjs.src = './pic/test2.png';
}
layer.add(darthVaderGroup);
darthVaderGroup.add(darthVaderImg);
var yodaGroup = new Konva.Group({
x: 20,
y: 110,
draggable: true,
id: 'Imgs',
});
layer.add(yodaGroup);
yodaGroup.add(yodaImg);
var imageObj1 = new Image();
imageObj1.onload = function() {
darthVaderImg.image(imageObj1);
layer.draw();
};
imageObj1.src = './pic/test2.png';
var imageObj2 = new Image();
imageObj2.onload = function() {
yodaImg.image(imageObj2);
layer.draw();
};
imageObj2.src = './pic/test1.jpg';
stage.on('click', function(e) {
if (e.target === stage) {
stage.find('Transformer').destroy();
layer.draw();
return;
}
// do nothing if clicked NOT on our rectangles
if (!e.target.hasName('imgs')) {
return;
}
// remove old transformers
// TODO: we can skip it if current rect is already selected
stage.find('Transformer').destroy();
// create new transformer
var tr = new Konva.Transformer();
layer.add(tr);
tr.attachTo(e.target);
layer.draw();
});
function addTrans(e) {
}
</script>
</body>
</html>
The output
Here's the output. Whenever I click the image the transform will be out of place and will on stay in 1 place.
I finally figure it out. Turn out I place the draggable in the wrong place. I put the draggable into the Konva.Image instead in the group.
Thanks

Images do not appear completely until mouse click

I found a issue that images are not show like below.
It's a canvas that I use konva.js.
And the stage is draggable: true. I found the images will now show event if I click this canvas when draggable: false. It's a little like the canvas be reload so all images appear.
After I click this canvas. All images will be showen.
This is some of my code.
var rackTop = new Image();
rackTop.onload = function() {
var image = new Konva.Image({
x: 13+x,
y : y,
image: rackTop,
width: drawer_width + rack_side*2,
height: Math.ceil(70 * scale_default)
});
onerackLayer.add(image);
};
rackTop.src = 'img/rack/rack_top.png';
function createMutiRackImage(callback, number, serverObj, serverContent, type) {
var img = new Image();
if (type === 'front') {
img.src = serverObj.imgUrl.thumFront;
} else if (type === 'rear') {
img.src = serverObj.imgUrl.thumRear;
} else {
// console.log('Server img type not defined.');
return;
}
var imgData = {};
imgData.x = serverContent.x;
imgData.y = serverContent.y;
imgData.width = serverContent.width;
imgData.height = serverContent.height;
imgData.status = serverContent.health;
imgData.type = type;
imgData.location = serverObj.locationId;
imgData.imgUrl = serverObj.imgUrl;
imgData.model = serverObj.model;
imgData.imgObj = img;
imgData.rackSize = serverContent.rackSize;
imgData.name = serverObj.name;
imgData.rackid = serverObj.rackid;
imgData.nodes = serverObj.nodes;
serverImgs.push(imgData);
img.onload = function() {
callback_multi(number);
}(number);
}
function callback_multi(i) {
var kinImgObj = createrMultiKonvaImage(serverImgs[i]);
onerackLayer.add(kinImgObj);
onerackLayer.draw();
}
function createrMultiKonvaImage(imgData) {
var _imgObj = imgData.imgObj;
var x = imgData.x;
var y = imgData.y;
var width = imgData.width;
var height = imgData.height;
var position = imgData.location;
var imgUrl = imgData.imgUrl;
var light = '';
var image = new Konva.Image({
x: x,
y: y,
width : width,
height : height,
image : _imgObj,
});
return image;
}
After you added a Konva.Image into a Layer you need to redraw it:
rackTop.onload = function() {
var image = new Konva.Image({
x: 13+x,
y : y,
image: rackTop,
width: drawer_width + rack_side*2,
height: Math.ceil(70 * scale_default)
});
onerackLayer.add(image);
onerackLayer.draw(); // this line is important
};

Kineticjs - free rotate on image

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).

In the following code, Canvas layer disappears on mouse click in Fabric.js and Firefox stops responding when creating canvas to image?

http://jsfiddle.net/rodrigopandini/gj7HT/
I'm using this example to drag & drop images from my computer to canvas using Fabric.js.
//Drag and Drop Image
var canvas = new fabric.Canvas('c');
function handleDragStart(e) {
[].forEach.call(images, function (img) {
img.classList.remove('img_dragging');
});
this.classList.add('img_dragging');
}
function handleDragOver(e) {
if (e.preventDefault) {
e.preventDefault(); // Necessary. Allows us to drop.
}
e.dataTransfer.dropEffect = 'copy'; // See the section on the DataTransfer object.
// NOTE: comment above refers to the article (see top) -natchiketa
return false;
}
function handleDragEnter(e) {
// this / e.target is the current hover target.
this.classList.add('over');
}
function handleDragLeave(e) {
this.classList.remove('over'); // this / e.target is previous target element.
}
function handleDrop(e) {
// this / e.target is current target element.
/*
if (e.stopPropagation) {
e.stopPropagation(); // stops the browser from redirecting.
}
*/
e.stopPropagation(); // Stops some browsers from redirecting.
e.preventDefault(); // Stops some browsers from redirecting.
// handle desktop images
if (e.dataTransfer.files.length > 0) {
var files = e.dataTransfer.files;
for (var i = 0, f; f = files[i]; i++) {
// Only process image files.
if (f.type.match('image.*')) {
// Read the File objects in this FileList.
var reader = new FileReader();
// listener for the onload event
reader.onload = function (evt) {
// create img element
var img = document.createElement('img');
img.src = evt.target.result;
// put image on canvas
var newImage = new fabric.Image(img, {
width: img.width,
height: img.height,
// Set the center of the new object based on the event coordinates relative to the canvas container.
left: e.layerX,
top: e.layerY
});
canvas.add(newImage);
};
// Read in the image file as a data URL.
reader.readAsDataURL(f);
}
}
}
// handle browser images
else {
var img = document.querySelector('#images img.img_dragging');
var newImage = new fabric.Image(img, {
width: img.width,
height: img.height,
// Set the center of the new object based on the event coordinates relative to the canvas container.
left: e.layerX,
top: e.layerY
});
canvas.add(newImage);
}
return false;
}
function handleDragEnd(e) {
// this/e.target is the source node.
[].forEach.call(images, function (img) {
img.classList.remove('img_dragging');
});
}
if (Modernizr.draganddrop) {
// Browser supports HTML5 DnD.
// Bind the event listeners for the image elements
var images = document.querySelectorAll('#images img');
[].forEach.call(images, function (img) {
img.addEventListener('dragstart', handleDragStart, false);
img.addEventListener('dragend', handleDragEnd, false);
});
// Bind the event listeners for the canvas
var canvasContainer = document.getElementById('canvas-container');
canvasContainer.addEventListener('dragenter', handleDragEnter, false);
canvasContainer.addEventListener('dragover', handleDragOver, false);
canvasContainer.addEventListener('dragleave', handleDragLeave, false);
canvasContainer.addEventListener('drop', handleDrop, false);
} else {
// Replace with a fallback to a library solution.
alert("This browser doesn't support the HTML5 Drag and Drop API.");
}
//End Drag and Drop
For adding multiple images by drag and drop I used the above code (jsfiddle example).
Here's my code which is working fine when I add images one by one on Canvas.
var $ = function (id) { return document.getElementById(id) };
//Upload Click
var fileSelect = document.getElementById("fileSelect"),
upload = document.getElementById("upload");
fileSelect.addEventListener("click", function (e) {
if (upload) {
upload.click();
}
e.preventDefault(); // prevent navigation to "#"
}, false);
//End
function applyFilter(index, filter) {
var obj = canvas.getActiveObject();
obj.filters[index] = filter;
obj.applyFilters(canvas.renderAll.bind(canvas));
}
function applyFilterValue(index, prop, value) {
var obj = canvas.getActiveObject();
if (obj.filters[index]) {
obj.filters[index][prop] = value;
obj.applyFilters(canvas.renderAll.bind(canvas));
}
}
var canvas = new fabric.Canvas('c'),
f = fabric.Image.filters;
//Canvas Events
canvas.on({
'object:selected': function () {
fabric.util.toArray(document.getElementsByTagName('input'))
.forEach(function (el) {
el.disabled = false;
})
//Check for already applied filter on Image after selecting an image
var filters = ['grayscale', 'invert', 'remove-white', 'sepia', 'sepia2',
'brightness', 'noise', 'gradient-transparency', 'pixelate',
'blur', 'sharpen'];
for (var i = 0; i < filters.length; i++) {
$(filters[i]).checked = !!canvas.getActiveObject().filters[i];
}
canvas._activeObject.bringToFront();
},
//'selection:cleared': function() {
// fabric.util.toArray(document.getElementsByTagName('input'))
// .forEach(function(el) { el.disabled = true; })
//}
});
var imageLoader = document.getElementById('upload');
imageLoader.addEventListener('change', handleImage, false);
var c = document.getElementById('c');
var context = canvas.getContext('2d');
//Canvas Handler
function handleImage(e) {
var reader = new FileReader();
reader.onload = function (event) {
var img = new Image();
img.onload = function () {
canvas.width = img.width;
canvas.height = img.height;
context.drawImage(img);
}
img.src = event.target.result;
}
reader.readAsDataURL(e.target.files[0]);
}
//Fabric.JS single image handler
document.getElementById('upload').onchange = function handleImage(e) {
var reader = new FileReader();
reader.onload = function(event) {
var imgObj = new Image();
imgObj.src = event.target.result;
imgObj.onload = function() {
var image = new fabric.Image(imgObj);
image.set({
left: 250,
top: 250,
angle: 20,
padding: 10,
cornersize: 10,
}).scale(0.4);
canvas.add(image);
}
}
reader.readAsDataURL(e.target.files[0]);
}
//End
//Static Image in background
function setBackgrnd() {
fabric.Image.fromURL('/2-road.jpg', function (img) {
var oImg = img.set({ left: 400, top: 300, opactiy:0.5, selectable:false, lockHorizontally: false, lockVertically: false, lockScaling: false, lockRotation: false }).scale(1);
//oImg.filters.push(new fabric.Image.filters.blur());
//oImg.applyFilters(canvas.renderAll.bind(canvas));
//canvas.setBackgroundImage('/2-road.jpg', canvas.renderAll.bind(canvas));
canvas.add(oImg).renderAll();
canvas.setActiveObject(oImg);
canvas.sendToBack(oImg);
$('#delBackgrnd').click(function() {
canvas.getObjects();
remove(oImg);
canvas.renderAll();
});
//function setBackgrnd() {
// canvas.add(oImg).renderAll();
// canvas.setActiveObject(oImg);
//}
//function delBackgrnd() {
// fxRemove(oImg, canvas.renderAll());
//}
});
}
//Clears Everything on Canvas
function clearCanvas() {
canvas.clear();
}
//Delete Background Image
function delBackgrnd() {
//SelectedObject.onclick = function () {
// if (canvas.getActiveGroup()) {
// canvas.getActiveGroup().forEachObject(function (o) { canvas.remove(o) });
// canvas.discardActiveGroup().renderAll();
// } else {
// canvas.remove(canvas.getActiveObject());
// }
//};
}
//Generate Collage
function convertCanvasToImage() {
//var canvas = document.getElementById('c');
canvas.deactivateAll().renderAll();
var image_src = canvas.toDataURL("image/jpeg");
//document.write('<img src="' + image_src + '"/>');
window.open(image_src);
}
//Drag and Drop Image
var canvas = new fabric.Canvas('c');
function handleDragStart(e) {
[].forEach.call(images, function (img) {
img.classList.remove('img_dragging');
});
this.classList.add('img_dragging');
}
function handleDragOver(e) {
if (e.preventDefault) {
e.preventDefault(); // Necessary. Allows us to drop.
}
e.dataTransfer.dropEffect = 'copy'; // See the section on the DataTransfer object.
// NOTE: comment above refers to the article (see top) -natchiketa
return false;
}
function handleDragEnter(e) {
// this / e.target is the current hover target.
this.classList.add('over');
}
function handleDragLeave(e) {
this.classList.remove('over'); // this / e.target is previous target element.
}
function handleDrop(e) {
// this / e.target is current target element.
/*
if (e.stopPropagation) {
e.stopPropagation(); // stops the browser from redirecting.
}
*/
e.stopPropagation(); // Stops some browsers from redirecting.
e.preventDefault(); // Stops some browsers from redirecting.
// handle desktop images
if (e.dataTransfer.files.length > 0) {
var files = e.dataTransfer.files;
for (var i = 0, f; f = files[i]; i++) {
// Only process image files.
if (f.type.match('image.*')) {
// Read the File objects in this FileList.
var reader = new FileReader();
// listener for the onload event
reader.onload = function (evt) {
// create img element
var img = document.createElement('img');
img.src = evt.target.result;
// put image on canvas
var newImage = new fabric.Image(img, {
width: img.width,
height: img.height,
// Set the center of the new object based on the event coordinates relative to the canvas container.
left: e.layerX,
top: e.layerY
});
canvas.add(newImage);
};
// Read in the image file as a data URL.
reader.readAsDataURL(f);
}
}
}
// handle browser images
else {
var img = document.querySelector('#images img.img_dragging');
var newImage = new fabric.Image(img, {
width: img.width,
height: img.height,
// Set the center of the new object based on the event coordinates relative to the canvas container.
left: e.layerX,
top: e.layerY
});
canvas.add(newImage);
}
return false;
}
function handleDragEnd(e) {
// this/e.target is the source node.
[].forEach.call(images, function (img) {
img.classList.remove('img_dragging');
});
}
if (Modernizr.draganddrop) {
// Browser supports HTML5 DnD.
// Bind the event listeners for the image elements
var images = document.querySelectorAll('#images img');
[].forEach.call(images, function (img) {
img.addEventListener('dragstart', handleDragStart, false);
img.addEventListener('dragend', handleDragEnd, false);
});
// Bind the event listeners for the canvas
var canvasContainer = document.getElementById('canvas-container');
canvasContainer.addEventListener('dragenter', handleDragEnter, false);
canvasContainer.addEventListener('dragover', handleDragOver, false);
canvasContainer.addEventListener('dragleave', handleDragLeave, false);
canvasContainer.addEventListener('drop', handleDrop, false);
} else {
// Replace with a fallback to a library solution.
alert("This browser doesn't support the HTML5 Drag and Drop API.");
}
//End Drag and Drop
//End of Code
My original HTML canvas tag is
<div id="canvas-container" class="canvas-container" >
<canvas id="c" width="800" height="600" style="left: -300px; border: 1px dotted;"></canvas>
</div>
But, when I integrated this code the images are adding to the canvas but as I click on Canvas they disappears. I inspected element in Chrome and found that there are 2 Canvas tags.
<div id="canvas-container" class="canvas-container">
<div class="canvas-container" style="width: 800px; height: 600px; position: relative; -webkit-user-select: none;">
<div class="canvas-container" style="width: 800px; height: 600px; position: relative; -webkit-user-select: none;">
<canvas id="c" width="800" height="600" style="left: 0px; border: 1px dotted; position: absolute; width: 800px; height: 600px; top: 0px; -webkit-user-select: none;" class="lower-canvas"></canvas>
<canvas class="upper-canvas" width="800" height="600" style="position: absolute; width: 800px; height: 600px; left: 0px; top: 0px; -webkit-user-select: none;"></canvas>
</div>
<canvas class="upper-canvas" width="800" height="600" style="position: absolute; width: 800px; height: 600px; left: 0px; top: 0px; -webkit-user-select: none;"></canvas>
</div>
</div>
When I changed the position of all elements in above code to position: relative;, it works.
The 3 extra Canvas tags are generated automatically. How can I change the position? Also, when I generate the png or jpg image of canvas using DataURL, firefox stops responding.
You need to override the css of that library, by using the following code.
/deep/ .canvas-container{
.upper-canvas {
position: relative !important;
}
}

Proportion scaling AND stretching of image using anchor points

i have an image with 8 anchor points. Thanks to an example, i've managed to get those on the 4 corners to only scale the picture. But i am having difficulty in making the other 4 to stretch the image ONLY.
The midTop & midBottom anchors shall stretch vertically; the midLeft and midRight anchors shall stretch horizontally. I think it might concern the bounds those anchors can move but i don't know how to proceed.
http://jsfiddle.net/Dppm7/3/ (sorry can't get this to work in jsFiddle)..
The output looks like this.
Please if anyone can help. :)
Some code for the anchors (not all codes for the middle anchors have been implemented):
// Update the positions of handles during drag.
// This needs to happen so the dimension calculation can use the
// handle positions to determine the new width/height.
switch (activeHandleName) {
case "topLeft":
topRight.setY(activeHandle.getY());
midRight.setY(activeHandle.getY());
midTop.setY(activeHandle.getY());
bottomLeft.setX(activeHandle.getX());
midLeft.setX(activeHandle.getX());
midBottom.setX(activeHandle.getX());
break;
case "topRight":
topLeft.setY(activeHandle.getY());
midLeft.setY(activeHandle.getY());
midTop.setY(activeHandle.getY());
bottomRight.setX(activeHandle.getX());
midBottom.setX(activeHandle.getX());
midRight.setX(activeHandle.getX());
break;
case "bottomRight":
bottomLeft.setY(activeHandle.getY());
midBottom.setY(activeHandle.getY());
midLeft.setY(activeHandle.getY());
topRight.setX(activeHandle.getX());
midTop.setX(activeHandle.getX());
midRight.setX(activeHandle.getX());
break;
case "bottomLeft":
bottomRight.setY(activeHandle.getY());
midBottom.setY(activeHandle.getY());
midRight.setY(activeHandle.getY());
topLeft.setX(activeHandle.getX());
midTop.setX(activeHandle.getX());
midLeft.setX(activeHandle.getX());
break;
case "midTop":
topRight.setY(activeHandle.getY());
topLeft.setY(activeHandle.getY());
midRight.setY(activeHandle.getY());
midLeft.setY(activeHandle.getY());
break;
case "midBottom":
bottomRight.setY(activeHandle.getY());
bottomLeft.setY(activeHandle.getY());
midRight.setY(activeHandle.getY());
midLeft.setY(activeHandle.getY());
break;
case "midRight":
topRight.setX(activeHandle.getX());
bottomRight.setX(activeHandle.getX());
midTop.setX(activeHandle.getX());
midBottom.setX(activeHandle.getX());
break;
case "midLeft":
topLeft.setX(activeHandle.getX());
bottomLeft.setX(activeHandle.getX());
midTop.setX(activeHandle.getX());
midBottom.setX(activeHandle.getX());
break;
}
// Calculate new dimensions. Height is simply the dy of the handles.
// Width is increased/decreased by a factor of how much the height changed.
newHeight = bottomLeft.getY() - topLeft.getY();
newWidth = image.getWidth() * newHeight / image.getHeight();
// Move the image to adjust for the new dimensions.
// The position calculation changes depending on where it is anchored.
// ie. When dragging on the right, it is anchored to the top left,
// when dragging on the left, it is anchored to the top right.
if (activeHandleName === "topRight" || activeHandleName === "bottomRight") {
image.setPosition(topLeft.getX(), topLeft.getY());
} else if (activeHandleName === "topLeft" || activeHandleName === "bottomLeft") {
image.setPosition(topRight.getX() - newWidth, topRight.getY());
}
imageX = image.getX();
imageY = image.getY();
// Update handle positions to reflect new image dimensions
topLeft.setPosition(imageX, imageY);
topRight.setPosition(imageX + newWidth, imageY);
bottomRight.setPosition(imageX + newWidth, imageY + newHeight);
bottomLeft.setPosition(imageX, imageY + newHeight);
midTop.setPosition(imageX + image.getWidth() / 2, imageY);
midBottom.setPosition(imageX + image.getWidth() / 2, imageY + newHeight);
midRight.setPosition(imageX + image.getWidth(), imageY + image.getHeight() / 2);
midLeft.setPosition(imageX, imageY + image.getHeight() / 2);
// Set the image's size to the newly calculated dimensions
if (newWidth && newHeight) {
image.setSize(newWidth, newHeight);
}
}
<script>
var imWidth;
var imHeight;
var topRight;
var topLeft;
var bottomLeft;
var width;
var height;
var group;
var bottomRight;
var image;
var aspectRatio;
var oldwidth;
var oldheight;
var oldtopleftX;
var oldtopleftY;
var shrinkLimitBound;
function update(activeAnchor) {
group = activeAnchor.getParent();
var anchorX = activeAnchor.getX();
var anchorY = activeAnchor.getY();
actRatio=imWidth/imHeight;
shrinkLimitBound=100;
height=bottomLeft.getY() - topLeft.getY();
width=topRight.getX() - topLeft.getX();
newRatio=(width)/(height);
width=actRatio*height;
switch (activeAnchor.getName()) {
case 'topLeft':
if(height<shrinkLimitBound)
{
height=shrinkLimitBound;
width=actRatio*height;;
topRight.setY(bottomRight.getY()-height);
}
else
{
if(anchorY < bottomRight.getY())
topRight.setY(anchorY);
else
topRight.setY(bottomRight.getY()-height);
}
topRight.setX(bottomRight.getX());
bottomLeft.setX(bottomRight.getX()-width);
bottomLeft.setY(bottomRight.getY());
topLeft.setX(bottomRight.getX()-width);
topLeft.setY(bottomRight.getY()-height);
break;
case 'topRight':
if(height<shrinkLimitBound)
{
height=shrinkLimitBound;
width=actRatio*height;;
topLeft.setY(bottomLeft.getY()-height);
}
else
{
if(anchorY < bottomLeft.getY()-shrinkLimitBound)
{
topLeft.setY(anchorY)
}
else
{
topLeft.setY(bottomLeft.getY()-height);
}
}
topLeft.setX(bottomLeft.getX());
bottomRight.setX(bottomLeft.getX()+width);
bottomRight.setY(bottomLeft.getY());
topRight.setX(bottomLeft.getX()+width);
topRight.setY(bottomLeft.getY()-height);
break;
case 'bottomRight':
if(height<shrinkLimitBound)
{
height=shrinkLimitBound;
width=actRatio*height;;
bottomLeft.setY(topLeft.getY()+height);
}
else
{
if(anchorY > topLeft.getY()+shrinkLimitBound)
{
bottomLeft.setY(anchorY);
}
else
bottomLeft.setY(topLeft.getY()+height);
}
bottomLeft.setX(topLeft.getX());
topRight.setX(topLeft.getX()+width);
topRight.setY(topLeft.getY());
bottomRight.setX(topLeft.getX()+width);
bottomRight.setY(topLeft.getY()+height);
break;
case 'bottomLeft':
if(height<shrinkLimitBound)
{
height=shrinkLimitBound;
width=actRatio*height;;
bottomRight.setY(topRight.getY()+height);
}
else
{
if(anchorY > topRight.getY())
bottomRight.setY(anchorY);
else
bottomRight.setY(topRight.getY()+height);
}
bottomRight.setX(topRight.getX());
topLeft.setX(topRight.getX()-width);
topLeft.setY(topRight.getY());
bottomLeft.setX(topRight.getX()-width);
bottomLeft.setY(topLeft.getY()+height);
break;
}
image.setPosition(topLeft.getPosition());
if(width>0 && height>0)
{
image.setSize(width,height);
}
oldwidth=width;
oldheight=height;
oldtopleftX=topLeft.getX();
oldtopleftY=topLeft.getY();
}
function addAnchor(group, x, y, name) {
var stage = group.getStage();
var layer = group.getLayer();
var anchor = new Kinetic.Circle({
x: x,
y: y,
stroke: '#666',
fill: '#ddd',
strokeWidth: 0,
radius: 4,
name: name,
draggable: true,
dragOnTop: false
});
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 initStage(images) {
var conWidth = 578; //container Width.
var conHeight = 400; //container Heitgh.
imWidth = images.dressTrailImage.width;
imHeight = images.dressTrailImage.height;
if (imWidth > conWidth)
{
imHeight = (imHeight/imWidth)*conWidth;
imWidth = conWidth;
}
if (imHeight > conHeight)
{
imWidth = (imWidth/imHeight)*conHeight;
imHeight = conHeight;
}
if ((imHeight < conHeight) && (imWidth < conWidth))
{
var diffX = conWidth - imWidth;
var diffY = conHeight - imHeight;
var diffY2 = (imHeight/imWidth)*diffX;
if (diffY2 > diffY)
{
imWidth = (imWidth/imHeight)*conHeight;
imHeight = conHeight;
}
else
{
imHeight = (imHeight/imWidth)*conWidth;
imWidth = conWidth;
}
}
images.UsrTrail.width = imWidth;
images.UsrTrail.height = imHeight;
var stage = new Kinetic.Stage({
container: 'container',
width: imWidth,
height: imHeight
});
var dressTrailImageGroup = new Kinetic.Group({
x: 0,
y: 0,
draggable: true,
//dragBoundFunc: function(pos) {
// console.log(pos);
// // var newX;
// // var newY;
// console.log(topLeft.x+","+bottomRight.y);
// x1=topLeft.x;
// x2=bottomRight.x;
// y1=topLeft.y;
// y2=bottomRight.y;
// x=pos.x;
// y=pos.y;
// var calsign = ((x-x1)*(y-y2))-((y-y1)*(x-x2))
// if (calsign < 0){
// return {
// x : pos.x,
// y : pos.y
// }
// }else {
// return {
// x : 50,
// y : 50
// }
// }
//}
// if (pos.x < ){
// newX=10;
// }
// else if ((pos.x+dressTrailImage.getWidth()) > stage.getWidth()-50){
// newX = stage.getWidth()-dressTrailImage.getWidth()-50;
// }
// else{
// newX = pos.x;
// };
// if(pos.y < 10){
// newY = 10;
// }
// else if((pos.y + dressTrailImage.getHeight()) > stage.getHeight()-50){
// newY = stage.getHeight()-dressTrailImage.getHeight()-50;
// }
// else {
// newY = pos.y;
// }
//console.log("newX:"+newX+", newY:"+newY);
// return {
// x : newX,
// y : newY,
// };
//}
});
// UsrTrail
var UsrTrailImg = new Kinetic.Image({
x: 0,
y: 0,
image: images.UsrTrail,
width: images.UsrTrail.width,
height: images.UsrTrail.height,
name: 'image'
});
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(dressTrailImageGroup);
layer.add(UsrTrailImg);
stage.add(layer);
UsrTrailImg.moveToBottom();
intialAspRatio = images.dressTrailImage.width/images.dressTrailImage.height;
console.log("aspectRatio is :"+intialAspRatio);
// dress Trail Image
var inith=200; //set this to the desired height of the dress that shows up initially
var initw=intialAspRatio*inith;
var neck_user_x=50;//from backend
var neck_user_y=20;//from backend
var neck_dress_x=50;//from backend
var neck_dress_y=5;//from backend
//for getting the actual width and height of the User's Image
var UsrImgObjActual= new Image();
UsrImgObjActual.src=sources.UsrTrail;
UsrimgWidth=UsrImgObjActual.width;
UsrimgHeight=UsrImgObjActual.height;
//////////////////////////////////////////
// var UsrimgWidth= 180;
// var UsrimgHeight=270;
console.log("height Should Be 270 and is:"+UsrimgHeight);
console.log("Width Should Be 180 and is:"+UsrimgWidth);
var dressimgWidth=initw;
var dressimgHeight=inith;
console.log("usertrail image width adn height"+images.UsrTrail.width+"::"+images.UsrTrail.height);
console.log("neck user and dress resp"+neck_user_x+","+neck_user_y+','+neck_dress_x+','+neck_dress_y);
var x_draw=((neck_user_x*UsrimgWidth)-(neck_dress_x*dressimgWidth));
var y_draw=((neck_user_y*UsrimgHeight)-(neck_dress_y*dressimgHeight));
x_draw=x_draw/100;
y_draw=y_draw/100;
console.log("xdraw and ydraw:"+x_draw+','+y_draw);
//top left corner coordinates of the dress image.
var initx=x_draw;
var inity=y_draw;
var dressTrailImage = new Kinetic.Image({
x: initx,
y: inity,
image: images.dressTrailImage,
name: 'image',
width: initw,// images.dressTrailImage.width,
height: inith //images.dressTrailImage.height
});
// dressTrailImage.width = 50;
// dressTrailImage.height = dressTrailImage.width / intialAspRatio;
// console.log(dressTrailImage.height);
dressTrailImageGroup.add(dressTrailImage);
addAnchor(dressTrailImageGroup, initx , inity, 'topLeft');
addAnchor(dressTrailImageGroup, initx + initw , inity , 'topRight');
addAnchor(dressTrailImageGroup, initx + initw , inity + inith, 'bottomRight');
addAnchor(dressTrailImageGroup, initx , inity + inith, 'bottomLeft');
topLeft = dressTrailImageGroup.get('.topLeft')[0];
topRight = dressTrailImageGroup.get('.topRight')[0];
bottomRight = dressTrailImageGroup.get('.bottomRight')[0];
bottomLeft = dressTrailImageGroup.get('.bottomLeft')[0];
image = dressTrailImageGroup.get('.image')[0];
dressTrailImageGroup.on('dragstart', function() {
this.moveToTop();
});
stage.draw();
}
var sources = {
dressTrailImage: "http://www.html5canvastutorials.com/demos/assets/darth-vader.jpg",
UsrTrail: "http://www.html5canvastutorials.com/demos/assets/yoda.jpg"
};
loadImages(sources, initStage);
//function called on clicking the submit button.
function Sunmit_fn(){
//neck positions of the trail dress in percentages (assumed for now!).
neckDressX=50;//in percentage.
neckDressY=5;//in percentage.
//height and width of the user image used in the canvas.
//original here here is refered to the height and width used in the canavs
var originalUserImgWidth = imWidth;
var originalUserImgHeight = imHeight;
var trailDressWidth = image.getWidth();//Final Image Width
var trailDressHeight = image.getHeight();//Final Image Height
imageX=topLeft.getParent().getX()+topLeft.getX()+1;//upper right anchor X Position
imageY=topLeft.getParent().getY()+topLeft.getY()+1;//upper right anchor Y Position
//formula for calculating the final neck positions of the resized and dragged dress
//with respect to the user image in percentages
neckFinalX=(imageX+(trailDressWidth*(neckDressX/100)))/originalUserImgWidth;
neckFinalY=(imageY+(trailDressHeight*(neckDressY/100)))/originalUserImgHeight;
//neck in percentages trail pic neck x,y.
neckFinalX=neckFinalX*100;
neckFinalY=neckFinalY*100;
//Just for testing.
console.log("neck position updated by User:");
console.log("X:"+neckFinalX+", Y:"+neckFinalY+")");
console.log("Resized Size of the dress is:");
console.log("Width:"+trailDressWidth+", Height:"+trailDressHeight);
}
</script>
This Script resizes only along one axis for four points.You can figure out the same for all the points

Categories

Resources