Rectangle vertices coordinates using canvas rect - javascript

I'm trying to draw rectangle on canvas in this way:
<canvas id="canvas" height="893" width="1262"></canvas>
<div id="output"></div>
<script>
var canvasSizeX = 1262;
var canvasSizeY = 893;
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
ctx.globalAlpha = 0.5;
//Variables
var canvasx = $(canvas).offset().left;
var canvasy = $(canvas).offset().top;
var canvasybottom = $(canvas).offset().bottom;
var last_mousex = last_mousey = 0;
var mousex = mousey = 0;
var mousedown = false;
// points
var A;
var B;
var C;
var D;
//Mousedown
$(canvas).on('mousedown', function (e) {
last_mousex = parseInt(e.clientX - canvasx);
last_mousey = parseInt(e.clientY - canvasy);
mousedown = true;
});
//Mouseup
$(canvas).on('mouseup', function (e) {
mousedown = false;
});
//Mousemove
$(canvas).on('mousemove', function (e) {
mousex = parseInt(e.clientX - canvasx);
mousey = parseInt(e.clientY - canvasy);
if (mousedown) {
ctx.clearRect(0, 0, canvas.width, canvas.height); //clear canvas
ctx.beginPath();
var width = mousex - last_mousex;
var height = mousey - last_mousey;
ctx.rect(last_mousex, last_mousey, width, height);
ctx.strokeStyle = 'red';
ctx.lineWidth = 7;
ctx.stroke();
//
// Here I need the A, B, C and D values
//
}
//Output
$('#output').html('current: ' + mousex + ', ' + mousey + '<br/>last: ' + last_mousex + ', ' + last_mousey + '<br/>mousedown: ' + mousedown + '<br/>A: ' + A + '<br/>B: ' + B + '<br/>C: ' + C + '<br/>D: ' + D);
});
</script>
When the rect is drawn, I'd like to know the A, B, C and D (vertices) coordinates. On mousemove event actually I can get only the width the mouse X and mouse Y coordinates.
Is there a way to do it or I'm missing something?

Related

Can not drag objects in canvas when the latter is scrolled offscreen

I have taken a working jsFiddle with draggable battleships on a canvas and have just added some HTML paragraphs on top of it. Suddenly I can not drag the battleships anymore.
I have tried adding e.pageX and e.pageY in the mouse handlers, but that does not help.
How to handle scrolled content in such situations?
Please see a screenshot and the copy of the troubled JavaScript code below -
jQuery(document).ready(function($) {
var board = document.getElementById("board");
var ctx = board.getContext("2d");
ctx.strokeStyle = "lightgray";
var canvasOffset = $("#board").offset();
var offsetX = canvasOffset.left;
var offsetY = canvasOffset.top;
console.log('ready: offsetX=' + offsetX + ", " + "offsetY=" + offsetY);
var mouseIsDown = false;
var lastX = 0;
var lastY = 0;
var ships = [];
makeShip(20, 30, 50, 25, "skyblue");
makeShip(20, 100, 30, 25, "skyblue");
makeShip(20, 170, 50, 25, "salmon");
makeShip(20, 240, 30, 25, "salmon");
function makeShip(x, y, width, height, fill) {
var ship = {
x: x,
y: y,
width: width,
height: height,
right: x + width,
bottom: y + height,
fill: fill
}
ships.push(ship);
}
drawAllShips();
function drawAllShips() {
ctx.clearRect(0, 0, board.width, board.height);
for (var i = 0; i < ships.length; i++) {
var ship = ships[i]
drawShip(ship);
ctx.fillStyle = ship.fill;
ctx.fill();
ctx.stroke();
}
}
function drawShip(ship) {
ctx.beginPath();
ctx.moveTo(ship.x, ship.y);
ctx.lineTo(ship.right, ship.y);
ctx.lineTo(ship.right + 10, ship.y + ship.height / 2);
ctx.lineTo(ship.right, ship.bottom);
ctx.lineTo(ship.x, ship.bottom);
ctx.closePath();
}
function handleMouseDown(e) {
mouseX = parseInt(e.clientX - offsetX);
mouseY = parseInt(e.clientY - offsetY);
console.log('handleMouseDown: mouseX=' + mouseX + ", " + "mouseY=" + mouseY);
lastX = mouseX;
lastY = mouseY;
mouseIsDown = true;
}
function handleMouseUp(e) {
mouseX = parseInt(e.clientX - offsetX);
mouseY = parseInt(e.clientY - offsetY);
console.log('handleMouseUp: mouseX=' + mouseX + ", " + "mouseY=" + mouseY);
mouseIsDown = false;
}
function handleMouseMove(e) {
if (!mouseIsDown) {
return;
}
mouseX = parseInt(e.clientX - offsetX);
mouseY = parseInt(e.clientY - offsetY);
console.log('handleMouseMove: mouseX=' + mouseX + ", " + "mouseY=" + mouseY);
for (var i = 0; i < ships.length; i++) {
var ship = ships[i];
drawShip(ship);
if (ctx.isPointInPath(lastX, lastY)) {
ship.x += (mouseX - lastX);
ship.y += (mouseY - lastY);
ship.right = ship.x + ship.width;
ship.bottom = ship.y + ship.height;
}
}
lastX = mouseX;
lastY = mouseY;
drawAllShips();
}
$("#board").mousedown(function(e) {
handleMouseDown(e);
});
$("#board").mousemove(function(e) {
handleMouseMove(e);
});
$("#board").mouseup(function(e) {
handleMouseUp(e);
});
});
You need also to consider the document scroll values
Here is the sample i created
jQuery(document).ready(function($) {
var board = document.getElementById("board");
var ctx = board.getContext("2d");
ctx.strokeStyle = "lightgray";
var canvasOffset = $("#board").offset();
var offsetX = canvasOffset.left;
var offsetY = canvasOffset.top;
var scrolltop = $(document).scrollTop();
var scrollleft = $(document).scrollLeft();
console.log('ready: offsetX=' + offsetX + ", " + "offsetY=" + offsetY, scrolltop, scrollleft);
var mouseIsDown = false;
var lastX = 0;
var lastY = 0;
var ships = [];
makeShip(20, 30, 50, 25, "skyblue");
makeShip(20, 100, 30, 25, "skyblue");
makeShip(20, 170, 50, 25, "salmon");
makeShip(20, 240, 30, 25, "salmon");
function makeShip(x, y, width, height, fill) {
var ship = {
x: x,
y: y,
width: width,
height: height,
right: x + width,
bottom: y + height,
fill: fill
}
ships.push(ship);
return (ship);
}
drawAllShips();
function drawAllShips() {
ctx.clearRect(0, 0, board.width, board.height);
for (var i = 0; i < ships.length; i++) {
var ship = ships[i]
drawShip(ship);
ctx.fillStyle = ship.fill;
ctx.fill();
ctx.stroke();
}
}
function drawShip(ship) {
ctx.beginPath();
ctx.moveTo(ship.x, ship.y);
ctx.lineTo(ship.right, ship.y);
ctx.lineTo(ship.right + 10, ship.y + ship.height / 2);
ctx.lineTo(ship.right, ship.bottom);
ctx.lineTo(ship.x, ship.bottom);
ctx.closePath();
}
function handleMouseDown(e) {
scrolltop = $(document).scrollTop();
scrollleft = $(document).scrollLeft();
mouseX = parseInt(e.clientX - offsetX + scrollleft);
mouseY = parseInt(e.clientY - offsetY + scrolltop);
lastX = mouseX;
lastY = mouseY;
mouseIsDown = true;
console.log('ready: offsetX=' + offsetX + ", " + "offsetY=" + offsetY, scrolltop, scrollleft);
}
function handleMouseUp(e) {
mouseX = parseInt(e.clientX - offsetX + scrollleft);
mouseY = parseInt(e.clientY - offsetY + scrolltop);
console.log('handleMouseUp: mouseX=' + mouseX + ", " + "mouseY=" + mouseY);
mouseIsDown = false;
}
function handleMouseMove(e) {
if (!mouseIsDown) {
return;
}
mouseX = parseInt(e.clientX - offsetX + scrollleft);
mouseY = parseInt(e.clientY - offsetY + scrolltop);
console.log('handleMouseMove: mouseX=' + mouseX + ", " + "mouseY=" + mouseY);
for (var i = 0; i < ships.length; i++) {
var ship = ships[i];
drawShip(ship);
if (ctx.isPointInPath(lastX, lastY)) {
ship.x += (mouseX - lastX);
ship.y += (mouseY - lastY);
ship.right = ship.x + ship.width;
ship.bottom = ship.y + ship.height;
}
}
lastX = mouseX;
lastY = mouseY;
drawAllShips();
}
$("#board").mousedown(function (e) {
handleMouseDown(e);
});
$("#board").mousemove(function (e) {
handleMouseMove(e);
});
$("#board").mouseup(function (e) {
handleMouseUp(e);
});
});
DEMO HERE

HTML5 canvas, make image rotate around click to select and drag circle

I have completed code that has a user click a button (to the right of the canvas), then the image is added to the canvas and is constrained to only move around the circumference of a circle. In order to move the image the user just needs to click the image and then move the mouse. To release the image the user simply needs to click where the image goes on the canvas.
Here is a fiddle showing what the current code does.
http://jsfiddle.net/smacnabb/68awv7sq/9/
Question: I am looking to be able to have the images that move around the circumference of the circle rotate while moving around the circumference of the circle.
This is what I mean:
Here is a fiddle for the code I added to try and make this happen
http://jsfiddle.net/smacnabb/68awv7sq/11/
in the handlemousemove method, it calls state.draw() every time the mouse move i'm passing mouseX, mouseY to state.draw.
state.draw() is in addstate method and this was the code I added to make the image rotate
var dx = mouseX - centerX;
var dy = mouseY - centerY;
var radianAngle = Math.atan2(dy, dx);
context.save();
context.translate(centerX, centerY);
context.rotate(radianAngle);
if (this.dragging) {
context.strokeStyle = 'black';
context.strokeRect(this.x, this.y, this.width + 2, this.height + 2)
}
context.drawImage(this.image, this.x, this.y);
context.restore();
What am I doing wrong?
You are close...Take a look at this example:
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 radianAngle = 0;
var cx = 225;
var cy = 125;
var radius = 50;
// image loader
var imageURLs = [];
var imagesOK = 0;
var imgs = [];
imageURLs.push("https://dl.dropboxusercontent.com/u/139992952/multple/cars.png");
imageURLs.push("https://dl.dropboxusercontent.com/u/139992952/multple/plane.png");
imageURLs.push("https://dl.dropboxusercontent.com/u/139992952/multple/cars1.png");
imageURLs.push("https://dl.dropboxusercontent.com/u/139992952/multple/plane1.png");
loadAllImages(start);
function loadAllImages(callback) {
for (var i = 0; i < imageURLs.length; i++) {
var img = new Image();
imgs.push(img);
img.onload = function() {
imagesOK++;
if (imagesOK >= imageURLs.length) {
callback();
}
};
img.onerror = function() {
alert("image load failed");
}
img.crossOrigin = "anonymous";
img.src = imageURLs[i];
}
}
var imagesY = 20;
var targets = [];
var selectedTarget = -1;
function start() {
var n = imgs.length / 2;
for (var i = 0; i < n; i++) {
var target = imgs[i + n];
ctx.drawImage(target, 15, imagesY);
targets.push({
x: 15,
y: imagesY,
width: target.width,
height: target.height,
image: imgs[i]
});
imagesY += target.height + 10;
}
}
function handleMouseDown(e) {
e.preventDefault();
x = parseInt(e.clientX - offsetX);
y = parseInt(e.clientY - offsetY);
for (var i = 0; i < targets.length; i++) {
var t = targets[i];
if (x >= t.x && x <= t.x + t.width && y >= t.y && y <= t.y + t.height) {
selectedTarget = i;
draw(x, y);
}
}
}
function handleMouseMove(e) {
if (selectedTarget < 0) {
return;
}
e.preventDefault();
mouseX = parseInt(e.clientX - offsetX);
mouseY = parseInt(e.clientY - offsetY);
draw(mouseX, mouseY);
}
function draw(mouseX, mouseY) {
var dx = mouseX - cx;
var dy = mouseY - cy;
var radianAngle = Math.atan2(dy, dx);
// Drawing code goes here
var img = targets[selectedTarget].image;
ctx.clearRect(100, 0, canvas.width, canvas.height);
// draw the circle
ctx.beginPath();
ctx.arc(cx, cy, radius, 0, Math.PI * 2);
ctx.closePath();
ctx.stroke();
// draw the image rotated around the circumference
ctx.save();
ctx.translate(cx, cy);
ctx.rotate(radianAngle);
ctx.drawImage(img, radius - img.width / 2, -img.height / 2);
ctx.restore();
}
$("#canvas").mousedown(function(e) {
handleMouseDown(e);
});
$("#canvas").mousemove(function(e) {
handleMouseMove(e);
});
body{ background-color: ivory; }
canvas{border:1px solid red;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<h4>Select an icon on left by clicking<br>
Then move mouse to have icon rotate around circle</h4>
<canvas id="canvas" width=350 height=350></canvas>

Capture user input on HTML canvas/Javascript and vice versa

I am trying to draw a rectangle in HTML5 canvas based on user input. I am also trying to do the opposite. If a user draws a rectangle in the canvas, the width and height values are dropped into the form. Please see my jsfiddle.
http://jsfiddle.net/hbrennan72/FyTx5/
var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");
var rect = {};
//var drag = false;
function getarea()
{
var wid = document.getElementById("wid").value;
var hgt = document.getElementById("hgt").value;
var area = wid * hgt;
var perim = wid * 2 + hgt * 2;
if (wid =="") {
document.getElementById("errors").innerHTML = "The value for the width is blank.";
document.getElementById('wid').focus();
}
else if (hgt == "") {
document.getElementById("errors").innerHTML = "The value for the height is blank.";
document.getElementById("hgt").focus();
}
else if (isNaN (wid)) {
document.getElementById("errors").innerHTML = "Please enter a numeric value for the width.";
document.getElementById('wid').focus();
}
else if (isNaN (hgt)) {
document.getElementById("errors").innerHTML = "Please enter a numeric value for the height.";
document.getElementById("hgt").focus();
}
else if (wid <= 0) {
document.getElementById("errors").innerHTML = "The width is less than or equal to zero.";
document.getElementById('wid').focus();
}
else if (hgt <= 0) {
document.getElementById("errors").innerHTML = "The height is less than or equal to zero.";
document.getElementById("hgt").focus();
}
else if (wid > 500) {
document.getElementById("errors").innerHTML = "The width is greater than 500.";
document.getElementById('wid').focus();
}
else if (hgt > 500) {
document.getElementById("errors").innerHTML = "The height is greater than 500.";
document.getElementById("hgt").focus();
}
else {
window.document.getElementById("area").innerHTML = area;
window.document.getElementById("perim").innerHTML = perim;
document.getElementById("errors").innerHTML = "Please see results listed above.";
}
}
function updateform (){
"use strict"
var wid = document.getElementById("wid").value;
var hgt = document.getElementById("hgt").value;
var area = wid * hgt;
var canvas = document.getElementById("canvas");
var context = canvas.getContext("2D");
context.clearRect(0, 0, canvas.width, canvas.height);
context.fillRect(0,0, rect.wid, rect.hgt);
context.fillStyle = "#FF0000"; //red color
draw();
}
function mouseDown(e)
{
rect.startX = e.pageX - this.offsetLeft;
rect.startY = e.pageY - this.offsetTop;
canvas.style.cursor="crosshair";
drag = true;
}
function mouseUp () {
drag = false;
}
function mouseMove(e) {
if (drag) {
rect.wid = (e.pageX - this.offsetLeft) - rect.startX;
rect.hgt = (e.pageY - this.offsetTop) - rect.startY ;
context.clearRect(0,0,canvas.width,canvas.height);
draw();
}
}
function init() {
canvas.addEventListener("mousedown", mouseDown, false);
canvas.addEventListener("mouseup", mouseUp, false);
canvas.addEventListener("mousemove", mouseMove, false);
}
init();
function drawform() {
var canvas = document.getElementById("canvas");
var context = canvas.getContext("2D");
context.clearRect(0, 0, canvas.width, canvas.height);
context.fillRect(0,0, rect.wid, rect.hgt);
context.fillStyle = "#FF0000"; //red color
}
function draw (){
context.clearRect(0, 0, canvas.width, canvas.height);
context.fillRect(rect.startX, rect.startY, rect.wid, rect.hgt);
context.fillStyle = "#378E37"; //green color
}
draw();
I have tried to do it in this way.It is working fine.The code is
$("#smt").click(function(){
var canvasel=' <canvas id="myCanvas" width="400" height="400"></canvas>'
$("#canvas").append(canvasel)
var w=$("#wid").val();
var h=$("#hgt").val();
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
ctx.rect(20,20,w,h);
ctx.stroke();
})
$("#clr").click(function(){
$("#canvas").empty();
$("#wid").val('');
$("#hgt").val('');
})
initDraw(document.getElementById('canvas'));
function initDraw(canvas) {
function setMousePosition(e) {
var ev = e || window.event; //Moz || IE
if (ev.pageX) { //Moz
mouse.x = ev.pageX + window.pageXOffset;
mouse.y = ev.pageY + window.pageYOffset;
} else if (ev.clientX) { //IE
mouse.x = ev.clientX + document.body.scrollLeft;
mouse.y = ev.clientY + document.body.scrollTop;
}
};
var mouse = {
x: 0,
y: 0,
startX: 0,
startY: 0
};
var element = null;
canvas.onmousemove = function (e) {
setMousePosition();
if (element !== null) {
element.style.width = Math.abs(mouse.x - mouse.startX) + 'px';
element.style.height = Math.abs(mouse.y - mouse.startY) + 'px';
element.style.left = (mouse.x - mouse.startX < 0) ? mouse.x + 'px' : mouse.startX + 'px';
element.style.top = (mouse.y - mouse.startY < 0) ? mouse.y + 'px' : mouse.startY + 'px';
}
}
canvas.onclick = function (e) {
if (element !== null) {
element = null;
canvas.style.cursor = "default";
console.log("finsihed.");
var width=$(".rectangle").width();
var height=$(".rectangle").height();
$("#wid").val(width);
$("#hgt").val(height)
} else {
console.log("begun.");
mouse.startX = mouse.x;
mouse.startY = mouse.y;
element = document.createElement('div');
element.className = 'rectangle'
element.style.left = mouse.x + 'px';
element.style.top = mouse.y + 'px';
canvas.appendChild(element)
canvas.style.cursor = "crosshair";
}
}
}
SEE DEMO HERE
NOTE:Its not working in Mozilla. I am trying to fix it.Check in Chrome

Html5 canvas image on click

I'm having a problem whit my code.
I draw some circles in a circular path and I expect when to click on them to return something other than 0 in firebug console but that's not happening;
I don't know what is wrong with my code and i hope someone will tell me.
Here's my code:
var canvas, ctx;
var circle_data = [];
function circles(x, y, radius) {
this.x = x;
this.y = y;
this.radius = radius;
circle_data.push(this);
}
circles.prototype = {
draw: function (context) {
context.beginPath();
context.arc(this.x, this.y, this.radius / 5, 0, 2 * Math.PI, false);
context.fillStyle = "red";
context.fill();
}
}
function draw() {
ctx.translate(250, 250);
for (var n = 0; n < 10; n++) {
var radi = (Math.PI / 180);
var x = Math.sin(radi * n * 36) * 70;
var y = Math.cos(radi * n * 36) * 70;
var radius = 50;
var thiscircle = new circles(x, y, radius);
thiscircle.draw(ctx);
}
}
function mouseDown(e) {
var img_data = ctx.getImageData(e.pageX, e.pageY, 1, 1);
console.log(img_data.data[3]);
}
function init() {
canvas = document.getElementById('canvas'),
ctx = canvas.getContext('2d');
canvas.addEventListener('mousedown', mouseDown, false);
}
init();
It dosen't matter is i use data[3];
I tried whit console.log(img_data.data[0]+" "+img_data.data[1]+" "+img_data.data[2]);
Still getting 0 0 0
Your detecting the mouse position relative to the page and not the canvas, you need to get the position of the canvas on the page and subtract that from the X and Y of the mouse to find you position relative to the canvas. I use functions similar to the ones below when working with canvas.
getOffsetPosition = function(obj){
/*obj is the Canvas element*/
var offsetX = offsetY = 0;
if (obj.offsetParent) {
do {
offsetX += obj.offsetLeft;
offsetY += obj.offsetTop;
}while(obj = obj.offsetParent);
}
return [offsetX,offsetY];
}
getMouse = function(e,canvasElement){
OFFSET = getOffsetPosition(canvasElement);
mouse_x = (e.pageX || (e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft)) - OFFSET[0];
mouse_y = (e.pageY || (e.clientY + document.body.scrollTop + document.documentElement.scrollTop)) - OFFSET[1];
return [mouse_x,mouse_y];
}
The following code works.
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
</head>
<body>
<canvas id="canvas" width="500" height="500" style="background-color:#999999;"></canvas>
</body>
<script>
var canvas,ctx;
var circle_data = [];
function circles(x,y,radius)
{
this.x = x;
this.y = y;
this.radius = radius;
circle_data.push(this);
}
circles.prototype = {
draw: function(context){
context.beginPath();
context.arc(this.x, this.y, this.radius / 5, 0, 2* Math.PI, false);
context.fillStyle = "red";
context.fill();
}
}
getOffsetPosition = function(obj){
/*obj is the Canvas element*/
var offsetX = offsetY = 0;
if (obj.offsetParent) {
do {
offsetX += obj.offsetLeft;
offsetY += obj.offsetTop;
}while(obj = obj.offsetParent);
}
return [offsetX,offsetY];
}
getMouse = function(e,canvasElement){
OFFSET = getOffsetPosition(canvasElement);
mouse_x = (e.pageX || (e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft)) - OFFSET[0];
mouse_y = (e.pageY || (e.clientY + document.body.scrollTop + document.documentElement.scrollTop)) - OFFSET[1];
return [mouse_x,mouse_y];
}
function draw(){
ctx.translate(250, 250);
for (var n = 0; n < 10; n++) {
var radi = (Math.PI/180);
var x = Math.sin(radi*n*36)*70;
var y = Math.cos(radi*n*36)*70;
var radius = 50;
var thiscircle = new circles(x,y,radius);
thiscircle.draw(ctx);
}
}
function mouseDown(e)
{
var pos = getMouse(e,ctx.canvas);
var img_data = ctx.getImageData(pos[0],pos[1],1,1);
console.log(img_data.data[3]);
}
function init() {
canvas = document.getElementById('canvas'),
ctx = canvas.getContext('2d');
draw();
canvas.addEventListener('mousedown', mouseDown, false);
}
init();
</script>
</html>

JQuery Listener on Canvas Child doesn't work

i have a problem i'm implementing a crop custom rectangle on a canvas i made a function in Javascript that when the crop function is called the create on existing canvas a child and then with the JQuery listener i draw the rectangle.The childNode is create correctly while the listener don't work they don't get the events. This is my code:
var dragging = false;
var xstart = 0;
var ystart = 0;
var width = 0;
var height = 0;
var ctxotmp = null;
var ctxtmp = null;
var canvastmp = null;
var mycanvas = null;
function draw() {
ctxtmp.fillRect(xstart, ystart, width, height);
}
function init() {
mycanvas = $('#mycanvas')[0];
// create temp canvas
canvastmp = document.createElement('canvas');
canvastmp.id = "mycanvastmp";
canvastmp.width = mycanvas.width;
canvastmp.height = mycanvas.height;
mycanvas.parentNode.appendChild(canvastmp);
$("#mycanvastmp").css({position:"absolute",top:$("#mycanvas").css("top"),left:$("#mycanvas").css("left")});
canvastmp = $('#mycanvastmp')[0];
ctxtmp = canvastmp.getContext('2d');
ctxtmp.lineWidth = 1;
ctxtmp.fillStyle = "rgba(0, 0, 0, 0.5)";
}
//listener
$('#mycanvastmp').mousedown(function(e) {
var xoffs = $(this).offset().left;
var yoffs = $(this).offset().top;
xstart = e.pageX - xoffs;
ystart = e.pageY - yoffs;
dragging = true;
});
$('#mycanvastmp').mousemove(function(e) {
if(dragging) {
var xoffs = $(this).offset().left;
var yoffs = $(this).offset().top;
width = e.pageX - xoffs - xstart;
height = e.pageY - yoffs - ystart;
ctxtmp.clearRect(0, 0, $(this).width(), $(this).height());
draw();
}
});
$('#mycanvastmp').mouseup(function() {
dragging=false;
alert('The rectangle for crop (x, y, width, height): ' + xstart + ', ' + ystart + ', ' + width + ', ' + height);
});
Someone can help me?
Looks like you're attaching the events before the temp canvas is created.
Either attach the events in the init() function after adding the temp canvas to the DOM or use .delegate() or .on()
$("#mycanvas").on("mouseup", "#mycanvastmp", function() {
//...
});
You need to use .on on method in order to bind events to dynamically created objects. When your page initially loads and the dom fires, it doesn't see tempCanvas so it doesn't attach them initially.
//listener
$('body').on('mousedown' ,'#mycanvastmp', function(e) {
var xoffs = $(this).offset().left;
var yoffs = $(this).offset().top;
xstart = e.pageX - xoffs;
ystart = e.pageY - yoffs;
dragging = true;
});
$('body').on('mousemove' ,'#mycanvastmp', function(e) {
if(dragging) {
var xoffs = $(this).offset().left;
var yoffs = $(this).offset().top;
width = e.pageX - xoffs - xstart;
height = e.pageY - yoffs - ystart;
ctxtmp.clearRect(0, 0, $(this).width(), $(this).height());
draw();
}
});
$('body').on('mouseup' ,'#mycanvastmp', function(e) {
dragging=false;
alert('The rectangle for crop (x, y, width, height): ' + xstart + ', ' + ystart + ', ' + width + ', ' + height);
});
init();
Live Demo

Categories

Resources