//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:
Related
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.
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.
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);
Basically I want to scroll a object along path. I've seen several threads looking for similar solution not using paper.js but i was wondering if this possible with paper.js. Or can someone give me a working jsfiddle of object follow svg curve because I couldn't get any thing to work. I ultimately want to have a chain of divs follow the path.
// vars
var point1 = [0, 100];
var point2 = [120, 100];
var point3 = [120, 150];
// draw the line
var path = new Path();
path.add(new Point(point1), new Point(point2), new Point(point3));
path.strokeColor = "#FFF";
path.closed = true;
// draw the circle
var circle = new Path.Circle(0,100,4);
circle.strokeColor = "#FFF";
// target to move to
var target = point2;
// how many frame does it take to reach a target
var steps = 200;
// defined vars for onFrame
var dX = 0;
var dY = 0;
// position circle on path
circle.position.x = target[0];
circle.position.y = target[1];
function onFrame(event) {
//check if cricle reached its target
if (Math.round(circle.position.x) == target[0] && Math.round(circle.position.y) == target[1]) {
switch(target) {
case point1:
target = point2;
break;
case point2:
target = point3;
break;
case point3:
target = point1;
break;
}
// calculate the dX and dY
dX = (target[0] - circle.position.x)/steps;
dY = (target[1] - circle.position.y)/steps;
}
// do the movement
//circle.position.x += dX;
//circle.position.y += dY;
}
Here is the jsfiddle:
http://jsfiddle.net/J9xgY/12/
Thanks!
You can find a point along a path with path.getPointAt(offset) where offset is measured in points along the length of the path. If you can calculate the position of a slider along its track, you can multiply that by the path.length to get an offset.
You can do this with an HTML slider or with a canvas element, as shown here:
// vars
var point1 = [0, 100];
var point2 = [120, 100];
var point3 = [120, 150];
// draw the line
var path = new Path();
path.add(new Point(point1), new Point(point2), new Point(point3));
path.strokeColor = "#FFF";
path.closed = true;
// draw the circle
var circle = new Path.Circle(0,100,4);
circle.strokeColor = "#FFF";
// slider
var sliderLine = new Path(new Point(10,30.5), new Point(210, 30.5));
sliderLine.strokeColor = '#FFF';
var sliderKnob = new Path.Circle(new Point(10,30.5), 5);
sliderKnob.fillColor = '#FFF';
var sliderHit = false;
function onMouseDown(event) {
if (event.item == sliderKnob) sliderHit = true;
}
function onMouseDrag(event) {
if (sliderHit === true) {
if (event.point.x > 10 && event.point.x < 210) {
sliderKnob.position.x = event.point.x;
}
else if (event.point.x < 11) {
sliderKnob.position.x = 10;
}
else if (event.point.x > 209) {
sliderKnob.position.x = 210;
}
// Get offset and set circle position
var percent = ( sliderKnob.position.x - 10 ) / 200;
circle.position = path.getPointAt(path.length * percent);
}
}
function onMouseUp(event) {
sliderHit = false;
}
jsfiddle: http://jsfiddle.net/J9xgY/13/
Click and drag the filled circle along the line to move the circle along the triangle.
I'm working on creating a tic-tac-toe game in canvas. I'm currently stuck at a point where I detect if there is a symbol(X or O) already at x/y cordinates on the canvas.
I tried using ImageData to check if an element is present but it returns an error if nothing is there. I also thought perhaps I could assign an ID to the square or the symbol. However that doesn't seem to be possible from what I've read.
Any help would be appreciated.
You can see the game running here http://jsfiddle.net/weeklygame/dvJ5X/30/
function TTT() {
this.canvas = document.getElementById('ttt');
this.context = this.canvas.getContext('2d');
this.width = this.width;
this.height = this.height;
this.square = 100;
this.boxes = [];
this.turn = Math.floor(Math.random() * 2) + 1;
this.message = $('.message');
};
var ttt = new TTT();
TTT.prototype.currentPlayer = function() {
var symbol = (this.turn === 1) ? 'X' : 'O';
ttt.message.html('It is ' + symbol + '\'s turn');
};
// Draw the board
TTT.prototype.draw = function(callback) {
// Draw Grid
for(var row = 0; row <= 200; row += 100) {
var group = [];
for(var column = 0; column <= 200; column += 100) {
group.push(column);
this.context.strokeStyle = 'white';
this.context.strokeRect(column,row,this.square,this.square);
};
this.boxes.push(group);
};
callback;
};
// Get center of the click area cordinates
TTT.prototype.cordinates = function(e) {
var row = Math.floor(e.clientX / 100) * 100,
column = Math.floor(e.clientY / 100) * 100;
return [row, column];
};
// Check if the clicked box has symbol
TTT.prototype.check = function(row, column) {
};
// Get cordinates and set image in container
TTT.prototype.click = function(e) {
var cordinates = ttt.cordinates(e),
x = cordinates[0] + 100 / 2,
y = cordinates[1] + 100 / 2,
image = new Image();
if (ttt.turn === 1) {
image.src = 'http://s8.postimg.org/tdp7xn6lt/naught.png';
ttt.turn = 2;
} else {
image.src = 'http://s8.postimg.org/9kd44xt81/cross.png';
ttt.turn = 1;
};
ttt.context.drawImage(image, x - (image.width / 2), y - (image.height / 2));
ttt.currentPlayer();
};
function render() {
ttt.draw($('#ttt').on("click", ttt.click));
ttt.currentPlayer();
};
(function init() {
render();
})();
Would it not be easier for you to keep track of the grid positions using an array. When you place something on the grid allocate that position in the array. That way rather than having to work out a way to read it from the Canvas you just look in the array. This also allows you to quickly redraw the canvas from the array when needed, such as when the screen resizes...
To detect which field was clicked, iterate through your 9 fields and check if the clicked position is in the area where the field is drawn.
To be able to do this, store the state of your fields (position and if it has a X, O or nothing in it). You should also store the 9 fields in an array, so you can easily iterate over them. I would store it in a two dimensional array (3x3).
function Field(x, y) {
this.x = x;
this.y = y;
this.value = null; // Can be null, 'X' or 'O'
}
Initialisation of the tic tac toe field:
var fields = [
[new Field(0,0), new Field(1,0), new Field(2,0)],
[new Field(0,1), new Field(1,1), new Field(2,1)],
[new Field(0,2), new Field(1,2), new Field(2,2)]
];
Iteration:
for (var y = 0; y <= 2; y++) {
for (var x = 0; x <= 2; x++) {
var field = fields[y][x];
// Do something with the field.
}
}
I would store the position of the fields with model coordinates. So you multiply the coordinates with a value to get the coordinates for drawing on the canvas.