How do I get mouse coordinates on Fabric.js? - javascript

I'm trying to read the X coordinate of a mouse click on Fabric.js.
Here is my code. The console logs undefined every time.
var canvas = new fabric.Canvas('c1');
canvas.on('mouse:down', function(e){
getMouse(e);
});
function getMouse(e) {
console.log(e.clientX);
}

The best fix is this method
Implementation:
function getMouseCoords(event)
{
var pointer = canvas.getPointer(event.e);
var posX = pointer.x;
var posY = pointer.y;
console.log(posX+", "+posY); // Log to console
}

To get coordinates based on set width and height on the canvas itself, use layerX and layerY property.
canvas.on('mouse:move', function(options) {
console.log(options.e.layerX, options.e.layerY);
});

Try this,
function getMouse(e) {
console.log(e.e.clientX);
}
Demo
Updated, as canvas events takes the options as an argument not an event like,
canvas.on('mouse:down', function(options){
getMouse(options);// its not an event its options of your canvas object
});
function getMouse(options) {
console.log(options);// you can check all options here
console.log(options.e.clientX);
}

just use e.e.clientX
or
e.e.clientY
for getting positions

Maybe this will help:
//Convert To Local Point
function toLocalPoint(event, canvas) {
var offset = fabric.util.getElementOffset(canvas.lowerCanvasEl), localX = event.e.clientX - offset.left, localY = event.e.clientY - offset.top;
return new fabric.Point(localX, localY);
}

Related

Change pinch-zoom sensitivity in fabric.js

I have a custom built fabric.js bundle with touch support. Now I can scale any object with the pinch-zoom gesture. The problem is the zoom is really really sensitive, I barely move my fingers and the object is hugely scaled.
I couldn't find much information in the documents about how I can change the sensitivity. I know Event.js is used to handle the touch events within fabric.js. Is there any way I can change this sensitivity?
Ok, I ended up implementing touch controls myself, this is the code I made. This code was placed on the added event of my custom fabric.js object.
////////////////////////////// Touch event handlers
// Add listener event for pinch-zoom
var bbScope = this;
var hammer = new Hammer.Manager(this.canvas.upperCanvasEl);
var pinch = new Hammer.Pinch();
hammer.add([pinch]);
hammer.on('pinch', function (ev) {
// Set the scale and render only if we have a valid pinch (inside the object)
if (bbScope._validPinch) {
bbScope.set('scaleX', ev.scale);
bbScope.set('scaleY', ev.scale);
bbScope.canvas.renderAll();
}
});
hammer.on('pinchend', function (ev) {
bbScope._validPinch = false;
});
hammer.on('pinchcancel', function (ev) {
bbScope._validPinch = false;
});
hammer.on('pinchstart', function (ev) {
// Convert mouse coordinates to canvas coordinates
ev.clientX = ev.center.x;
ev.clientY = ev.center.y;
// Check if the pinch was started inside this object
if (bbScope.canvas) {
var p = bbScope.canvas.getPointer(ev);
bbScope._validPinch = bbScope.containsPoint(p);
}
else {
bbScope._validPinch = false;
}
});

Receiving the coordinates of a mouse drag

I want to get coordinates of a mouse drag.
I have canvas and inside him I draw same object after I want to get the coordinates of the new mouse (pixel) grab the object,
my code is in javascript.
my object not in tag elemnts of html just drawing inside the canvas with pixel and I want to grab him with mouse and need the new coordination of the mouse.
Thanks,
Canvas is a kind of 2d image element/tag, so there is no direct way to drag the objects inside canvas.
You need to listen for mouse events inside the canvas, and repaint the canvas based on these events.
Listen these 3 events for dragging the objects inside canvas
function handleMouseDown(e) {
var mousePos = getMousePosition(canvas, e);
// if current position matches the object postion
// set a flag and monitor mouse move and mouse up event
}
function handleMouseUp(e) {
var mousePos = getMousePosition(canvas, e);
//if your flag is true, then move the object to here and reset flag
}
function handleMouseMove(e) {
var mousePos = getMousePosition(canvas, e);
//Handle if you need smooth drag experience
}
function getMousePosition(canvas, e) {
var boundary = canvas.getBoundingClientRect();
// (e.clientX, e.clientY) => Mouse coordinates wrt whole browser
// (boundary.left, boundary.top) => Canvas starting coordinate
return {
x: e.clientX - boundary.left,
y: e.clientY - boundary.top
};
}
var canvas = document.getElementById('canvasId');
canvas.addEventListener('mousemove', handleMouseMove, false);
canvas.addEventListener('mousedown', handleMouseDown, false);
canvas.addEventListener('mouseup', handleMouseUp, false);

EaselJS - How is mouse movement accessed?

Inside an object (created based on this tutorial), I have the following code. In this code, the lines:
event.target.x = evt.stageX;
event.target.y = evt.stageY;
are wrong. What should they be to access the mouse movement?:
(function() {
....
var p = createjs.extend(Card, createjs.Container);
p.setup = function() {
this.on("pressmove", this.handlePressMove);
....
p.handlePressMove = function (event) {
event.target.x = evt.stageX; //"Event" is wrong. So is "evt"
event.target.y = evt.stageY;
stage.setChildIndex(this, stage.getNumChildren()-1);
stage.update();
}
}
}());
Your code sample uses evt.stageX instead of event.stageX. All MouseEvents will have a stageX and stageY, which is the position the mouse was in when it fired the event. I think your code came from this tutorial which uses evt exlusively.
Additionally, MouseEvents have a rawX and rawY on pressMove events, which give you the x/y outside of the canvas element. There is no clientX or clientY on EaselJS MouseEvents.
Here is a quick sample using the stageX/stageY.
http://jsfiddle.net/lannymcnie/suva8vt3/
Snippet:
shape.on("pressmove", function(event) {
shape.x = event.stageX;
shape.y = event.stageY;
});

How to change image size based on the element's distance in javascript

I'd like to draw a line that connects two circles, but when the window is being re-sized, the distance between the two circles changes therefore the height of the line image should change accordingly. Here is what I have now but it only does it once when the page loads, but I want the image height to be dynamically changing as the window is being re-sized:
function getDistance(id1, id2){
distX = id1.offsetLeft - id2.offsetLeft;
distY = id1.offsetTop - id2.offsetTop;
distance = Math.sqrt(distX*distX + distY*distY);
return distance;
console.log(distance);
}
var myImage = new Image(50, 100);
myImage.src = 'images/line.png';
myImage.height = getDistance(circle1, circle2);
document.getElementById("line").appendChild(myImage);
You have to add an event listener to the window resize event.
Add the following snippet on the end of your code:
window.addEventListener('resize', function(){
myImage.height = getDistance(circle1, circle2);
}, false);
Doing this way instead of assigning an event on window.onresize allows binding multiple functions to the event.
You can also use jQuery if you have it loaded on your site:
$(window).bind('resize',function(){/*code*/});
Try this:
var myImage = new Image(50, 100);
myImage.id = 'line-image';
myImage.src = 'images/line.png';
document.getElementById("line").appendChild(myImage);
window.onresize = function() {
document.getElementById('line-image').height = getDistance(circle1, circle2);
}

Canvas Drawing Application Wont Work in Firefox

I'm working on this little drawing application type thing, but it won't work in Firefox. It works fine in chrome though. Here's the javascript, then I just have a regular old canvas element in HTML. Any help is appreciated!
/* FOR THE DRAWING APPLICATION */
/* =========================== */
var canvasMouse, contextMouse;
var started = false;
var x, y;
function initMouse() {
// Get the drawing canvas
canvasMouse = document.getElementById('drawing');
contextMouse = canvasMouse.getContext('2d');
// Add some event listeners so we can figure out what's happening
// and run a few functions when they are executed.
canvasMouse.addEventListener('mousemove', mousemovement, false);
canvasMouse.addEventListener('mousedown', mouseclick, false);
canvasMouse.addEventListener('mouseup', mouseunclick, false);
}
function mouseclick() {
// When the mouse is clicked. Change started to true and move
// the initial position to the position of the mouse
contextMouse.beginPath();
contextMouse.moveTo(x, y);
started = true;
}
function mousemovement(e) {
// Get moust position
x = e.offsetX;
y = e.offsetY;
// If started is true, then draw a line
if(started) {
contextMouse.lineTo(x, y);
contextMouse.stroke();
}
}
function mouseunclick() {
// Change started to false when the user unclicks the mouse
if(started) {
started = false;
}
}
Any ideas?
offsetX and offsetY are not supported in firefox (see compatibility table here). Instead you need to use layerX and layerY.
The following will work in firefox (see fiddle):
/* FOR THE DRAWING APPLICATION */
/* =========================== */
var canvasMouse, contextMouse;
var started = false;
var x, y;
function initMouse() {
// Get the drawing canvas
canvasMouse = document.getElementById('drawing');
contextMouse = canvasMouse.getContext('2d');
// Add some event listeners so we can figure out what's happening
// and run a few functions when they are executed.
canvasMouse.addEventListener('mousemove', mousemovement, false);
canvasMouse.addEventListener('mousedown', mouseclick, false);
canvasMouse.addEventListener('mouseup', mouseunclick, false);
}
function mouseclick(e) {
// When the mouse is clicked. Change started to true and move
// the initial position to the position of the mouse
// Get moust position
x = e.layerX;
y = e.layerY;
console.log("coords", x, y);
contextMouse.beginPath();
contextMouse.moveTo(x, y);
started = true;
}
function mousemovement(e) {
// Get mouset position
x = e.layerX;
y = e.layerY;
console.log("coords", x, y);
// If started is true, then draw a line
if(started) {
contextMouse.lineTo(x, y);
contextMouse.stroke();
}
}
function mouseunclick() {
// Change started to false when the user unclicks the mouse
if(started) {
started = false;
}
}
initMouse();
If you want to avoid browser specific conditional code and / or your canvas element is offset within the DOM hierarchy (read the limitations of layerX and layerY in the compatibility table linked to above), there may be an argument for using jQuery and its position() method.

Categories