Change origin of canvas drawn image - javascript

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>

Related

Shooting bullets from player towards mouse?

How do I shoot bullets from my Player X and Y towards the mouse x and y?
I can find the angle of the mouse X and Y but I have no idea how to create a bullet which will fly towards the mouse.
The code for the mouse coordinates are (dx, dy).
Also, if you could explain the logic behind what you did and how you did it, I would be greatful.
Thanks!
Fiddle
var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');
var pressingDown = false;
var pressingUp = false;
var pressingLeft = false;
var pressingRight = false;
var mouseX, mouseY;
function Player(x, y) {
this.x = x;
this.y = y;
this.angle;
}
Player.prototype.draw = function() {
context.save();
context.translate(this.x, this.y);
context.rotate(this.angle);
context.beginPath();
context.fillStyle = "green";
context.arc(0, 0, 30, 0, 2 * Math.PI);
context.fill();
context.fillStyle = "red";
context.fillRect(0, -10, 50, 20);
context.restore();
}
Player.prototype.update = function(mouseX, mouseY) {
var dx = mouseX - this.x;
var dy = mouseY - this.y;
this.angle = Math.atan2(dy, dx);
}
canvas.addEventListener('mousemove', mouseMove);
function mouseMove(evt) {
mouseX = evt.x;
mouseY = evt.y;
}
var player = new Player(350, 250);
function updatePlayer() {
context.clearRect(0, 0, canvas.width, canvas.height);
player.draw();
player.update(mouseX, mouseY);
updatePlayerPosition();
}
document.onkeydown = function(event) {
if (event.keyCode === 83) //s
pressingDown = true;
else if (event.keyCode === 87) //w
pressingUp = true;
else if (event.keyCode === 65) //a
pressingLeft = true;
else if (event.keyCode === 68) //d
pressingRight = true;
}
document.onkeyup = function(event) {
if (event.keyCode === 83) //s
pressingDown = false;
else if (event.keyCode === 87) //w
pressingUp = false;
else if (event.keyCode === 65) //a
pressingLeft = false;
else if (event.keyCode === 68) //d
pressingRight = false;
}
updatePlayerPosition = function() {
if (pressingRight)
player.x += 1;
if (pressingLeft)
player.x -= 1;
if (pressingDown)
player.y += 1;
if (pressingUp)
player.y -= 1;
}
function update() {
updatePlayer();
}
setInterval(update, 0)
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<style>
body {
background-color: black;
}
canvas {
position: absolute;
margin: auto;
left: 0;
right: 0;
border: solid 1px white;
border-radius: 10px;
}
</style>
</head>
<body>
<canvas id="canvas"></canvas>
<script type="application/javascript">
(function() {
"use strict";
var canvasWidth = 180;
var canvasHeight = 160;
var canvas = null;
var bounds = null;
var ctx = null;
var mouseX = 0.0;
var mouseY = 0.0;
var player = {
x: (canvasWidth * 0.5) | 0,
y: (canvasHeight * 0.5) | 0,
dx: 0.0,
dy: 0.0,
angle: 0.0,
radius: 17.5,
tick: function() {
this.angle = Math.atan2(mouseY - this.y,mouseX - this.x);
},
render: function() {
ctx.fillStyle = "darkred";
ctx.strokeStyle = "black";
ctx.translate(this.x,this.y);
ctx.rotate(this.angle);
ctx.beginPath();
ctx.moveTo(this.radius,0.0);
ctx.lineTo(-0.5 * this.radius,0.5 * this.radius);
ctx.lineTo(-0.5 * this.radius,-0.5 * this.radius);
ctx.lineTo(this.radius,0.0);
ctx.fill();
ctx.stroke();
ctx.rotate(-this.angle);
ctx.translate(-this.x,-this.y);
}
};
var bullet = {
x: (canvasWidth * 0.5) | 0,
y: (canvasHeight * 0.5) | 0,
dx: 0.0,
dy: 0.0,
radius: 5.0,
tick: function() {
this.x += this.dx;
this.y += this.dy;
if (this.x + this.radius < 0.0
|| this.x - this.radius > canvasWidth
|| this.y + this.radius < 0.0
|| this.y - this.radius > canvasHeight)
{
this.dx = 0.0;
this.dy = 0.0;
}
},
render: function() {
ctx.fillStyle = "darkcyan";
ctx.strokeStyle = "white";
ctx.beginPath();
ctx.arc(this.x,this.y,this.radius,0.0,2.0*Math.PI,false);
ctx.fill();
ctx.stroke();
}
};
function loop() {
// Tick
bullet.tick();
player.tick();
// Render
ctx.fillStyle = "gray";
ctx.fillRect(0,0,canvasWidth,canvasHeight);
bullet.render();
player.render();
//
requestAnimationFrame(loop);
}
window.onmousedown = function(e) {
// The mouse pos - the player pos gives a vector
// that points from the player toward the mouse
var x = mouseX - player.x;
var y = mouseY - player.y;
// Using pythagoras' theorm to find the distance (the length of the vector)
var l = Math.sqrt(x * x + y * y);
// Dividing by the distance gives a normalized vector whose length is 1
x = x / l;
y = y / l;
// Reset bullet position
bullet.x = player.x;
bullet.y = player.y;
// Get the bullet to travel towards the mouse pos with a new speed of 10.0 (you can change this)
bullet.dx = x * 10.0;
bullet.dy = y * 10.0;
}
window.onmousemove = function(e) {
mouseX = e.clientX - bounds.left;
mouseY = e.clientY - bounds.top;
}
window.onload = function() {
canvas = document.getElementById("canvas");
canvas.width = canvasWidth;
canvas.height = canvasHeight;
bounds = canvas.getBoundingClientRect();
ctx = canvas.getContext("2d");
loop();
}
})();
</script>
</body>
</html>
Moving from point to point.
Given two points p1 and p2, each point as a coordinate (x,y) and a speed value that is the number of pixels per step, there are two methods you can use to move between them.
Cartesian
Calculate the vector from p1 to p2
var vx = p2.x - p1.x;
var vy = p2.y - p1.y;
Then calculate the delta by getting the length of the vector, normalise it (make the vector 1 pixel long) then multiply by the speed
var dist = Math.sqrt(vx * vx + vy * vy);
var dx = vx / dist;
var dy = vy / dist;
dx *= speed;
dy *= speed;
This can be optimized a little by scaling the speed with the distance.
var scale = speed / Math.sqrt(vx * vx + vy * vy);
var dx = vx / dist;
var dy = vy / dist;
Polar
The other way is to get the direction from p1 to p2 and use that create the deltas
var dir = Math.atan2(p2.y - p1.y, p2.x - p1.x);
var dx = Math.cos(dir) * speed;
var dx = Math.sin(dir) * speed;
Animate
Once you have the delta you just need to update the position via addition.
const bullet = {x : p1.x, y : p1.y}; // set the bullet start pos
// then each frame add the delta
bullet.x += dx;
bullet.y += dy;
// draw the bullet

image resizing & Dragging inside a canvas

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>

Apply uploaded image into canvas after resizing/moving it around

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.

How to make an image as background in canvas

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

Scaling with rotating image using html5 canvas

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

Categories