I am trying to make an image object rotate in accordance to the mouse being clicked down on that image and the angle of the mouse to the center of the object.
Think of a unit circle and having the image being rotated about the circle based on where the mouse is on that circle.
I currently have
var stage = new Kinetic.Stage({
container: "container",
width: 800,
height: 500,
id: "myCanvas",
name: "myCanvas"
});
var layer = new Kinetic.Layer();
//gets the canvas context
var canvas = stage.getContainer();
var mousePosX;
var mousePosY;
var mouseStartAngle;
var selectedImage;
var mouseAngle;
var mouseStartAngle;
console.log(canvas)
var shiftPressed
window.addEventListener('keydown', function (e) {
if (e.keyCode == "16") {
shiftPressed = true;
}
console.log(shiftPressed)
}, true);
window.addEventListener('keyup', function (e) {
if (e.keyCode == "16") {
shiftPressed = false;
}
console.log(shiftPressed)
}, true);
function drawImage(imageObj) {
var dynamicImg = new Kinetic.Image({
image: imageObj,
x: stage.getWidth() / 2 - 200 / 2,
y: stage.getHeight() / 2 - 137 / 2,
width: 100, //imageObj.width,
height: 100, // imageObj.height,
draggable: true,
offset: [50,50] //[(imageObj.width/2), (imageObj.height/2)]
});
dynamicImg.on('mousedown', function () {
selectedImage = this;
console.log("x: " + this.getX())
console.log("y: " + this.getY())
var mouseStartXFromCenter = mousePosX - (this.getX() + (this.getWidth() / 2));
var mouseStartYFromCenter = mousePosY - (this.getY() + (this.getHeight() / 2));
mouseStartAngle = Math.atan2(mouseStartYFromCenter, mouseStartXFromCenter);
if (shiftPressed) {
//console.log("trying to switch draggable to false");
//console.log(this)
this.setDraggable(false);
}
});
dynamicImg.on('mouseup mouseout', function () {
//console.log('mouseup mouseout')
this.setDraggable(true);
});
dynamicImg.on('mouseover', function () {
document.body.style.cursor = 'pointer';
});
dynamicImg.on('mouseout', function () {
document.body.style.cursor = 'default';
});
imageArray.push(dynamicImg);
layer.add(dynamicImg);
stage.add(layer);
}
var imageObj = new Image();
imageObj.onload = function () {
drawImage(this);
};
imageObj.src = 'http://localhost:60145/Images/orderedList8.png';
function getMousePos(evt) {
var rect = canvas.getBoundingClientRect();
return {
x: evt.clientX - rect.left,
y: evt.clientY - rect.top
};
}
canvas.addEventListener('mouseup', function () {
selectedImage = undefined;
});
canvas.addEventListener('mousemove', function (evt) {
mousePos = getMousePos(evt);
//console.log('Mouse position: ' + mousePos.x + ',' + mousePos.y)
mousePosX = mousePos.x;
mousePosY = mousePos.y;
if (selectedImage != undefined) {
mouseXFromCenter = mousePosX - selectedImage.getX();
mouseYFromCenter = mousePosY - selectedImage.getY();
mouseAngle = Math.atan2(mouseYFromCenter, mouseXFromCenter);
var rotateAngle = mouseAngle - mouseStartAngle;
selectedImage.setRotation(rotateAngle);
}
}, false);
the code has a couple things to it.
-It should only allow a rotate if 'shift' is pressed and mousedown event happens on an image.
-it needs to maintain the dynamic image drawing as they will be populating the canvas dynamically over the life of the page.
here is a good example of something similar i want to happen, but just simply cannot get it to work in canvas/kineticjs.
http://jsfiddle.net/22Feh/5/
I would go simpler way using dragBoundFunc. http://jsfiddle.net/bighostkim/vqGmL/
dragBoundFunc: function (pos, evt) {
if (evt.shiftKey) {
var x = this.getX() - pos.x;
var y = this.getY() - pos.y;
var radian = Math.PI + Math.atan(y/x);
this.setRotation(radian);
return {
x: this.getX(),
y: this.getY()
}
} else {
return pos;
}
}
My mistake, I misread your question. You were essentially missing one line:
layer.draw();
Hold shift and move the mouse, you'll see it rotates nicely.
http://jsfiddle.net/WXHe6/2/
canvas.addEventListener('mousemove', function (evt) {
mousePos = getMousePos(evt);
//console.log('Mouse position: ' + mousePos.x + ',' + mousePos.y)
mousePosX = mousePos.x;
mousePosY = mousePos.y;
if (selectedImage != undefined) {
mouseXFromCenter = mousePosX - selectedImage.getX();
mouseYFromCenter = mousePosY - selectedImage.getY();
mouseAngle = Math.atan2(mouseYFromCenter, mouseXFromCenter);
var rotateAngle = mouseAngle - mouseStartAngle;
selectedImage.setRotation(rotateAngle);
layer.draw(); // <--------------- right here
}
}, false);
You should be more clear what your .on() events do. In your code, the mousedown on the shape doesn't do anything other than calculate an mouseStartAngle, but doesn't do anything. And your mouseUp on the shape event doesn't do much either. It's your browser/client mousedown/mouseup that do all the work, and that's why it rotates properly on some clicks and not others.
For setting the rotation you have many options, here are two:
Option one: set the radians manually on mousedown
dynamicImg.on('mousedown', function () {
dynamicImg.setRotation(mouseStartAngle); //set the rotation degree
layer.draw(); // redraw the layer
}
Option two: let kineticJS animate the rotation for you
dynamicImg.on('mousedown', function () {
dynamicImg.transitionTo({
duration: 1, // length of animation in seconds
rotation: mouseStartAngle // your angle, in radians
});
}
your updated jsfiddle: http://jsfiddle.net/WXHe6/1/
Here are some additional notes:
The reason you are having trouble is because your code is structured is a bit of a messy manner, sorry to say. You are mixing browser events with and adding listeners to the canvas rather than using built-in kineticJS functionality, for example, you could use stage.getUserPosition() to get the mouse coordinates. Unless you have some dire need to structure your project this way, try to avoid it.
What I do like is that you have created functions to break up your code, but on the down-side you have multiple functions doing the same thing, like calculating and updating the rotation angle. Why not just make one function to get the angle?
Some Tips:
Try using mainly KineticJS for functionality (I know you'll need event listeners for buttons like SHIFT). What I mean is, use things like stage.getUserPosition(); to get the mouse/touch coordinates, rather than evt.clientX, it's cleaner, and the work has been done for you already, no need to re-invent the wheel.
Make one function for setting/getting the rotation for a shape. Then you can call it whenever you want. (use less repetitive code)
If you don't want the shape to be draggable when shift is clicked, you should set that before an item is clicked. You have button listeners so you can either disable rotation for all shapes when shift is pressed down, or just for a shape on that is under the cursor.
imageArray.push(dynamicImg); not sure if you really need this, if you need to access all the elements as an array, you could alway do layer.getChildren(); to get all the images in the layer, or access them numerically like layer.getChildren()[0]; (in creation order)
Related
In short, I'm making an app where people can collaborate and draw over an image.
I have a proof-of-concept right now, but I've noticed that the drawings show up with incorrect scale on the other person's browser if the two people collaborating are using different sized windows.
The solution is to normalize the drawing input so that points are expressed as a percentage of the canvas that they span, instead of absolute pixel values. However, I don't know how to do this in FabricJS. Finally, I need to be certain that the solution works when zoomed as well.
Any advice for normalizing drawing input would be appreciated! For reference, here is my code so far.
Be warned: I've never used FabricJS before, so this code sample is a mashup of several blog posts and SO answers. This is not good code and will be refactored entirely if FabricJS is the library I decide to go with
The important lines have been commented
document.addEventListener('DOMContentLoaded', () => {
const room = window.location.href.split('/').pop();
const socket = io.connect();
socket.on('connect', () => {
socket.emit('room', room);
});
var canvas = new fabric.Canvas('map', {
isDrawingMode: true
});
let size = Math.min(window.innerWidth, window.innerHeight);
canvas.setHeight(size);
canvas.setWidth(size);
var img = new Image();
img.onload = function () {
canvas.setBackgroundImage(img.src, canvas.renderAll.bind(canvas), {
width: canvas.width,
height: canvas.height,
});
};
img.src = "/images/map.jpg";
canvas.wrapperEl.addEventListener('wheel', (e) => {
if (e.deltaY <= 0) {
canvas.zoomToPoint({
x: e.offsetX,
y: e.offsetY
}, canvas.getZoom() * 1.1);
} else {
canvas.zoomToPoint({
x: e.offsetX,
y: e.offsetY
}, canvas.getZoom() * 0.9);
}
});
canvas.on('path:created', function (e) {
// This is where I need to normalize the path data
canvas.remove(fabric.Path.fromObject(JSON.stringify(e.path)));
socket.emit('draw_line', {
line: e.path.toJSON(),
room: room
});
});
socket.on('draw_line', function (path) {
// This is where I need to convert the path data from percentages to real size
fabric.util.enlivenObjects([path], function (objects) {
objects.forEach(function (o) {
canvas.add(o);
});
});
});
var panning = false;
canvas.on('mouse:up', function (e) {
panning = false;
});
canvas.on('mouse:out', function (e) {
panning = false;
});
canvas.on('mouse:down', function (e) {
panning = true;
});
canvas.on('mouse:move', function (e) {
//allowing pan only if the image is zoomed.
if (panning && e && e.e && e.e.shiftKey) {
var delta = new fabric.Point(e.e.movementX, e.e.movementY);
canvas.relativePan(delta);
}
});
});
A general working solution is that you give your drawing board a virtual fixed dimension:
15.000 x 15.000 for example.
Then in each client app you make the canvas as big as you want, for example 1000 x 1000 and another will get 800 x 800.
Setting the canvas zoom to each one will make possible to see the drawing as big as needed mantaining the same point values on the 15.000 space coordinates.
The drawing thickness will probably change with zoom level.
canvas.setZoom(1000/15000) and canvas.setZoom(800/15000) should be enough.
If it does not work, there is a bug somewhere, that should be fixed.
I am trying to develop a simple cross-platform game, and trying to move a PhysicsSprite with a Body to the position I touched/clicked, using Cocos2D-JS.
Here is the code that I have:
var TAG_SPRITE = 1;
var AnimationLayer = cc.Layer.extend({
space:null,
ctor:function (space) {
this._super();
this.space = space;
this.init();
},
init:function () {
this._super();
var winsize = cc.director.getWinSize();
//init physics sprite
var spriteHead = new cc.PhysicsSprite(res.Head_png);
var headContentSize = spriteHead.getContentSize();
//init body
var headBody = new cp.Body(1, cp.momentForBox(1, headContentSize.width, headContentSize.height));
headBody.p = cc.p(winsize.width / 2, winsize.height / 3);
this.space.addBody(headBody);
//init shape
var headShape = new cp.CircleShape(headBody, headContentSize.width / 2, cp.v(0, 0));
headShape.setFriction(0.3);
headShape.setElasticity(0.8);
this.space.addShape(headShape);
spriteHead.setBody(headBody);
this.addChild(spriteHead, 0, TAG_SPRITE);
//for mobile
if('touches' in cc.sys.capabilities ){
cc.eventManager.addListener({
event: cc.EventListener.TOUCH_ONE_BY_ONE,
swallowTouches: true,
onTouchBegan:function (touch, event) {
cc.log('touch began');
event.getCurrentTarget().moveSprite(touch.getLocation());
return true;
},
onTouchMoved: function (touch, event) {
},
onTouchEnded: function (touch, event) {
},
onTouchCancelled: function (touch, event) {
}
}, this);
}
//for desktop
else if ('mouse' in cc.sys.capabilities ) {
cc.eventManager.addListener({
event: cc.EventListener.MOUSE,
onMouseUp: function (event) {
event.getCurrentTarget().moveSprite(event.getLocation());
}
}, this);
}
},
moveSprite:function(position) {
cc.log('move to: ' + position.x + ',' + position.y);
var sprite = this.getChildByTag(TAG_SPRITE);
var moveAction = new cc.moveTo(1, position);
sprite.runAction(moveAction);
}
});
As I see the logs from the logcat, it can handle touch events but cannot move the sprite. When I convert the PhysicsSprite to just Sprite object and remove all other Body and Shape stuff, it can be moved to the location that I touch.
The problem is that I can move the PhysicsSprite in the browser whereas I cannot do that in my Android phone.
Note: I use Chipmunk physics engine
I don't know this is the real solution or should be considered as a workaround but the code below works fine for both web and Android. But still don't know why the code in the question doesn't work for Android while it does for the web. (It would make more sense if it didn't work for both...)
I tried to move body of the sprite instead of itself. The new moveSprite method is like that:
moveSprite: function(sprite){
cc.log('move to: ' + position.x + ',' + position.y);
var sprite = this.getChildByTag(TAG_SPRITE);
var body = sprite.getBody();
var velocity = 300;
this.moveWithVelocity(body, position, velocitiy);
}
moveWithVelocity is the custom function that I created in the same Layer, moving the Body to the destination point with a particular velocity:
moveWithVelocity: function(body, destination, velocity){
var deltaX = destination.x - body.p.x;
var deltaY = destination.y - body.p.y;
var distance = Math.sqrt(Math.pow(deltaX,2) + Math.pow(deltaY,2));
var time = distance / velocity;
var velocityX = deltaX / time;
var velocityY = deltaY / time;
//start the action with the calculated velocity in the calculated direction
body.applyImpulse(cc.v(velocityX, velocityY), cc.v(0,0));
//stop the sprite (or body here) when duration of movement is time out (or when the sprite/body arrives its destination)
setTimeout(function(){
body.setVel(cc.v(0,0));
}, time*1000);
}
Hope this helps anyone encountered the same problem.
I am trying to free draw rectangle on canvas.
Here's my JSFiddle.
Code:
var canvas1 = new fabric.Canvas("canvas2");
var freeDrawing = true;
var divPos = {};
var offset = $("#canvas2").offset();
$(document).mousemove(function(e) {
divPos = {
left : e.pageX - offset.left,
top : e.pageY - offset.top
};
});
$('#2').click(function() {
console.log("Button 2 cilcked");
// Declaring the variables
var isMouseDown = false;
var refRect;
// Setting the mouse events
canvas1.on('mouse:down', function(event) {
// Defining the procedure
isMouseDown = true;
// Getting yhe mouse Co-ordinates
// Creating the rectangle object
if (freeDrawing) {
var rect = new fabric.Rect({
left : divPos.left,
top : divPos.top,
width : 0,
height : 0,
stroke : 'red',
strokeWidth : 3,
fill : ''
});
canvas1.add(rect);
refRect = rect; // **Reference of rectangle object
}
});
canvas1.on('mouse:move', function(event) {
// Defining the procedure
if (!isMouseDown) {
return;
}
// Getting yhe mouse Co-ordinates
if (freeDrawing) {
var posX = divPos.left;
var posY = divPos.top;
refRect.setWidth(Math.abs((posX - refRect.get('left'))));
refRect.setHeight(Math.abs((posY - refRect.get('top'))));
canvas1.renderAll();
}
});
canvas1.on('mouse:up', function() {
// alert("mouse up!");
isMouseDown = false;
// freeDrawing=false; // **Disables line drawing
});
});
The problem that I am facing is after drawing a rectangle I am unable to move, resize or at least select the drawn rectangle.
Mistake is you are not adding the object finally when mouse is up. Just change the mouse:up event function like this:
canvas1.on('mouse:up', function() {
// alert("mouse up!");
canvas1.add(refRect);
isMouseDown = false;
// freeDrawing=false; // **Disables line drawing
});
It will work fine. :)
I am also facing the same issue, thanks for the solution provided. If you noticed in this fiddle, duplicate object is creating when moving the shape.
How to solve the issue.
$(document).ready(function(){
//Getting the canvas
var canvas1 = new fabric.Canvas("canvas2");
var freeDrawing = true;
var divPos = {};
var offset = $("#canvas2").offset();
$(document).mousemove(function(e){
divPos = {
left: e.pageX - offset.left,
top: e.pageY - offset.top
};
});
$('#2').click(function(){
console.log("Button 2 cilcked");
//Declaring the variables
var isMouseDown=false;
var refRect;
//Setting the mouse events
canvas1.on('mouse:down',function(event){
//Defining the procedure
isMouseDown=true;
//Getting yhe mouse Co-ordinates
//Creating the rectangle object
if(freeDrawing) {
var rect=new fabric.Rect({
left:divPos.left,
top:divPos.top,
width:0,
height:0,
stroke:'red',
strokeWidth:3,
fill:''
});
canvas1.add(rect);
refRect=rect; //**Reference of rectangle object
}
});
canvas1.on('mouse:move', function(event){
// Defining the procedure
if(!isMouseDown)
{
return;
}
//Getting yhe mouse Co-ordinates
if(freeDrawing) {
var posX=divPos.left;
var posY=divPos.top;
refRect.setWidth(Math.abs((posX-refRect.get('left'))));
refRect.setHeight(Math.abs((posY-refRect.get('top'))));
canvas1.renderAll();
}
});
canvas1.on('mouse:up',function(){
//alert("mouse up!");
canvas1.add(refRect);
isMouseDown=false;
//freeDrawing=false; // **Disables line drawing
});
});
});
JS Fiddle Link here.
http://jsfiddle.net/PrakashS/8u1cqasa/75/
None of the other answer's implementations worked for me. All seem to be un compatible with latest fabric.js versions or have important issues.
So I implemented my own (check the JS in the HTML sources)
https://cancerberosgx.github.io/demos/misc/fabricRectangleFreeDrawing.html?d=9
supports two modes: one that will create and update a rectangle onmousedown and another that won't and only create the rectangle onmouseup
doesn't depend on any other library other than fabric.js (no jquery, no react no nothing)
Doesn't use offsets or event.clientX, etc to track the coordinates. It just uses fabric event.pointer API to compute it. This is safe and compatible since it doesn't depend on the DOM and just on a fabric.js public API
carefully manages event listeners
TODO:
I probably will also add throttle support for mousemove
Thanks
I'm learning Javascript / Raphael and got stuck in what should be something really simple to solve. I need to move and rotate a number of figures with the mouse, but when I rotate them (with doubleclick) as:
rect1.dblclick(function() {
this.rotate('90');
});
the reference points I am using to keep track of the mouse also get rotated. In Processing I would use pushMatrix() and popMatrix(), but I can't find something similar for Raphael nor any simple examples using save() and restore() canvas (...not sure if they can be used here either).
Here is a working example.
var canvas = document.getElementById("the_canvas");
var paper = Raphael(canvas, '500', '500');
var rect1 = paper.rect(380,10,100,50).attr({fill: '#ddd', 'stroke': 'none', opacity: '0.8'});
var startX, startY;
function onstart() {
startX = this.attr('x');
startY = this.attr('y');
}
function onend() {
}
function onmove(dx, dy) {
this.attr({
x: startX + dx,
y: startY + dy
});
}
rect1.drag(onmove, onstart, onend);
//// ... problem here
rect1.dblclick(function() {
this.rotate('90');
});
Cheers,
I am trying to achieve something similar to the code below. When user is on the edge of a rectangle, the cursor points a pointer, otherwise cursor is an arrow.
shape.graphics.beginStroke("#000").beginFill("#daa").drawRect(50, 150, 250, 250);
shape.on("mousemove", function(evt) {
if (isOnEdges(evt)) {
evt.target.cursor = "pointer";
} else {
evt.target.cursor = "arrow";
}
});
Problems with the above code is:
Shape doesn't have a mousemove handler
how do i calculate if mouse is on the edge of a shape (isOnEdges function)
You can simply set the cursor on the shape, and ensure that you enableMouseOver on the stage:
var shape = new Shape();
shape.graphics.beginStroke("#000").beginFill("#daa").drawRect(50, 150, 250, 250);
shape.cursor = "pointer";
stage.enableMouseOver();
EaselJS will automatically determine when you are over the shape's bounds.
I have a similar problem:
container.on("pressmove", function (evt) {
this.x = evt.stageX + this.offset.x;
this.y = evt.stageY + this.offset.y;
if (this.allowDrop(board)) {
this.cursor = "pointer";
}
else {
this.cursor = "no-drop";
}
});
This code doesn't change my cursor in runtime.. I update the stage with a ticker.. so this is not the problem.