RaphealJS Resize and mouse shift - javascript

I have been using RaphealJS to create a vector drawing tool, I have all the drawing completed and working
my issues comes in when I resize the browser window and try to draw the mouse pointer is off from the location that is being drawn.
I use the mouse move event on the browser and draw lines , Like so
$(document).mousemove(function(e){
if (IE) {
var dh = $("#details").height();
var dw = $("#details").width();
xx = e.offsetX;
yy = e.offsetY;
} else {
var offset = $("#workcanvas").offset();
xx = e.pageX - offset.left;
yy = e.pageY - offset.top;
}
if (lineObject != null) {
lineObject.updateEnd(xx, yy);
} else {
lineObject = Line(xx, yy, xx, yy, MasterCanvas);
}
});
I create my canvas and background image
var MasterCanvas = Raphael($("#workcanvas").attr("id"));
var MasterBGImage = MasterCanvas.image(imgPath, 0, 0, $("#workcanvas").width(),$("#workcanvas").height());
MasterCanvas.setViewBox(0, 0, $("#workcanvas").width(), $("#workcanvas").height(), true);
and in my window resize event I tried this
MasterCanvas.setSize($("#workcanvas").width(), $("#workcanvas").height());
Now I have beat my head against this for a few days to no avail. Please note: I can the drawing function work, and as long as the window does not resize every thing is great but when the page resizes the drawing point is off.

Just in case anyone else has this problem, it turns out to be a viewBox problem, I had to calculate the mouse position based on the viewBox coordinates not the screen so my original code becomes:
$(document).mousemove(function(e){
var uupos = MasterCanvas.canvas.createSVGPoint();
uupos.x = e.clientX;
uupos.y = e.clientY;
var ctm = MasterCanvas.canvas.getScreenCTM();
if (ctm = ctm.inverse())
uupos = uupos.matrixTransform(ctm);
x = uupos.x;
y = uupos.y;
if (lineObject != null) {
lineObject.updateEnd(x, y);
} else {
lineObject = Line(x, y, x, y, MasterCanvas);
}
});
Edit:
Looks like this solution is SVG only though and it does not work in IE8 which is a requirement for me - any ideas.
Is there something like viewBox coordinates in VML

Related

Fixing the canvas offset in Raphael.js when DOM element centered

I'm creating circles in a Raphael.js Canvas with a clicking action. When the canvas is drawn at the origin of the website it works fine. But when I move it to the middle some type offseting happens and only when you click on the right side of the canvas the circles are drawn at the left side of the canvas. Even though I have my listener action to the canvas and not the div that the is append to, here is the code:
<body>
<div id="container"></div>
</body>
Here is the JS:
var canvas = Raphael("container", 500, 500);
var ourCanvas = $('svg').last();
ourCanvas.attr("id", "canvas");
var canvasHandler = $("#canvas");
//We create a div with a class to append our canvas
var containerHandler = $("#container");
var circleClass = $("circle.quincy");
var justDragged = false;
canvasHandler.mouseup(function (e) {
var mouseX = e.pageX;
var mouseY = e.pageY;
makeCircle(mouseX, mouseY);
});
function makeCircle(mouseX, mouseY) {
var radius;
var fill;
var thisCirclesID = String(new Date().getTime());
var circle = canvas.circle(mouseX, mouseY, 50).attr({
fill: "hsb(.8, 1, 1)",
stroke: "none",
opacity: .5,
});
}
Here is a JSFiddle
I wonder if the way that I'm using the event position is correct. Any suggestion is more than welcome.
Thanks
M
I figured it out after realizing that the offset of the new position of svg was causing the mouse event to not recognize its real position. I found this blog post that shows how to use the offsetParent method to calculate the new position of my canvas relative its parent . Here is the code:
$(document).ready(function () {
//We create our canvas and add an ID
var canvas = Raphael("container", 500, 500);
var ourCanvas = $('svg').last();
ourCanvas.attr("id", "canvas");
var canvasHandler = $("#canvas");
//We create a div with a class to append our canvas
var containerHandler = $("#container");
var circleClass = $("circle.quincy");
var justDragged = false;
canvasHandler.mouseup(function (e) {
var mouseX = e.pageX - findPos(this)[0];
var mouseY = e.pageY - findPos(this)[1];
makeCircle(mouseX, mouseY);
findPos(this);
console.log("This is the position of the mouse in X: " + e.pageX);
console.log("This is the position of the mouse in Y: " + e.pageY);
});
function findPos(obj) {
var curleft = curtop = 0;
if (obj.offsetParent) {
do {
curleft += obj.offsetLeft;
curtop += obj.offsetTop;
} while (obj == obj.offsetParent);
console.log(curleft);
console.log(curtop);
// return [curleft, curtop];
}
return [curleft, curtop];
}
As you can see the findPos(obj) returns and array of the new position of X and Y. So I substract that to my mouseX and mouseY to get the real position on the svg when clicking.
Update
Doing more reading and asking around. I didn't realize what type of elements the web browser returns. Instead of using e.pageX and e.pageY. offsetX offers the position of the mouse in respect to the parent giving the real coordinates. So the code will look like this:
canvasHandler.mouseup(function (e) {
var mouseX = e.offsetX;
var mouseY = e.offsetY;
makeCircle(mouseX, mouseY);
findPos(this);
});
This makes it easier since the offset takes into consideration the real position of the mouse in respect to the element.

How to fix offset issue for mouse pointer on canvas on HTML5 fullscreen mode?

I am using the HTML5 full_screen API to scale up this letter to full screen mode of the browser.
Follow https://bubbleideas.com/letters/html5-full_screen-api for the demo and steps to reproduce.
There seems a problem/bug with the way browser returns (x,y) value of pointer location of the mouse. In full_screen mode when you scroll down an offset is introduced between the mouse pointer and scribbled path.
Here are the steps to reproduce the issue. (go to above demo link)
Click on button on the right hand top of this page.
Click on "Free hand" drawing tool on the right bottom side. It will open up a stationery panel (Choose pen or pencil tool)
Scribble on the drawing area a couple of times
Now scroll down a bit and try to scribble with the same pen. You ll notice that there is gap/offset between mouse pointer position and scribbled path(this is the issue). Ideally, there should be no gap in the full screen mode either
Has someone been here before? Also note this works perfectly fine for other shapes like the square, circle and triangle without any offset.
UPDATE: (As asked by "Iftah" in the commment below)
As per fabric js I use calcOffset() which recalculates offset on every mouse down. As far as other functions are concerned we do some thing like this. Hopefully this gives some idea
$("#rectangle-function").click(function (evt1) {
doCanvasUp();
initObjectDrawing();
//canvas.isDrawingMode = true;
canvas1 = document.createElement("canvas");
canvas1.height = canvas.height;
canvas1.width = canvas.width;
canvas1.id = "dummy-canvas";
canvas1.style.zIndex = 998;
canvas1.style.position = "absolute";
$(".page-body").prepend(canvas1);
$("#dummy-canvas").mousedown(function (evt) {
var context1 = canvas1.getContext("2d");
var offset = $("#dummy-canvas").offset();
startX = evt.pageX - offset.left;
startY = evt.pageY - offset.top;
context1.beginPath();
$("#dummy-canvas").mousemove(function (event) {
context1.clearRect(0, 0, canvas1.width, canvas1.height);
context1.strokeStyle = "#ff0000";
context1.lineWidth = 1;
context1.moveTo(startX, startY);
var offset1 = $("#dummy-canvas").offset();
var x = event.pageX - offset1.left;
var y = event.pageY - offset1.top;
var diffX = x - startX;
var diffY = y - startY;
context1.strokeRect(startX, startY, diffX, diffY);
context1.closePath();
context1.beginPath();
}).mouseup(function (eventf) {
$("#dummy-canvas").unbind('mousemove');
$("#dummy-canvas").unbind('mouseup');
var offset = $("#dummy-canvas").offset();
//$("#dummy-canvas").remove();
context1.clearRect(0, 0, canvas1.width, canvas1.height);
var endX = eventf.pageX - offset.left;
var endY = eventf.pageY - offset.top;
var diffX = endX - startX;
var diffY = endY - startY;
var rect = new fabric.Rect({
left: startX + diffX * 0.5,
top: startY + diffY * 0.5,
width: diffX,
height: diffY,
opacity: 1,
fill: null,
stroke: color
});
canvas.add(rect);
});
});
Without looking at your code it is impossible to tell exactly where the error is...
One problem could be when reading the mouse coordinates, IE. You could be wrongly using event.pageY instead of event.clientY or a similar confusion (see What is the difference between screenX/Y, clientX/Y and pageX/Y?)
Or you can say the problem is how you use those coordinates,
ie. if you take the mouse event coordinates in screen space then before applying it on the canvas you need to subtract the canvas element screen offset and add the scrolling offset...
Since you have one tool that works and one that doesn't you can compare them and see where they differ.

Implement dragging an image within a canvas

I want to implement dragging of an image within a canvas. I want simplest code for that. So far I have seen a lot of examples but they have used complex ways of implementation. I want an example that is easy to learn and implement.
It's pretty difficult. You'll first need to write a function that can detect when you click a particular element. However, before we can do that, we must define what we mean by "element". Is it the product of a single draw instruction (e.g. a rectangle or arc), or something complex? (Imagine I wanted to draw a cat and make the entire cat draggable as a unit.)
A canvas is nothing but a collection of pixels. If you want your program to have an idea of "shapes" or even "collections of shapes treated as a unit" you'll need to implement them yourself as data structures external to the canvas itself. Once you have that, you can write an onmousedown handler that takes the x/y point clicked and determine what shape (if any) the click falls inside of (and if it falls inside of multiple shapes, check which has the foremost z-index). Then add an onmousemove handler that erases and redraws the shape on the canvas based on the information in the shape data object.
This is a moderately difficult problem with very difficult prerequisite problems (creating data structures that can describe a wide range of shapes as well as collections of shapes). I highly recommend you use a canvas drawing library that has already solved these problems. I use cake.js but there are loads of options available.
If you don't have to use the HTML5 canvas, jQuery UI is a lot simpler:
HTML:
<img class="drag-me" src="http://www.google.com/images/srpr/logo3w.png">​
JavaScript:
$(function() {
$('.drag-me').draggable();
});
​
See it in action:
http://jsfiddle.net/flackend/TQzSe/
The jQuery UI API has a lot of options too to make it act how you want:
http://jqueryui.com/demos/draggable/
Plus, if it doesn't do what you need, it's easy to implement yourself. Post here if you need help with that.
jsfiddle.net/Zevan/QZejF/5 This may help you.
<html>
<head>
<title>Test Page</title>
<script type="text/javascript" src="jquery.js"></script>
</head>
<body>
<canvas id="c" width = "500" height = "500" ></canvas>
<script type="text/javascript">
var canvas = $("#c");
var c = canvas[0].getContext("2d");
//var path = "http://wonderfl.net/images/icon/e/ec/ec3c/ec3c37ba9594a7b47f1126b2561efd35df2251bfm";
var path = "blue.jpg";
var path2 = "purple.jpg";
var image1 = new DragImage(path, 200, 100);
var image2 = new DragImage(path2, 300, 100);
var loop = setInterval(function() {
c.fillStyle = "gray";
c.fillRect(0, 0, 500, 500);
image1.update();
image2.update();
}, 30);
var mouseX = 0,
mouseY = 0;
var mousePressed = false;
var dragging = false;
canvas.mousemove(function(e) {
mouseX = e.offsetX;
mouseY = e.offsetY;
})
$(document).mousedown(function() {
mousePressed = true;
}).mouseup(function() {
mousePressed = false;
dragging = false;
});
function DragImage(src, x, y) {
var that = this;
var startX = 0,
startY = 0;
var drag = false;
this.x = x;
this.y = y;
var img = new Image();
img.src = src;
this.update = function() {
if (mousePressed ) {
var left = that.x;
var right = that.x + img.width;
var top = that.y;
var bottom = that.y + img.height;
if (!drag) {
startX = mouseX - that.x;
startY = mouseY - that.y;
}
if (mouseX < right && mouseX > left && mouseY < bottom && mouseY > top) {
if (!dragging){
dragging = true;
drag = true;
}
}
} else {
drag = false;
}
if (drag) {
that.x = mouseX - startX;
that.y = mouseY - startY;
}
c.drawImage(img, that.x, that.y);
}
}
</script>
</body>
</html>

HTML5 Panning based on Mouse Movement

I'm trying to implement functionality to "pan" inside a canvas in HTML5 and I am unsure about the best way to go about accomplishing it.
Currently - I am trying to detect where the mouse is on the canvas, and if it is within 10% of an edge, it will move in that direction, as shown:
Current Edge Detection:
canvas.onmousemove = function(e)
{
var x = e.offsetX;
var y = e.offsetY;
var cx = canvas.width;
var cy = canvas.height;
if(x <= 0.1*cx && y <= 0.1*cy)
{
alert("Upper Left");
//Move "viewport" to up and left (if possible)
}
//Additional Checks for location
}
I know I could probably accomplish this by creating paths within the canvas and attaching events to them, but I haven't worked with them much, so I thought I would ask here. Also - if a "wrapping" pan would be possible that would be awesome (panning to the left will eventually get to the right).
Summary: I am wondering what the best route is to accomplish "panning" is within the HTML5 Canvas. This won't be using images but actual drawn objects (if that makes any difference). I'll be glad to answer any questions if I can.
Demo:
Demo
It depends on how you want panning with mouse movement to be implemented, but today it's often 'realtime' panning in that you can drag around. I tried to update your fiddle a little: http://jsfiddle.net/pimvdb/VWn6t/3/.
var isDown = false; // whether mouse is pressed
var startCoords = []; // 'grab' coordinates when pressing mouse
var last = [0, 0]; // previous coordinates of mouse release
canvas.onmousedown = function(e) {
isDown = true;
startCoords = [
e.offsetX - last[0], // set start coordinates
e.offsetY - last[1]
];
};
canvas.onmouseup = function(e) {
isDown = false;
last = [
e.offsetX - startCoords[0], // set last coordinates
e.offsetY - startCoords[1]
];
};
canvas.onmousemove = function(e)
{
if(!isDown) return; // don't pan if mouse is not pressed
var x = e.offsetX;
var y = e.offsetY;
// set the canvas' transformation matrix by setting the amount of movement:
// 1 0 dx
// 0 1 dy
// 0 0 1
ctx.setTransform(1, 0, 0, 1,
x - startCoords[0], y - startCoords[1]);
render(); // render to show changes
}
pimvdb's fiddle shows the concept nicely but doesn't actually work, at least not for me.
Here's a fixed version: http://jsfiddle.net/VWn6t/173/
The meat of it is basically the same.
var startCoords = {x: 0, y: 0};
var last = {x: 0, y: 0};
var isDown = false;
canvas.onmousemove = function (e) {
if(isDown) {
ctx.setTransform(1, 0, 0, 1,
xVal - startCoords.x,
yVal - startCoords.y);
}
};
canvas.onmousedown = function (e) {
isDown = true;
startCoords = {x: e.pageX - this.offsetLeft - last.x,
y: e.pageY - this.offsetTop - last.y};
};
canvas.onmouseup = function (e) {
isDown = false;
last = {x: e.pageX - this.offsetLeft - startCoords.x,
y: e.pageY - this.offsetTop - startCoords.y};
};

Click event position (Y) is too high

I have a canvas element and when i click on it i get the click position with e.clientX(Y) or e.screenX(Y). Something strange is happening. Y value is always too high. Please look at this image: http://img840.imageshack.us/img840/268/eventq.jpg. Any ideia why is it so high?
You just need to take the ClientX and Y and subtract the position of the canvas from them.
This example is unnecessarily verbose, just to show the steps:
var canvas = document.getElementById('game');
var canvasX, canvasY;
canvas.addEventListener('click', function(event) {
canvasX = canvas.offsetLeft;
canvasY = canvas.offsetTop;
var eventX = event.clientX;
var eventY = event.clientY;
var relX = eventX - canvasX;
var relY = eventY - canvasY;
alert('X = ' + relX + ', Y = ' + relY);
});
Working sample: http://jsfiddle.net/JfhJF/
I'm pretty sure you can tell what's happening. You do not have the coordinates relative to your canvas, but relative to your viewport. It also depends on your browser whether or not they include padding.
Convert them to normal coordinates. In your case this involves substracting the offset of the canvas.

Categories

Resources