Created raster is not following mouse - javascript

Icon moves when I move the mouse, but it doesn't move to the last position when I stop moving.
I used Paper.js for this.
My code:
function setMousePosition(data) {
var yyy;
var deltaX;
for (var i = 0; i < playersData.length; i++) {
var element = playersData[i];
if (element.playerName == data.playerName) {
// element.cursor.position = new Point(data.position[1], data.position[2]);
deltaX = (data.position[1] - element.cursor.position.x) / (100);
yyy = (data .position[2] - element.cursor.position.y) / (100);
var lastx = element.cursor.position.x + deltaX;
var lasty = element.cursor.position.y + yyy;
element.cursor.position = new Point(lastx,lasty);
}
}
}
Icon doesn't move to cursor end position.

Related

How to store X and Y coordinates, after clicking on a button to store it

im trying to store the x and y coordinates after clicking on the canvas, i can set a marker position, i can show the x an y coordinates and a picture of a marker on that position, but now i want to store these coordinates so that when you reload the web browser, the marker position wil still be at his place where you first placed it.
full code down..
var context = (this.canvas.nativeElement as HTMLCanvasElement).getContext("2d")
//Map sprite
var mapSprite = new Image();
mapSprite.src = "http://antyradar.info/wp-content/uploads/commercial-tumilty-design-commercial-floor-plans.jpg";
var Marker = function () {
this.Sprite = new Image();
this.Sprite.src = "https://www.lasvegas-waterdelivery.com/wp-content/uploads/2016/07/5gal-cropped.png"
this.Width = 12;
this.Height = 20;
this.XPos = 0;
this.YPos = 0;
}
var Markers = new Array();
var rect = (this.canvas.nativeElement as HTMLCanvasElement).getBoundingClientRect();
var mouseClicked = function (mouse) {
// Get current mouse coords
var mouseXPos = (mouse.x - rect.left);
var mouseYPos = (mouse.y - rect.top);
console.log("x: " + mouseXPos);
console.log("y: " + mouseYPos)
console.log("Marker added");
// Move the marker when placed to a better location
var marker = new Marker();
marker.XPos = mouseXPos - (marker.Width * 37.7);
marker.YPos = mouseYPos - (marker.Height * 7);
Markers.push(marker);
for (var i = 0; i < Markers.length; i++) {
if(i > 1){
Markers.splice(marker);
}
}
sessionStorage.setItem('Marker', JSON.stringify(marker));
let store = sessionStorage.getItem('Marker');
console.log(store);
var remember = function(){
return store;
}
}
// Add mouse click event listener to canvas
/* (this.canvas.nativeElement as HTMLCanvasElement).addEventListener("mousedown", mouseClicked, false); */
var firstLoad = function () {
context.font = "15px Georgia";
context.textAlign = "center";
}
firstLoad();
var main = function () {
draw();
};
var width = (this.canvas.nativeElement as HTMLCanvasElement).width
var height = (this.canvas.nativeElement as HTMLCanvasElement).height
var draw = function () {
// Clear Canvas
context.fillStyle = "#000";
context.fillRect(0, 0, width, height);
// Draw map
// Sprite, X location, Y location, Image width, Image height
// You can leave the image height and width off, if you do it will draw the image at default size
context.drawImage(mapSprite, 0, 0, 700, 700);
// Draw markers
for (var i = 0; i < Markers.length; i++) {
var tempMarker = Markers[i];
// Draw marker
context.drawImage(tempMarker.Sprite, tempMarker.XPos, tempMarker.YPos, tempMarker.Width, tempMarker.Height);
}
};
setInterval(main, (1000 / 10)); // Refresh 60 times a second
}
You can use Window.sessionStorage to store your coordinates.
sessionStorage.setItem('Marker', JSON.stringify(marker));
If this is ionic 3 store the information in a Provider too keep it consistent from page to page/on refresh or use a service for ionic 4 (https://www.youtube.com/watch?v=MUvDM55PN9k - tutorial). To keep the information after closing and opening the app you could use the ionic file plugin https://ionicframework.com/docs/native/file or other such native storage.

From Paperscript to Javascript

I'm trying to convert one of the Paper.js library examples (http://paperjs.org/examples/smoothing/) from PaperScript to Javascript. Following the documentation, I have
Made the scope global
Installed the event handlers onFrame and onResize
Created a tool and installed the event handlers onMouseMove and onMouseDown
But the canvas is not shown. I only see a couple of small blue lines: AFAIK the problem lies in the view.onFrame() function, since commenting that out at least I can see the shape, but not interact with it. The JS console dosen't show any error. What is missing?
// Make the paper scope global, by injecting it into window
paper.install(window);
window.onload = function () {
// Setup directly from canvas id:
paper.setup('myCanvas');
// Create tool
tool = new Tool();
var width, height, center;
var points = 10;
var smooth = true;
var path = new Path();
var mousePos = view.center / 2;
var pathHeight = mousePos.y;
path.fillColor = 'black';
initializePath();
function initializePath() {
center = view.center;
width = view.size.width;
height = view.size.height / 2;
path.segments = [];
path.add(view.bounds.bottomLeft);
for (var i = 1; i < points; i++) {
var point = new Point(width / points * i, center.y);
path.add(point);
}
path.add(view.bounds.bottomRight);
path.fullySelected = true;
}
view.onFrame = function (event) {
pathHeight += (center.y - mousePos.y - pathHeight) / 10;
for (var i = 1; i < points; i++) {
var sinSeed = event.count + (i + i % 10) * 100;
var sinHeight = Math.sin(sinSeed / 200) * pathHeight;
var yPos = Math.sin(sinSeed / 100) * sinHeight + height;
path.segments[i].point.y = yPos;
}
if (smooth)
path.smooth({ type: 'continuous' });
}
tool.onMouseMove = function (event) {
mousePos = event.point;
}
tool.onMouseDown = function (event) {
smooth = !smooth;
if (!smooth) {
// If smooth has been turned off, we need to reset
// the handles of the path:
for (var i = 0, l = path.segments.length; i < l; i++) {
var segment = path.segments[i];
segment.handleIn = segment.handleOut = null;
}
}
}
// Reposition the path whenever the window is resized:
view.onResize = function (event) {
initializePath();
}
}
To try it: https://jsfiddle.net/1rtkbp9s/
Found the solution (credits to Stefan Krüger of the Paper.js Google Group):
var mousePos = view.center / 2;
Should have been:
var mousePos = view.center.divide(2);
The fact is that Math functions should be used instead of operators for Point and Size object... and I didn't realize that view.center IS a Point object: http://paperjs.org/reference/view/#center

HTML5 Canvas - Drag and Drop co-ordinates on rescale

//VARIABLES
//Drag Object Size
dragRadius = 100;
//Destination Size
destHeight = 434;
destWidth = 220;
var RosieDrag = new lib.RosieDrag();
//Drag Object Creation
//Placed inside a container to hold both label and shape
var test = new lib.test();
stage.addChild(test);
test.x = 525;
test.y = 1035;
var dragger = new createjs.Container();
dragger.x = 250;
dragger.y = 460;
dragger.addChild(RosieDrag);
dragger.setBounds(100, 100, dragRadius*2, dragRadius*2);
//DragRadius * 2 because 2*r = width of the bounding box
var RosieDrop = new lib.RosieDrop();
var destination = new createjs.Container();
destination.x = 900;
destination.y = 240;
destination.setBounds(950, 350, 100, 100);
destination.addChild(RosieDrop);
//DRAG FUNCTIONALITY =====================
dragger.on("pressmove", function(evt){
evt.currentTarget.x = evt.stageX;
evt.currentTarget.y = evt.stageY;
stage.update(); //much smoother because it refreshes the screen every pixel movement instead of the FPS set on the Ticker
if(intersect(evt.currentTarget, destination)){
evt.currentTarget.alpha=0.2;
}else{
evt.currentTarget.alpha=1;
}
});
//Mouse UP and SNAP====================
dragger.on("pressup", function(evt) {
if(intersect(evt.currentTarget, destination)){
test.gotoAndPlay(5);
dragger.x = destination.x + destWidth/2;
dragger.y = destination.y + destHeight/2;
dragger.alpha = 1;
stage.update(evt);
}
});
//Tests if two objects are intersecting
//Sees if obj1 passes through the first and last line of its
//bounding box in the x and y sectors
//Utilizes globalToLocal to get the x and y of obj1 in relation
//to obj2
//PRE: Must have bounds set for each object
//Post: Returns true or false
function intersect(obj1, obj2){
var objBounds1 = obj1.getBounds().clone();
var objBounds2 = obj2.getBounds().clone();
var pt = obj1.globalToLocal(objBounds2.x, objBounds2.y);
var h1 = -(objBounds1.height / 2 + objBounds2.height);
var h2 = objBounds2.width / 2;
var w1 = -(objBounds1.width / 2 + objBounds2.width);
var w2 = objBounds2.width / 2;
if(pt.x > w2 || pt.x < w1) return false;
if(pt.y > h2 || pt.y < h1) return false;
return true;
}
//Adds the object into stage
stage.addChild(destination, dragger);
stage.mouseMoveOutside = true;
stage.update();
Hi,
I've made a simple drag and drop in a canvas. It works fine but when the canvas resizes to the window it changes the position of the object when it is picked up and also of the drop area (Interestingly it still draws things in the right position and places the object in the right position after it is dropped.
I'm sure I'm missing something simple, here's my code:

paper.js animate point on graph

I'm trying to build an animated graph with paper.js that can react to different input. So I want to smoothly animate one point vertically to a different point.
I've looked at different examples and the closest ones to mine is this one:
paper.tool.onMouseDown = function(event) {
x = event.event.offsetX;
y = event.event.offsetY;
paper.view.attach('frame', moveSeg);
}
var x;
var y;
function moveSeg(event) {
event.count = 1;
if(event.count <= 100) {
myPath.firstSegment.point._x += (x / 100);
myPath.firstSegment.point._y += (y / 100);
for (var i = 0; i < points - 1; i++) {
var segment = myPath.segments[i];
var nextSegment = segment.next;
var vector = new paper.Point(segment.point.x - nextSegment.point.x,segment.point.y - nextSegment.point.y);
vector.length = length;
nextSegment.point = new paper.Point(segment.point.x - vector.x,segment.point.y - vector.y);
}
myPath.smooth();
}
}
This Code animates one Point to the click position, but I couldn't change it to my needs.
What I need is:
var aim = [120, 100];
var target = aim;
// how many frames does it take to reach a target
var steps = 200;
// Segment I want to move
myPath.segments[3].point.x
And then I dont know how to write the loop that will produce a smooth animation.
example of the graph:
I worked out the answer. The following steps in paperscript:
Generate Path
Set aim for the point
OnFrame Event that does the moving (eased)
for further animations just change the currentAim variable.
var myPath = new Path({
segments: [[0,100],[50,100],[100,100]]});
// styling
myPath.strokeColor = '#c4c4c4'; // red
myPath.strokeWidth = 8;
myPath.strokeJoin = 'round';
myPath.smooth();
// where the middle dot should go
var currentAim = [100,100];
// Speed
var steps = 10;
//Animation
function onFrame(event) {
dX1 = (currentAim[0] - myPath.segments[1].point.x )/steps;
dY1 = (currentAim[1] - myPath.segments[1].point.y )/steps;
myPath.segments[1].point.x += dX1;
myPath.segments[1].point.y += dY1;
}

DIV rotate in Javascript

I am currently trying to rotate this div toward the mouse pointer, and it hasnt worked. I even tried going to a chat room about it. Currently, It sorta rotates toward the mouse...here is my code so far:
var x = 0;
var y = 0;
document.addEventListener("mousemove", function(event){
x = Number(event.pageX);
y = Number(event.pageY);
}, false);
setInterval(function(){
var boxX = document.getElementById('temp').style.left;
boxX = Number(boxX.substring(0, boxX.length - 1));
var boxX = screen.width * ((boxX)/100);
var boxY = document.getElementById('temp').style.top;
boxY = Number(boxY.substring(0, boxY.length - 1));
var boxY = screen.width * ((boxY)/100);
var slope = [Math.round(x - boxX),Math.round(y - boxY)];
//x,y
var angle = Math.round(Math.atan(slope[1]/slope[0]) *100) ;
document.getElementById('temp').style.transform = "translate(-50%,-50%) rotate(0deg)";
document.getElementById('temp').style.transform = "translate(-50%,-50%) rotate("+angle+"deg)";
}, 500);

Categories

Resources