I have using scaling and rotation of images using mouse dragging separately. but i need to combine both the operations.
Please refer jsfiddle files for your understanding.
Scaling - http://jsfiddle.net/QqwKR/74/
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var canvasOffset = $("#canvas").offset();
var offsetX = canvasOffset.left;
var offsetY = canvasOffset.top;
var startX;
var startY;
var isDown = false;
var pi2 = Math.PI * 2;
var resizerRadius = 8;
var rr = resizerRadius * resizerRadius;
var draggingResizer = {
x: 0,
y: 0
};
var imageX = 50;
var imageY = 50;
var imageWidth, imageHeight, imageRight, imageBottom;
var draggingImage = false;
var startX;
var startY;
var img = new Image();
img.onload = function (){
imageWidth = img.width;
imageHeight = img.height;
imageRight = imageX + imageWidth;
imageBottom = imageY + imageHeight;
draw(true, false);}
img.src = "https://dl.dropboxusercontent.com/u/139992952/stackoverflow/facesSmall.png";
function draw(withAnchors, withBorders) {
// clear the canvas
ctx.clearRect(0, 0, canvas.width, canvas.height);
// draw the image
ctx.drawImage(img, 0, 0, img.width, img.height, imageX, imageY, imageWidth, imageHeight);
// optionally draw the draggable anchors
if (withAnchors) {
drawDragAnchor(imageX, imageY);
drawDragAnchor(imageRight, imageY);
drawDragAnchor(imageRight, imageBottom);
drawDragAnchor(imageX, imageBottom);
}
// optionally draw the connecting anchor lines
if (withBorders) {
ctx.beginPath();
ctx.moveTo(imageX, imageY);
ctx.lineTo(imageRight, imageY);
ctx.lineTo(imageRight, imageBottom);
ctx.lineTo(imageX, imageBottom);
ctx.closePath();
ctx.stroke();
}
}
function drawDragAnchor(x, y) {
ctx.beginPath();
ctx.arc(x, y, resizerRadius, 0, pi2, false);
ctx.closePath();
ctx.fill();
}
function anchorHitTest(x, y) {
var dx, dy;
// top-left
dx = x - imageX;
dy = y - imageY;
if (dx * dx + dy * dy <= rr) {
return (0);
}
// top-right
dx = x - imageRight;
dy = y - imageY;
if (dx * dx + dy * dy <= rr) {
return (1);
}
// bottom-right
dx = x - imageRight;
dy = y - imageBottom;
if (dx * dx + dy * dy <= rr) {
return (2);
}
// bottom-left
dx = x - imageX;
dy = y - imageBottom;
if (dx * dx + dy * dy <= rr) {
return (3);
}
return (-1);
}
function hitImage(x, y) {
return (x > imageX && x < imageX + imageWidth && y > imageY && y < imageY + imageHeight);
}
function handleMouseDown(e) {
startX = parseInt(e.clientX - offsetX);
startY = parseInt(e.clientY - offsetY);
draggingResizer = anchorHitTest(startX, startY);
draggingImage = draggingResizer < 0 && hitImage(startX, startY);
}
function handleMouseUp(e) {
draggingResizer = -1;
draggingImage = false;
draw(true, false);
}
function handleMouseOut(e) {
handleMouseUp(e);
}
function handleMouseMove(e) {
if (draggingResizer > -1) {
mouseX = parseInt(e.clientX - offsetX);
mouseY = parseInt(e.clientY - offsetY);
// resize the image
switch (draggingResizer) {
case 0:
//top-left
imageX = mouseX;
imageWidth = imageRight - mouseX;
imageY = mouseY;
imageHeight = imageBottom - mouseY;
break;
case 1:
//top-right
imageY = mouseY;
imageWidth = mouseX - imageX;
imageHeight = imageBottom - mouseY;
break;
case 2:
//bottom-right
imageWidth = mouseX - imageX;
imageHeight = mouseY - imageY;
break;
case 3:
//bottom-left
imageX = mouseX;
imageWidth = imageRight - mouseX;
imageHeight = mouseY - imageY;
break;
}
// enforce minimum dimensions of 25x25
if (imageWidth < 25) {
imageWidth = 25;
}
if (imageHeight < 25) {
imageHeight = 25;
}
// set the image right and bottom
imageRight = imageX + imageWidth;
imageBottom = imageY + imageHeight;
// redraw the image with resizing anchors
draw(true, true);
} else if (draggingImage) {
imageClick = false;
mouseX = parseInt(e.clientX - offsetX);
mouseY = parseInt(e.clientY - offsetY);
// move the image by the amount of the latest drag
var dx = mouseX - startX;
var dy = mouseY - startY;
imageX += dx;
imageY += dy;
imageRight += dx;
imageBottom += dy;
// reset the startXY for next time
startX = mouseX;
startY = mouseY;
// redraw the image with border
draw(false, true);
}
}
$("#canvas").mousedown(function (e) {
handleMouseDown(e);
});
$("#canvas").mousemove(function (e) {
handleMouseMove(e);
});
$("#canvas").mouseup(function (e) {
handleMouseUp(e);
});
$("#canvas").mouseout(function (e) {
handleMouseOut(e);
});
Rotating - http://jsfiddle.net/m1erickson/QqwKR/
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var canvasOffset = $("#canvas").offset();
var offsetX = canvasOffset.left;
var offsetY = canvasOffset.top;
var startX;
var startY;
var isDown = false;
var cx = canvas.width / 2;
var cy = canvas.height / 2;
var w;
var h;
var r = 0;
var img = new Image();
img.onload = function () {
w = img.width / 2;
h = img.height / 2;
draw();
}
img.src = "https://dl.dropboxusercontent.com/u/139992952/stackoverflow/facesSmall.png";
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
drawRotationHandle(true);
drawRect();
}
function drawRect() {
ctx.save();
ctx.translate(cx, cy);
ctx.rotate(r);
ctx.drawImage(img, 0, 0, img.width, img.height, -w / 2, -h / 2, w, h);
// ctx.fillStyle="yellow";
// ctx.fillRect(-w/2,-h/2,w,h);
ctx.restore();
}
function drawRotationHandle(withFill) {
ctx.save();
ctx.translate(cx, cy);
ctx.rotate(r);
ctx.beginPath();
ctx.moveTo(0, -1);
ctx.lineTo(w / 2 + 20, -1);
ctx.lineTo(w / 2 + 20, -7);
ctx.lineTo(w / 2 + 30, -7);
ctx.lineTo(w / 2 + 30, 7);
ctx.lineTo(w / 2 + 20, 7);
ctx.lineTo(w / 2 + 20, 1);
ctx.lineTo(0, 1);
ctx.closePath();
if (withFill) {
ctx.fillStyle = "blue";
ctx.fill();
}
ctx.restore();
}
function handleMouseDown(e) {
mouseX = parseInt(e.clientX - offsetX);
mouseY = parseInt(e.clientY - offsetY);
drawRotationHandle(false);
isDown = ctx.isPointInPath(mouseX, mouseY);
console.log(isDown);
}
function handleMouseUp(e) {
isDown = false;
}
function handleMouseOut(e) {
isDown = false;
}
function handleMouseMove(e) {
if (!isDown) {
return;
}
mouseX = parseInt(e.clientX - offsetX);
mouseY = parseInt(e.clientY - offsetY);
var dx = mouseX - cx;
var dy = mouseY - cy;
var angle = Math.atan2(dy, dx);
r = angle;
draw();
}
$("#canvas").mousedown(function (e) {
handleMouseDown(e);
});
$("#canvas").mousemove(function (e) {
handleMouseMove(e);
});
$("#canvas").mouseup(function (e) {
handleMouseUp(e);
});
$("#canvas").mouseout(function (e) {
handleMouseOut(e);
})
;
I need to work scaling with rotation of image. ie) Four anchor points with rotating handle
Related
I've been trying to drag and resize the same image inside my canvas but i am not able to successfully do that
I've selected the dragging codes from the first link and resizing codes from the second link but while combining those codes the final output has some errors and issues. I have also added an upload image button in which the user can choose the image to be uploaded to the canvas from a local directory, that was working properly
$(function () {
$('#file-input').change(function (e) {
var file = e.target.files[0],
imageType = /image.*/;
if (!file.type.match(imageType))
return;
var reader = new FileReader();
reader.onload = fileOnload;
reader.readAsDataURL(file);
});
function fileOnload(e) {
var $img = $('<img>', { src: e.target.result });
var canvas = $('#canvas')[0];
var context = canvas.getContext('2d');
$img.load(function () {
context.drawImage(this, 0, 0, canvas.width, canvas.height);
fileResize();
});
}
function fileResize() {
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var canvasOffset = $("#canvas").offset();
var offsetX = canvasOffset.left;
var offsetY = canvasOffset.top;
var startX;
var startY;
var isDown = false;
// var pi2 = Math.PI * 2;
var resizerRadius = 10;
var rr = resizerRadius * resizerRadius ;
var imageX = 0;
var imageY = 0;
var imageWidth, imageHeight, imageRight, imageBottom;
var draggingImage = false;
var img = new Image();
var draggingResizer = {
x: 0,
y: 0
};
img.onload = function () {
imageWidth = img.width;
imageHeight = img.height;
imageRight = imageX + imageWidth;
imageBottom = imageY + imageHeight;
iOrientation = (imageWidth >= imageHeight) ? "Wide" : "Tall";
draw(true, true);
}
img.src = canvas.toDataURL();
var border = 8;
var isLeft = false;
var isRight = false;
var isTop = false;
var isBottom = false;
var iAnchor;
canvas.onmousedown = handleMousedown;
canvas.onmousemove = handleMousemove;
canvas.onmouseup = handleMouseup;
canvas.onmouseout = handleMouseup;
function draw(withAnchors, withBorders) {
var cx = imageX + (imageRight - imageX) / 2;
var cy = imageY + (imageBottom - imageY) / 2;
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.drawImage(img, imageX, imageY, imageRight - imageX, imageBottom - imageY);
ctx.setLineDash([10, 15]);
ctx.strokeStyle = "#000";
ctx.stroke();
if (withAnchors) {
ctx.fillRect(imageX, imageY, border, border);
ctx.fillRect(imageRight - border, imageY, border, border);
ctx.fillRect(imageRight - border, imageBottom - border, border, border);
ctx.fillRect(imageX, imageBottom - border, border, border);
ctx.fillRect(cx, imageY, border, border);
ctx.fillRect(cx, imageBottom - border, border, border);
ctx.fillRect(imageX, cy, border, border);
ctx.fillRect(imageRight - border, cy, border, border);
}
if (withBorders) {
ctx.beginPath();
ctx.moveTo(imageX, imageY);
ctx.lineTo(imageRight, imageY);
ctx.lineTo(imageRight, imageBottom);
ctx.lineTo(imageX, imageBottom);
ctx.closePath();
ctx.stroke();
}}
function hitResizeAnchor(x, y) {
// which borders are under the mouse
isLeft = (x > imageX && x < imageX + border);
isRight = (x < imageRight && x > imageRight - border);
isTop = (y > imageY && y < imageY + border);
isBottom = (y < imageBottom && y > imageBottom - border);
// return the appropriate anchor
if (isTop && isLeft) {
return (iOrientation + "TL");
}
if (isTop && isRight) {
return (iOrientation + "TR");
}
if (isBottom && isLeft) {
return (iOrientation + "BL");
}
if (isBottom && isRight) {
return (iOrientation + "BR");
}
if (isTop) {
return ("T");
}
if (isRight) {
return ("R");
}
if (isBottom) {
return ("B");
}
if (isLeft) {
return ("L");
}
return ("null");
}
var resizeFunctions = {
T: function (x, y) {
imageY = y;
canvas.style.cursor = "n-resize";
},
R: function (x, y) {
imageRight = x;
},
B: function (x, y) {
imageBottom = y;
},
L: function (x, y) {
imageX = x;
},
WideTR: function (x, y) {
imageRight = x;
imageY = imageBottom - (imageHeight * (imageRight - imageX) / imageWidth);
},
TallTR: function (x, y) {
imageY = y;
imageRight = imageX + (imageWidth * (imageBottom - imageY) / imageHeight);
},
WideBR: function (x, y) {
imageRight = x;
imageBottom = imageY + (imageHeight * (imageRight - imageX) / imageWidth);
},
TallBR: function (x, y) {
imageBottom = y;
imageRight = imageX + (imageWidth * (imageBottom - imageY) / imageHeight);
},
WideBL: function (x, y) {
imageX = x;
imageBottom = imageY + (imageHeight * (imageRight - imageX) / imageWidth);
},
TallBL: function (x, y) {
imageBottom = y;
imageX = imageRight - (imageWidth * (imageBottom - imageY) / imageHeight);
},
WideTL: function (x, y) {
imageX = x;
imageY = imageBottom - (imageHeight * (imageRight - imageX) / imageWidth);
},
TallTL: function (x, y) {
imageBottom = y;
imageX = imageRight - (imageWidth * (imageBottom - imageY) / imageHeight);
}
};
function hitImage(x, y) {
return (x > imageX && x < imageX + imageWidth && y > imageY && y < imageY + imageHeight);
}
function handleMousedown(e) {
e.preventDefault();
e.stopPropagation();
canvas.style.cursor = "move";
startX = parseInt(e.clientX - offsetX);
startY = parseInt(e.clientY - offsetY);
var mouseX = e.clientX - offsetX;
var mouseY = e.clientY - offsetY;
iAnchor = hitResizeAnchor(mouseX, mouseY);
isDown = (iAnchor);
draggingImage = hitImage(startX, startY);
}
function handleMouseup(e) {
canvas.style.cursor = "default";
e.preventDefault();
e.stopPropagation();
draggingImage = false;
isDown = false;
draw(true);
}
function handleMousemove(e) {
e.preventDefault();
e.stopPropagation();
if (isDown) {
var mouseX = e.clientX - offsetX;
var mouseY = e.clientY - offsetY;
resizeFunctions[iAnchor](mouseX, mouseY);
draw(false);
}
if (draggingImage) {
canvas.style.cursor = "move";
imageClick = false;
mouseX = parseInt(e.clientX - offsetX);
mouseY = parseInt(e.clientY - offsetY);
var dx = mouseX - startX;
var dy = mouseY - startY;
imageX += dx;
imageY += dy;
imageRight += dx;
imageBottom += dy;
startX = mouseX;
startY = mouseY;
draw(false, true);
}
}
function handleMouseOut(e) {
handleMouseUp(e);
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<head>
<title>Upload to Canvas</title>
<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript" src="demo-uploader.js"></script>
</head>
<body>
<input type="file" id="file-input" accept=".jpg,.png,.gif.,svg">
<canvas id="canvas" width="600" height="400" style=" border: solid thin #232323;"></canvas>
</body>
</html>
I can upload an image into the canvas and being able to resize and move it around. Now i want to apply the image into the canvas when i'm done moving it, for example, when i press the 'enter' key or something else (can be any other solution), so that i can upload another image and place it alongside the previous one.
This is what i have:
Fiddle
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var canvasOffset = $("#canvas").offset();
var offsetX = canvasOffset.left;
var offsetY = canvasOffset.top;
var startX;
var startY;
var isDown = false;
var pi2 = Math.PI * 2;
var resizerRadius = 8;
var rr = resizerRadius * resizerRadius;
var draggingResizer = {
x: 0,
y: 0
};
var imageX = 50;
var imageY = 50;
var imageWidth, imageHeight, imageRight, imageBottom;
var draggingImage = false;
var startX;
var startY;
function el(id){return document.getElementById(id);}
var img = new Image();
function readImage() {
if ( this.files && this.files[0] ) {
var FR= new FileReader();
FR.onload = function(e) {
img = new Image();
img.onload = function() {
imageWidth = img.width;
imageHeight = img.height;
imageRight = imageX + imageWidth;
imageBottom = imageY + imageHeight
draw(true, false);
};
img.src = e.target.result;
};
FR.readAsDataURL( this.files[0] );
}
}
el("fileUpload").addEventListener("change", readImage, false);
function draw(withAnchors, withBorders) {
// clear the canvas
ctx.clearRect(0, 0, canvas.width, canvas.height);
// draw the image
ctx.drawImage(img, 0, 0, img.width, img.height, imageX, imageY, imageWidth, imageHeight);
// optionally draw the draggable anchors
if (withAnchors) {
drawDragAnchor(imageX, imageY);
drawDragAnchor(imageRight, imageY);
drawDragAnchor(imageRight, imageBottom);
drawDragAnchor(imageX, imageBottom);
}
// optionally draw the connecting anchor lines
if (withBorders) {
ctx.beginPath();
ctx.moveTo(imageX, imageY);
ctx.lineTo(imageRight, imageY);
ctx.lineTo(imageRight, imageBottom);
ctx.lineTo(imageX, imageBottom);
ctx.closePath();
ctx.stroke();
}
}
function drawDragAnchor(x, y) {
ctx.beginPath();
ctx.arc(x, y, resizerRadius, 0, pi2, false);
ctx.closePath();
ctx.fill();
}
function anchorHitTest(x, y) {
var dx, dy;
// top-left
dx = x - imageX;
dy = y - imageY;
if (dx * dx + dy * dy <= rr) {
return (0);
}
// top-right
dx = x - imageRight;
dy = y - imageY;
if (dx * dx + dy * dy <= rr) {
return (1);
}
// bottom-right
dx = x - imageRight;
dy = y - imageBottom;
if (dx * dx + dy * dy <= rr) {
return (2);
}
// bottom-left
dx = x - imageX;
dy = y - imageBottom;
if (dx * dx + dy * dy <= rr) {
return (3);
}
return (-1);
}
function hitImage(x, y) {
return (x > imageX && x < imageX + imageWidth && y > imageY && y < imageY + imageHeight);
}
function handleMouseDown(e) {
startX = parseInt(e.clientX - offsetX);
startY = parseInt(e.clientY - offsetY);
draggingResizer = anchorHitTest(startX, startY);
draggingImage = draggingResizer < 0 && hitImage(startX, startY);
}
function handleMouseUp(e) {
draggingResizer = -1;
draggingImage = false;
draw(true, false);
}
function handleMouseOut(e) {
handleMouseUp(e);
}
function handleMouseMove(e) {
if (draggingResizer > -1) {
mouseX = parseInt(e.clientX - offsetX);
mouseY = parseInt(e.clientY - offsetY);
// resize the image
switch (draggingResizer) {
case 0:
//top-left
imageX = mouseX;
imageWidth = imageRight - mouseX;
imageY = mouseY;
imageHeight = imageBottom - mouseY;
break;
case 1:
//top-right
imageY = mouseY;
imageWidth = mouseX - imageX;
imageHeight = imageBottom - mouseY;
break;
case 2:
//bottom-right
imageWidth = mouseX - imageX;
imageHeight = mouseY - imageY;
break;
case 3:
//bottom-left
imageX = mouseX;
imageWidth = imageRight - mouseX;
imageHeight = mouseY - imageY;
break;
}
if(imageWidth<25){imageWidth=25;}
if(imageHeight<25){imageHeight=25;}
// set the image right and bottom
imageRight = imageX + imageWidth;
imageBottom = imageY + imageHeight;
// redraw the image with resizing anchors
draw(true, true);
} else if (draggingImage) {
imageClick = false;
mouseX = parseInt(e.clientX - offsetX);
mouseY = parseInt(e.clientY - offsetY);
// move the image by the amount of the latest drag
var dx = mouseX - startX;
var dy = mouseY - startY;
imageX += dx;
imageY += dy;
imageRight += dx;
imageBottom += dy;
// reset the startXY for next time
startX = mouseX;
startY = mouseY;
// redraw the image with border
draw(false, true);
}
}
$("#canvas").mousedown(function (e) {
handleMouseDown(e);
});
$("#canvas").mousemove(function (e) {
handleMouseMove(e);
});
$("#canvas").mouseup(function (e) {
handleMouseUp(e);
});
$("#canvas").mouseout(function (e) {
handleMouseOut(e);
});
Thanks.
Don't overthink it.
Edited your fiddle here: https://jsfiddle.net/mrqhpgnk/4/
Create an array to store old images:
var myOldImagesArray = [];
var atLeastOneImage = false;
Update in the readImage function:
var img;
function readImage() {
if ( this.files && this.files[0] ) {
var FR= new FileReader();
FR.onload = function(e) {
if(atLeastOneImage) {
myOldImagesArray.push({
image: img, X: imageX, Y: imageY,
width: imageWidth, height: imageHeight
});
}
var img2 = new Image();
img2.onload = function() {
imageWidth = img2.width;
imageHeight = img2.height;
imageRight = imageX + imageWidth;
imageBottom = imageY + imageHeight
draw(true, false);
};
img2.src = e.target.result;
img = img2;
atLeastOneImage = true;
};
FR.readAsDataURL( this.files[0] );
}
}
Don't forget to draw the old images while in your draw function.
for(var i=0; i<myOldImagesArray.length; i++) {
var oldImageDict = myOldImagesArray[i];
var oldImage = oldImageDict.image;
ctx.drawImage(oldImage, 0, 0, oldImage.width, oldImage.height, oldImageDict.X, oldImageDict.Y, oldImageDict.width, oldImageDict.height);
}
I used a dictionary for the array type, since you seem to have a lot of variables pertaining to the image itself.
Also, make sure img is fresh. Not sure if would have worked, if had not created new variable var img2 = new Image(); But seemed like could possibly have caused a problem, so just went ahead with my instincts there.
I uploaded an image to canvas and make it movable and resizable now I want to make it as background image after the user adjusted that image so that I can write text over it and make the text movable.
What should I do to make it as background image?
I have written a jquery script
$("#continueToCanvas").click(function(){
window.close();
window.open("./canvas.html","new ","width=1000,height=600");
});
function canvasImage(){
/*var x=document.getElementById('canvas');
canvas=x.getContext('2d');
var pic = new Image();
pic.src=localStorage.getItem('imgData');
pic.addEventListener("load",function(){canvas.drawImage(pic,0,0,x.width,x.height)},false);
}
window.addEventListener("load",canvasImage,false);*/
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var canvasOffset = $("#canvas").offset();
var offsetX = canvasOffset.left;
var offsetY = canvasOffset.top;
var startX;
var startY;
var isDown = false;
var pi2 = Math.PI * 2;
var resizerRadius = 8;
var rr = resizerRadius * resizerRadius;
var draggingResizer = {
x: 0,
y: 0
};
var imageX = 50;
var imageY = 50;
var imageWidth, imageHeight, imageRight, imageBottom;
var draggingImage = false;
var startX;
var startY;
var img = new Image();
img.onload = function () {
imageWidth = img.width;
imageHeight = img.height;
imageRight = imageX + imageWidth;
imageBottom = imageY + imageHeight
draw(true, false);
}
img.src = localStorage.getItem('imgData');
function draw(withAnchors, withBorders) {
// clear the canvas
var abc=document.getElementById("canvasTextInput").value;
var f= document.getElementById("fnt").value + "px";
ctx.font=f + " Georgia";
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.fillText(abc,200,200);
// draw the image
ctx.drawImage(img, 0, 0, img.width, img.height, imageX, imageY, imageWidth, imageHeight);
// optionally draw the draggable anchors
if (withAnchors) {
drawDragAnchor(imageX, imageY);
drawDragAnchor(imageRight, imageY);
drawDragAnchor(imageRight, imageBottom);
drawDragAnchor(imageX, imageBottom);
}
// optionally draw the connecting anchor lines
if (withBorders) {
ctx.beginPath();
ctx.moveTo(imageX, imageY);
ctx.lineTo(imageRight, imageY);
ctx.lineTo(imageRight, imageBottom);
ctx.lineTo(imageX, imageBottom);
ctx.closePath();
ctx.stroke();
}
}
function drawDragAnchor(x, y) {
ctx.beginPath();
ctx.arc(x, y, resizerRadius, 0, pi2, false);
ctx.closePath();
ctx.fill();
}
function anchorHitTest(x, y) {
var dx, dy;
// top-left
dx = x - imageX;
dy = y - imageY;
if (dx * dx + dy * dy <= rr) {
return (0);
}
// top-right
dx = x - imageRight;
dy = y - imageY;
if (dx * dx + dy * dy <= rr) {
return (1);
}
// bottom-right
dx = x - imageRight;
dy = y - imageBottom;
if (dx * dx + dy * dy <= rr) {
return (2);
}
// bottom-left
dx = x - imageX;
dy = y - imageBottom;
if (dx * dx + dy * dy <= rr) {
return (3);
}
return (-1);
}
function hitImage(x, y) {
return (x > imageX && x < imageX + imageWidth && y > imageY && y < imageY + imageHeight);
}
function handleMouseDown(e) {
startX = parseInt(e.clientX - offsetX);
startY = parseInt(e.clientY - offsetY);
draggingResizer = anchorHitTest(startX, startY);
draggingImage = draggingResizer < 0 && hitImage(startX, startY);
}
function handleMouseUp(e) {
draggingResizer = -1;
draggingImage = false;
draw(true, false);
}
function handleMouseOut(e) {
handleMouseUp(e);
}
function handleMouseMove(e) {
if (draggingResizer > -1) {
mouseX = parseInt(e.clientX - offsetX);
mouseY = parseInt(e.clientY - offsetY);
// resize the image
switch (draggingResizer) {
case 0:
//top-left
imageX = mouseX;
imageWidth = imageRight - mouseX;
imageY = mouseY;
imageHeight = imageBottom - mouseY;
break;
case 1:
//top-right
imageY = mouseY;
imageWidth = mouseX - imageX;
imageHeight = imageBottom - mouseY;
break;
case 2:
//bottom-right
imageWidth = mouseX - imageX;
imageHeight = mouseY - imageY;
break;
case 3:
//bottom-left
imageX = mouseX;
imageWidth = imageRight - mouseX;
imageHeight = mouseY - imageY;
break;
}
if(imageWidth<25){imageWidth=25;}
if(imageHeight<25){imageHeight=25;}
// set the image right and bottom
imageRight = imageX + imageWidth;
imageBottom = imageY + imageHeight;
// redraw the image with resizing anchors
draw(true, true);
} else if (draggingImage) {
imageClick = false;
mouseX = parseInt(e.clientX - offsetX);
mouseY = parseInt(e.clientY - offsetY);
// move the image by the amount of the latest drag
var dx = mouseX - startX;
var dy = mouseY - startY;
imageX += dx;
imageY += dy;
imageRight += dx;
imageBottom += dy;
// reset the startXY for next time
startX = mouseX;
startY = mouseY;
// redraw the image with border
draw(false, true);
}
}
$("#canvas").mousedown(function (e) {
handleMouseDown(e);
});
$("#canvas").mousemove(function (e) {
handleMouseMove(e);
});
$("#canvas").mouseup(function (e) {
handleMouseUp(e);
});
$("#canvas").mouseout(function (e) {
handleMouseOut(e);
});
}
window.addEventListener("load",canvasImage,false);
and now I want to put text over it which is also movable
I have this [sample][1], what I want is to have this result[![enter image description here][2]][2]
Note:
a.) 1 and 2 will be connected while 3 will be produced in the third mousedown click.
b.) 1,2,3 should be declared continously.
c.) 1 and 2 can be extend for the width
d.) 3 should be extend for the height.
e.) 1,2,3 should be drag as a whole (all together).
f.) The pattern of declaration is 1 to 2 (horizontally) and 2 to 3 (vertical).
function handleMouseDown(e){
// tell the browser we're handling this event
e.preventDefault();
e.stopPropagation();
startX=parseInt(e.clientX-offsetX);
startY=parseInt(e.clientY-offsetY);
draggingIndex=-1;
for(var i=0;i<anchors.length;i++){
var a=anchors[i];
var dx=startX-a.x;
var dy=startY-a.y;
if(dx*dx+dy*dy<radius*radius){
draggingIndex=i;
break;
}
}
//Detect if we're on a line:
fullDrag = mouseOnLine({x:startX, y: startY});
// If a drag hasn't started, add another anchor here
if(draggingIndex==-1 && fullDrag == null){
addAnchor(startX,startY);
var al = anchors.length-1;
var almod4 = al%2;
if(almod4==1){
connectors.push({start:al-1,end:al});
}
if(almod4==2){
connectors.push({start:al-2,end:al});
connectors.push({start:al-1,end:al});
}
draw();
}
}
I think, you can use the slope with the actual mouse point. The delta is only used by half.
deltaX = (anchors[al - 1].x - anchors[al].x) / 2;
deltaY = (anchors[al - 1].y - anchors[al].y) / 2;
ctx.strokeStyle = 'purple';
ctx.beginPath();
ctx.moveTo(mouseX - deltaX, mouseY - deltaY);
ctx.lineTo(mouseX + deltaX, mouseY + deltaY);
ctx.stroke();
Working example:
var canvas = document.getElementById("canvas"),
ctx = canvas.getContext("2d"),
cw = canvas.width,
ch = canvas.height,
mouseX, mouseY,
offsetX, offsetY,
startX, startY,
radius = 5,
nextLetter = 0,
anchors = [],
connectors = [],
draggingIndex = -1,
fullDrag = null;
reOffset();
window.onscroll = function (e) { reOffset(); }
window.onresize = function (e) { reOffset(); }
function reOffset() {
var BB = canvas.getBoundingClientRect();
offsetX = BB.left;
offsetY = BB.top;
}
function addAnchor(x, y) {
anchors.push({
x: x,
y: y,
});
}
draw();
$("#canvas").mousedown(function (e) { handleMouseDown(e); });
$("#canvas").mousemove(function (e) { handleMouseMove(e); });
$("#canvas").mouseup(function (e) { handleMouseUpOut(e); });
$("#canvas").mouseout(function (e) { handleMouseUpOut(e); });
$("#clear").click(function () {
ctx.clearRect(0, 0, canvas.width, canvas.height);
anchors = [];
connectors = [];
});
function draw() {
var deltaX, deltaY;
var al = anchors.length - 1;
//
ctx.clearRect(0, 0, cw, ch);
ctx.strokeStyle = 'black';
// draw connecting lines
for (var i = 0; i < connectors.length; i++) {
var c = connectors[i];
var s = anchors[c.start];
var e = anchors[c.end];
ctx.beginPath();
ctx.moveTo(s.x, s.y);
ctx.lineTo(e.x, e.y);
ctx.stroke();
//alert(anchors.length);
}
//draw lines
if (anchors.length > 0 && anchors.length % 3 > 0) {
ctx.strokeStyle = 'grey';
var almod4 = al % 2;
if (almod4 == 1 || almod4 == 2) {
//draw extra line
ctx.beginPath();
ctx.moveTo(anchors[al - 1].x, anchors[al - 1].y);
ctx.lineTo(mouseX, mouseY);
ctx.stroke();
// part for parallel line
deltaX = (anchors[al - 1].x - anchors[al].x) / 2;
deltaY = (anchors[al - 1].y - anchors[al].y) / 2;
ctx.strokeStyle = 'purple';
ctx.beginPath();
ctx.moveTo(mouseX - deltaX, mouseY - deltaY);
ctx.lineTo(mouseX + deltaX, mouseY + deltaY);
ctx.stroke();
}
ctx.strokeStyle = 'grey';
ctx.beginPath();
ctx.moveTo(anchors[al].x, anchors[al].y);
ctx.lineTo(mouseX, mouseY);
ctx.stroke();
}
// draw circles
for (var i = 0; i < anchors.length; i++) {
ctx.beginPath();
ctx.arc(anchors[i].x, anchors[i].y, radius, 0, Math.PI * 2);
ctx.fill();
}
}
function handleMouseDown(e) {
// tell the browser we're handling this event
e.preventDefault();
e.stopPropagation();
startX = parseInt(e.clientX - offsetX);
startY = parseInt(e.clientY - offsetY);
draggingIndex = -1;
for (var i = 0; i < anchors.length; i++) {
var a = anchors[i];
var dx = startX - a.x;
var dy = startY - a.y;
if (dx * dx + dy * dy < radius * radius) {
draggingIndex = i;
break;
}
}
//Detect if we're on a line:
fullDrag = mouseOnLine({ x: startX, y: startY });
// If a drag hasn't started, add another anchor here
if (draggingIndex == -1 && fullDrag == null) {
addAnchor(startX, startY);
var al = anchors.length - 1;
var almod4 = al % 2;
if (almod4 == 1) {
connectors.push({ start: al - 1, end: al });
}
if (almod4 == 2) {
connectors.push({ start: al - 2, end: al });
connectors.push({ start: al - 1, end: al });
}
draw();
}
}
function handleMouseUpOut(e) {
// tell the browser we're handling this event
e.preventDefault();
e.stopPropagation();
mouseX = parseInt(e.clientX - offsetX);
mouseY = parseInt(e.clientY - offsetY);
draggingIndex = -1;
fullDrag = null;
}
function handleMouseMove(e) {
//if(draggingIndex<0 && fullDrag == null){return;}
mouseX = parseInt(e.clientX - offsetX);
mouseY = parseInt(e.clientY - offsetY);
if (draggingIndex >= 0) {
// tell the browser we're handling this event
e.preventDefault();
e.stopPropagation();
var a = anchors[draggingIndex];
a.x += (mouseX - startX);
a.y += (mouseY - startY);
startX = mouseX;
startY = mouseY;
} else if (fullDrag != null) {
var startPoints = Math.floor(fullDrag.start / 4) * 4;
for (var i = 0; i < 2; i++) {
anchors[startPoints + i].x += (mouseX - startX);
anchors[startPoints + i].y += (mouseY - startY);
}
startX = mouseX;
startY = mouseY;
}
draw();
}
function mouseOnLine(mousePos) {
var i, pA, pB, first, second;
for (i = 0 ; i < connectors.length; i++) {
pA = anchors[connectors[i].start];
pB = anchors[connectors[i].end];
first = distanceBetween(pA, mousePos) + distanceBetween(pB, mousePos);
second = distanceBetween(pA, pB);
if (Math.abs(first - second) < 0.3) {
return connectors[i];
}
}
return null;
}
var distanceBetween = function (point1, point2) {
var distX = Math.abs(point1.x - point2.x);
var distY = Math.abs(point1.y - point2.y);
return Math.sqrt((distX * distX) + (distY * distY));
}
#canvas{border:1px solid red; }
<script src="http://code.jquery.com/jquery-2.1.4.min.js"></script>
<canvas id="canvas" width=500 height=500></canvas>
So I resizing a image using canvas. WHat happens is that is always resizes from the same point with is (0, 0). I want it to change it's pivot/origin according to which anchor is selected to resize. Which means if _ is selected:
Bottom-Left -> Top-Right
Bottom-Center -> Top-Center
Bottom-Right -> Top-Left
Top-Left -> Bottom-Right
Top-Center -> Bottom-Center
Top-Right -> Bottom-RIght
Left -> Right
RIght -> Left
Here's what's happening now: http://jsfiddle.net/mareebsiddiqui/2Gtq9/3
Here's my JS:
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
//var canvasOffset = $("#canvas").offset();
var offsetX = canvas.offsetLeft;
var offsetY = canvas.offsetTop;
var startX;
var startY;
var isDown = false;
var pi2 = Math.PI * 2;
var resizerRadius = 8;
var rr = resizerRadius * resizerRadius;
var draggingResizer = {
x: 0,
y: 0
};
var imageX = 50;
var imageY = 50;
var imageWidth, imageHeight, imageRight, imageBottom;
var draggingImage = false;
var startX;
var startY;
var img = new Image();
img.onload = function () {
imageWidth = img.width;
imageHeight = img.height;
imageRight = imageX + imageWidth;
imageBottom = imageY + imageHeight
draw(true, false);
}
img.src = 'img/' + localStorage["bgimgname"];
function draw(withAnchors, withBorders) {
// clear the canvas
ctx.clearRect(0, 0, canvas.width, canvas.height);
// draw the image
ctx.drawImage(img, 0, 0, img.width, img.height, imageX, imageY, imageWidth, imageHeight);
// optionally draw the draggable anchors
if (withAnchors) {
drawDragAnchor(imageX, imageY); //topleft
drawDragAnchor((imageRight+imageX)/2, imageY); //topcenter
drawDragAnchor(imageRight, imageY); //topright
drawDragAnchor(imageX, (imageBottom+imageY)/2); //left
drawDragAnchor(imageRight, (imageBottom+imageY)/2); //right
drawDragAnchor(imageX, imageBottom); //bottomleft
drawDragAnchor((imageRight+imageX)/2, imageBottom); //bottom center
drawDragAnchor(imageRight, imageBottom); //bottomright
}
}
function drawDragAnchor(x, y) {
ctx.beginPath();
ctx.arc(x, y, resizerRadius, 0, pi2, false);
ctx.closePath();
ctx.fill();
}
function anchorHitTest(x, y) {
var dx, dy;
// top-left
dx = x - imageX;
dy = y - imageY;
if (dx * dx + dy * dy <= rr) {
return (0);
}
// top-center
dx = x - (imageRight+imageX)/2
dy = y - imageY
if (dx/2 * dx/2 + dy * dy <= rr) {
return (1);
}
// top-right
dx = x - imageRight;
dy = y - imageY;
if (dx * dx + dy * dy <= rr) {
return (2);
}
//left
dx = x - imageX;
dy = y - (imageBottom+imageY)/2
if (dx * dx + dy/2 * dy/2 <= rr) {
return (3);
}
//right
dx = x - imageRight;
dy = y - (imageBottom+imageY)/2
if (dx * dx + dy/2 * dy/2 <= rr) {
return (4);
}
// bottom-left
dx = x - imageX;
dy = y - imageBottom;
if (dx * dx + dy * dy <= rr) {
return (5);
}
// bottom-center
dx = x - (imageRight+imageX)/2;
dy = y - imageBottom;
if (dx/2 * dx/2 + dy * dy <= rr) {
return (6);
}
// bottom-right
dx = x - imageRight;
dy = y - imageBottom;
if (dx * dx + dy * dy <= rr) {
return (7);
}
return (-1);
}
function hitImage(x, y) {
return (x > imageX && x < imageX + imageWidth && y > imageY && y < imageY + imageHeight);
}
function handleMouseDown(e) {
startX = parseInt(e.clientX - offsetX);
startY = parseInt(e.clientY - offsetY);
draggingResizer = anchorHitTest(startX, startY);
draggingImage = draggingResizer < 0 && hitImage(startX, startY);
}
function handleMouseUp(e) {
draggingResizer = -1;
draggingImage = false;
draw(true, false);
}
function handleMouseOut(e) {
handleMouseUp(e);
}
function handleMouseMove(e) {
e = window.event;
if (draggingResizer > -1) {
mouseX = parseInt(e.clientX - offsetX);
mouseY = parseInt(e.clientY - offsetY);
// resize the image
switch (draggingResizer) {
case 0:
//top-left
console.log("topleft");
imageHeight -= imageRight - mouseY;
imageWidth -= imageRight - mouseY;
break;
case 1:
//top-center
console.log("topcenter");
imageHeight -= imageBottom - mouseY;
break;
case 2:
//top-right
console.log("topright");
imageHeight -= imageBottom - mouseY;
imageWidth -= imageBottom - mouseY;
break;
case 3:
//left
console.log("left");
imageWidth -= imageX - mouseX;
break;
case 4:
//right
console.log("right");
imageWidth -= imageRight - mouseX;
break;
case 5:
//bottom-left
console.log("bottomleft");
imageHeight -= imageRight - mouseY;
imageWidth -= imageRight - mouseY;
break;
case 6:
//center
console.log("bottomcenter");
imageHeight -= imageBottom - mouseY;
break;
case 7:
//bottom-right
console.log("bottomright");
imageHeight -= imageBottom - mouseY;
imageWidth -= imageBottom - mouseY;
break;
}
if(imageWidth<25){imageWidth=25;}
if(imageHeight<25){imageHeight=25;}
if(imageWidth>700){imageWidth=700;}
if(imageHeight>700){imageHeight=700;}
// set the image right and bottom
imageRight = imageX + imageWidth;
imageBottom = imageY + imageHeight;
// redraw the image with resizing anchors
draw(true, true);
}
}
canvas.addEventListener('mousedown', handleMouseDown);
canvas.addEventListener('mousemove', handleMouseMove);
canvas.addEventListener('mouseup', handleMouseUp);
canvas.addEventListener('mouseout', handleMouseOut);
Please help me out. :(
One efficient way of resizing as you desire is to keep the opposite side(s) position fixed and let the selected side float with a dragging side or corner.
A side benefit of this method is that you don't really need the anchors!
This is the way operating system windows work.
When resizing windows you don't have visible anchors to drag, you just drag the side or corner of the window.
A Demo: http://jsfiddle.net/m1erickson/keZ82/
Left: original image,
Middle: resize from bottom-left corner & maintain aspect ratio (top-right corner remains fixed)
Right: resize from bottom & image scales in y direction only (top of image remains fixed)
Note: this Demo and example display anchors but they are strictly cosmetic. You can turn the anchor display off and still resize the image by dragging a side or corner of the image.
Example code:
<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" media="all" href="css/reset.css" /> <!-- reset css -->
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<style>
body{ background-color: ivory; }
canvas{border:1px solid red;}
</style>
<script>
$(function(){
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var $canvas=$("#canvas");
var canvasOffset=$canvas.offset();
var offsetX=canvasOffset.left;
var offsetY=canvasOffset.top;
var isDown=false;
var iW;
var iH;
var iLeft=50;
var iTop=50;
var iRight,iBottom,iOrientation;
var img=new Image();
img.onload=function(){
iW=img.width;
iH=img.height;
iRight=iLeft+iW;
iBottom=iTop+iH;
iOrientation=(iW>=iH)?"Wide":"Tall";
draw(true);
}
img.src="facesSmall.png";
var border=10;
var isLeft=false;
var isRight=false;
var isTop=false;
var isBottom=false;
var iAnchor;
canvas.onmousedown=handleMousedown;
canvas.onmousemove=handleMousemove;
canvas.onmouseup=handleMouseup;
canvas.onmouseout=handleMouseup;
function hitResizeAnchor(x,y){
// which borders are under the mouse
isLeft=(x>iLeft && x<iLeft+border);
isRight=(x<iRight && x>iRight-border);
isTop=(y>iTop && y<iTop+border);
isBottom=(y<iBottom && y>iBottom-border);
// return the appropriate anchor
if(isTop && isLeft){ return(iOrientation+"TL"); }
if(isTop && isRight){ return(iOrientation+"TR"); }
if(isBottom && isLeft){ return(iOrientation+"BL"); }
if(isBottom && isRight){ return(iOrientation+"BR"); }
if(isTop){ return("T"); }
if(isRight){ return("R"); }
if(isBottom){ return("B"); }
if(isLeft){ return("L"); }
return(null);
}
var resizeFunctions={
T: function(x,y){ iTop=y; },
R: function(x,y){ iRight=x; },
B: function(x,y){ iBottom=y; },
L: function(x,y){ iLeft=x; },
WideTR: function(x,y){
iRight=x;
iTop=iBottom-(iH*(iRight-iLeft)/iW);
},
TallTR: function(x,y){
iTop=y;
iRight=iLeft+(iW*(iBottom-iTop)/iH);
},
WideBR: function(x,y){
iRight=x;
iBottom=iTop+(iH*(iRight-iLeft)/iW);
},
TallBR: function(x,y){
iBottom=y;
iRight=iLeft+(iW*(iBottom-iTop)/iH);
},
WideBL: function(x,y){
iLeft=x;
iBottom=iTop+(iH*(iRight-iLeft)/iW);
},
TallBL: function(x,y){
iBottom=y;
iLeft=iRight-(iW*(iBottom-iTop)/iH);
},
WideTL: function(x,y){
iLeft=x;
iTop=iBottom-(iH*(iRight-iLeft)/iW);
},
TallTL: function(x,y){
iBottom=y;
iLeft=iRight-(iW*(iBottom-iTop)/iH);
}
};
function handleMousedown(e){
// tell the browser we'll handle this mousedown
e.preventDefault();
e.stopPropagation();
var mouseX=e.clientX-offsetX;
var mouseY=e.clientY-offsetY;
iAnchor=hitResizeAnchor(mouseX,mouseY);
isDown=(iAnchor);
}
function handleMouseup(e){
// tell the browser we'll handle this mouseup
e.preventDefault();
e.stopPropagation();
isDown=false;
draw(true);
}
function handleMousemove(e){
// tell the browser we'll handle this mousemove
e.preventDefault();
e.stopPropagation();
// return if we're not dragging
if(!isDown){return;}
// get MouseX/Y
var mouseX=e.clientX-offsetX;
var mouseY=e.clientY-offsetY;
// reset iLeft,iRight,iTop,iBottom based on drag
resizeFunctions[iAnchor](mouseX,mouseY);
// redraw the resized image
draw(false);
}
function draw(withAnchors){
var cx=iLeft+(iRight-iLeft)/2;
var cy=iTop+(iBottom-iTop)/2;
ctx.clearRect(0,0,canvas.width,canvas.height);
ctx.drawImage(img,iLeft,iTop,iRight-iLeft,iBottom-iTop);
if(withAnchors){
ctx.fillRect(iLeft,iTop,border,border);
ctx.fillRect(iRight-border,iTop,border,border);
ctx.fillRect(iRight-border,iBottom-border,border,border);
ctx.fillRect(iLeft,iBottom-border,border,border);
ctx.fillRect(cx,iTop,border,border);
ctx.fillRect(cx,iBottom-border,border,border);
ctx.fillRect(iLeft,cy,border,border);
ctx.fillRect(iRight-border,cy,border,border);
}
}
}); // end $(function(){});
</script>
</head>
<body>
<h4>Drag image anchors</h4>
<canvas id="canvas" width=300 height=300></canvas>
</body>
</html>