I tried three different approaches but none worked.
I place two rectangles on the canvas and want to catch the object under the mouse cursor when a mousedown event occurred.
The stagemousedown works, but the objects are not found. Watching the debugger I see that the rectangle has still the drawrect coordinates, not the one that I set later. There is also a 'hitarea' which I don't know how to use since it is checked during hittest and getObjectUnderPoint.
Approach 1: makeButton creates a handler on lines 66ff -> it never fires
Approach 2: getObjectUnderPoint when a mousedown evt happens. -> returns always null
Approach 3: loop through each child and apply the hitttest -> returns always false.
I come from Java and C# and am far from being experienced in JS, but I had hoped that I could catch the mousedown with at least one approach.
What makes me wonder is that the x and y in the rectangle never change from the ones used during creation (0,0). That's not the current position which I set for example in 73 and 74!
I don't seem to find the REAL x and y of the object and neither does approaches 2 and 3. I wished, approach 1 would work since that makes the most sense to me.
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<link rel="stylesheet" href="./css/style.css">
<meta charset="utf-8" />
<title></title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/EaselJS/1.0.2/easeljs.js"></script>
<script>
function init() {
var followme = 0;
var canvas = document.getElementById("canvas");
var stage=new createjs.Stage(canvas);
var shape=new createjs.Shape();
var dispO = new createjs.Shape();
makeBtn(3,3);
makeBtn(300,300);
stage.on("stagemousedown", function (evt) {
followme = 1;
found=stage.getObjectUnderPoint(stage.mouseX, stage.mouseY,0)
if(found != null)
{
console.log(found);
}
var xxx=stage.children;
for (i=0; i<xxx.length;i++)
{
if (xxx[i].hitTest(stage.mouseX, stage.mouseY))
{
shape.alpha=1;
}
}
});
stage.on("stagemouseup", function (evt) {
followme = 0;
});
stage.update();
createjs.Ticker.setFPS(30);
createjs.Ticker.addEventListener("tick", handleTick);
function handleTick(event)
{
if ((followme === 1) && (dispO != null))
{
var difX = stage.mouseX - dispO.x - 100;
var difY = stage.mouseY - dispO.y - 50;
dispO.x += difX / 20;
dispO.y += difY / 20;
stage.update();
}
else
if(dispO != null)
{
var dmy=dispO;
}
}
function makeBtn(x,y)
{
shape = new createjs.Shape();
shape.graphics.beginStroke("black").setStrokeStyle(2, 0, 1).drawRect(0, 0, 200, 100);
dispO=shape;
dispO.mouseEventsEnabled = true;
var handler=dispO.on("mousedown",
function(event) {console.log(instance == this); },// true, "on" uses dispatcher scope by default.
null,
once=true,
'theButton',
useCapture=true
);
dispO.x=x;
dispO.y=y;
stage.addChild(dispO);
}
}
</script>
</head>
<body onload="init();">
<div id="outer">
<canvas id="canvas" width="500" height="600">
</canvas>
<menu id="controls">
</menu>
</div>
</body>
</html>
<script src="https://cdnjs.cloudflare.com/ajax/libs/EaselJS/1.0.2/easeljs.js"></script>
Your demo works fine -- its just that your square has no fill, so only the border is clickable. If you add a fill, then it works great:
https://jsfiddle.net/lannymcnie/ozcr6tna/
shape.graphics.beginStroke("black")
.setStrokeStyle(2, 0, 1)
.beginFill("white") // <----- Fill call
.drawRect(0, 0, 200, 100);
If you want the clickable area to be transparent, then you can use a hitArea. Just assign a different shape with a fill as a hitArea (and don't add that shape to the stage). Hit testing in EaselJS uses pixel fill - so if there are no pixels, then there is no hit!
Hope that helps!
Related
Thank you in advance for you help. I am hoping someone could provide some solid examples of some Javascript or jQuery animation for running around a baseball diamond rather than starting from scratch.
So far I've found at least 1 think that gets me close however needs much control introduced. I'm looking for tracking live progress so this would be conditional based on the batters progress around the bases. So if the batter hit a double, the animation would go to 2nd base and stop. Eventually I need to add functionality to interact with the circle but that'll be another story.
<!DOCTYPE html>
<head>
<meta charset="UTF-8">
<title>Untitled Document</title>
<script>
var context;
var x=100;
var y=200;
var dx=3;
var dy=3;
function init()
{
context= myCanvas.getContext('2d');
setInterval(draw,10);
}
function draw()
{
context.clearRect(0,0, 300,300);
context.beginPath();
context.fillStyle="#0000ff";
// Draws a circle of radius 20 at the coordinates 100,100 on the canvas
context.arc(x,y,20,0,Math.PI*2,true);
context.closePath();
context.fill();
// Boundary Logic
if( x<0 || x>300) dx=-dx;
if( y<0 || y>300) dy=-dy;
x+=dx;
y+=dy;
}
</script>
</head>
<body onLoad="init();">
<canvas id="myCanvas" width="300" height="300" > </canvas>
</body>
</html>
Lots of negative votes and I can see why, however its actually quite straightforward if you use svg and a library, eg Snap.
jsfiddle click to move between bases
Here's a run down of the process....
Firstly load an svg, just plucked one from the internet, and load it..
Snap.load( "https://upload.wikimedia.org/wikipedia/commons/8/89/Baseball_diamond_clean.svg", onSVGLoaded )
We need to create a route, simply log a mouse click to get its x,y which you can use to create a path...
s.click( setRoute );
function setRoute(ev, x,y) {
console.log('xy', ev, x, y); // a click will log coordinates so you can build path route
movePlayer(currentPath++);
if( currentPath > 3) currentPath = 0;
}
Once you've clicked on the points you want to have as the path, add them into the array....
// build our 'virtual path' and player to animate when clicked
function onSVGLoaded( frag ) {
s.append( frag );
s.click( setRoute )
paths = [
"M335,430L448,324", // these were logged from mouse click
"M453,325L337,210",
"M330,210L215,324",
"M215,325L330,436"
];
player = s.circle(335,430,10).attr({ fill: 'red' })
for( var c=0; c<paths.length; c++) {
pathList[c] = s.path(paths[c]).attr({ stroke: 'none' });
}
}
Finally, we can animate the movement...
function movePlayer( currentPath ) {
Snap.animate(0, pathList[currentPath].getTotalLength(), function( val ) {
var pt = pathList[currentPath].getPointAtLength( val );
player.attr({ cx: pt.x, cy: pt.y })
}, 2000)
}
edit: Heh, just seen how old this is, not sure why it popped up now!
Using Html5 Canvas
You can use linear interpolation to navigate your lines and you can use De Casteljau's algorithm to navigate around your Bezier Curve.
Using SVG
Svg Paths have built-in methods that give you the total length of the path: getTotalLength and also the X,Y at a specified length along the path: getPointAtLength. You can use these methods to navigate your lines and curves.
Does anyone know the best way to clear a canvas using paper.js
I tried the regular canvas clearing methods but they do not seem to work with paper.js
Html
<canvas id="myCanvas" style="background:url(images/graphpaper.jpg); background-repeat:no-repeat" height="400px" width="400px;"></canvas>
<button class="btn btn-default button" id="clearcanvas" onClick="clearcanvas();" type="button">Clear</button>
Javascript/Paperscript
<script type="text/paperscript" canvas="myCanvas">
// Create a Paper.js Path to draw a line into it:
tool.minDistance = 5;
var path;
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
function onMouseDown(event) {
// Create a new path and give it a stroke color:
path = new Path();
path.strokeColor = 'red';
path.strokeWidth= 3;
path.opacity="0.4";
// Add a segment to the path where
// you clicked:
path.add(event.point, event.point);
}
function onMouseDrag(event) {
// Every drag event, add a segment
// to the path at the position of the mouse:
path.add(event.point, event.point);
}
</script>
Regular clearing does not work because paper.js maintains a scene graph and takes care of drawing it for you. If you want to clear all items that you have created in a project, you need to delete the actual items:
project.activeLayer.removeChildren(); works as long as all your items are inside one layer. There is also project.clear() which removes everything, including the layer.
In case someone comes looking for an answer with little experience in Javascript, I made a simple example :
1) As Jürg Lehni mentioned project.activeLayer.removeChildren(); can be used to remove all items inside active layer.
2) To reflect the cleaning you have to call paper.view.draw();.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Circles</title>
<link rel="stylesheet" href="style.css">
<script type="text/javascript" src="paper-full.js"></script>
<script type="text/paperscript" canvas="canvas">
function onMouseUp(event) {
var circle = new Path.Circle({
center: event.middlePoint,
radius: event.delta.length / 2
});
circle.strokeColor = 'black';
circle.fillColor = 'white';
}
</script>
<script type="text/javascript">
paper.install(window);
window.onload = function () {
paper.setup('canvas');
document.getElementById('reset').onclick = function(){
paper.project.activeLayer.removeChildren();
paper.view.draw();
}
};
</script>
</head>
<body>
<canvas style="background-color: #eeeeed" id="canvas" resize></canvas>
<input id="reset" type="button" value="Reset"/>
</body>
</html>
CSS :
html,
body {
margin: 0;
overflow: hidden;
height: 100%;
}
/* Scale canvas with resize attribute to full size */
canvas[resize] {
width: 58%;
height: 100%;
}
you can use project.activeLayer.removeChildren(); for clear entire layer,
or you can add your new paths to group and remove all childrens in group
var myPath;
var group = new Group();
function onMouseDown(event) {
myPath = new Path();
}
function onMouseDrag(event) {
myPath.add(event.point);
}
function onMouseUp(event) {
var myCircle = new Path.Circle({
center: event.point,
radius: 10
});
myCircle.strokeColor = 'black';
myCircle.fillColor = 'red';
group.addChild(myCircle);
}
// connect your undo function and button
document.getElementById('clearbutton').onclick = btnClear;
function btnClear(){
group.removeChildren();
}
c.width = c.width; ctx.clearRect(0,0,c.width,c.height); should be a good catchall if you've not tried it.
Beware however - setting canvas width will reset the canvas state including any applied transforms.
A quick google took me to https://groups.google.com/forum/#!topic/paperjs/orL7YwBdZq4 which specifies another (more paper.js specific) solution:
project.activeLayer.removeChildren();
I know there are question like this but I still can't find a fix, I've looked through the console and can't see anything. There are two images, one which should appear on set coordinates, and another which follows the mouse, the one which is mean't to follow the mouse does not show up but the other one does.
Main.js
/**
* Created with JetBrains WebStorm.
* User: Script47
* Date: 22/09/13
* Time: 00:54
*/
function drawAvatars() {
// Create variable for the canvas & create a new object for image
var gameCanvas = document.getElementById("gameCanvas");
var userImage = new Image();
// The source of the images
userImage.src = ("Images/userImage.png");
// Create an event listener then call function redrawAvatar
gameCanvas.addEventListener("mousemove", redrawAvatar);
}
function redrawAvatar(mouseEvent) {
var gameCanvas = document.getElementById("gameCanvas");
var userImage = new Image();
var enemyImage = new Image();
var score = 0;
userImage.src = ("Images/userImage.png");
enemyImage.src = ("Images/enemyImage.png");
// Erase canvas sort of refresh, then re-draw image following the coordinates of the mouse in the canvas
gameCanvas.width = 400;
gameCanvas.getContext("2d").drawImage(userImage, mouseEvent.offsetX, mouseEvent.offsetY);
gameCanvas.getContext("2d").drawImage(enemyImage, 150, 150);
// Simple hit detection to see if user image hits enemy image
if (mouseEvent.offsetX > 130 && mouseEvent.offsetX < 175 && mouseEvent.offsetY > 130 && mouseEvent.offsetY < 175) {
score++;
alert("You hit the enemy!\n You score is: " +score);
}
}
Index.html
<!DOCTYPE html>
<html>
<head>
<title>Avoid Me | Game</title>
<link rel="stylesheet" type="text/css" href="CSS/styles.css">
<script src="JS/Main.js"></script>
</head>
<body>
<br/>
<center><h3>Avoid Me!</h3>
<br/>
<br/>
<canvas id="gameCanvas" height="300" width="400" onclick="drawAvatars();">
<p><strong>Notice:</strong> Browser does not support canvas!</p>
</canvas>
</center>
</body>
</html>
JsFiddle
(Basing this off the code in the link you provided.)
In your mouseMovement function, you use mouseEvent.offsetX and mouseEvent.offsetY to get the player's position, but Firefox unfortunately doesn't support those properties. Unfortunately, IIRC, the only thing that works cross-browser is to get the position of the canvas, and subtract it from the event's pageX/pageY properties. You can use the canvas's getBoundingClientRect() method to find its position on the page.
This is is an example of a version of the function that should work in Firefox as well:
function mouseMovement(mouseEvent) {
var canvasPosition = gameCanvas.getBoundingClientRect();
userImageX = mouseEvent.pageX - canvasPosition.left;
userImageY = mouseEvent.pageY - canvasPosition.top;
}
I'm going to start this question off by saying that this is 100% working in Firefox (v21.0). For some reason it's not working in Google Chrome (v27.0.1453.94m). It also doesn't work in IE10.
Here is the JavaScript code I'm having issues with:
function canvasDrawBackground(value){
console.log(value);
stage.removeChild(background);
var temp = new createjs.Bitmap("images/bg_" + value +".jpg");
background = new createjs.Container();
background.x = background.y = 0;
background.addChild(temp);
stage.addChild(background);
background.addEventListener("mousedown", function(evt) {
var offset = {x:evt.target.x-evt.stageX, y:evt.target.y-evt.stageY};
evt.addEventListener("mousemove",function(ev) {
ev.target.x = ev.stageX+offset.x;
ev.target.y = ev.stageY+offset.y;
stage.update();
});
});
stage.update();
}
So, in Firefox the above code works, as in the image is added to the canvas and you can drag it around.
In Chrome / IE10 nothing happens - or more simply nothing appears on the canvas. I think the issue is in regards to when I add the image into the container, as I can place other items into the container and it works.
I am using http://code.createjs.com/easeljs-0.6.1.min.js and this code is based off of the "drag" tutorial. Here's the code from the tutorial:
<!DOCTYPE html>
<html>
<head>
<title>EaselJS demo: Dragging</title>
<link href="../../shared/demo.css" rel="stylesheet" type="text/css">
<script src="http://code.createjs.com/easeljs-0.6.0.min.js"></script>
<script>
var stage, output;
function init() {
stage = new createjs.Stage("demoCanvas");
// this lets our drag continue to track the mouse even when it leaves the canvas:
// play with commenting this out to see the difference.
stage.mouseMoveOutside = true;
var circle = new createjs.Shape();
circle.graphics.beginFill("red").drawCircle(0, 0, 50);
var label = new createjs.Text("drag me", "bold 14px Arial", "#FFFFFF");
label.textAlign = "center";
label.y = -7;
var dragger = new createjs.Container();
dragger.x = dragger.y = 100;
dragger.addChild(circle, label);
stage.addChild(dragger);
dragger.addEventListener("mousedown", function(evt) {
var offset = {x:evt.target.x-evt.stageX, y:evt.target.y-evt.stageY};
// add a handler to the event object's onMouseMove callback
// this will be active until the user releases the mouse button:
evt.addEventListener("mousemove",function(ev) {
ev.target.x = ev.stageX+offset.x;
ev.target.y = ev.stageY+offset.y;
stage.update();
});
});
stage.update();
}
</script>
</head>
<body onLoad="init();">
<canvas id="demoCanvas" width="500" height="200">
alternate content
</canvas>
</body>
</html>
To simulate my issue, change "var circle = new createjs.Shape();" into a bitmap / image, createjs.Bitmap("images/bg_" + value +".jpg");. It then doesn't render.
Any help is greatly appreciated! Hopefully I'm just doing it wrong. :P
This is probably because the image is not loaded. If you only update the stage after creating it, the image may not display. I would recommend adding a callback to the image to update the stage after its loaded.
// Simple approach. May not work depending on the scope of the stage.
var temp = new createjs.Bitmap("images/bg_" + value +".jpg");
temp.image.onload = function() { stage.update(); }
It also may make sense to preload the images you intend to use.
I have been trying to set up a javascript game loop and I have two issues I am running into. I find that in chrome when I lose focus of the browser window and then click back the animation I have running does this weird "catch up" thing where it quickly runs through the frames it should of been rendering in the background. I also have noticed that the animation is blury when moving at the current speed I have it at yet other people have been able to get their canvas drawings to move quickly and still look crisp. I know their seems to be a lot out about this but I cant make sense of what my issue really is. I thought this was a recommended way to create a game loop.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<title>Frame Test</title>
<link href="/css/bootstrap.css" media="all" rel="stylesheet" type="text/css" />
<script language="javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"
type="text/javascript">
</script>
<script language="javascript" src="js/jquery.hotkeys.js" type="text/javascript"></script>
<script language="javascript" src="js/key_status.js" type="text/javascript"></script>
<script language="javascript" src="js/util.js" type="text/javascript"></script>
<script language="javascript" src="js/sprite.js" type="text/javascript"></script>
</head>
<body>
<button id="button1">
Toggle Loop</button>
<h1 id="frameCount">
Game Loop Test</h1>
<canvas id="gameCanvas" width="800" height="500">
<p>Your browser doesn't support canvas.</p>
</canvas>
<script type='text/javascript'>
// demo code used for playing around with javascript-canvas animations
var frameCount = 0;
var drawingCanvas = document.getElementById('gameCanvas');
// Check the element is in the DOM and the browser supports canvas
if (drawingCanvas.getContext) {
var context = drawingCanvas.getContext('2d');
var x = 100;
var y = 100;
var right = true;
context.strokeStyle = "#000000";
context.fillStyle = "Green";
context.beginPath();
context.arc(x, y, 50, 0, Math.PI * 2, true);
context.closePath();
context.stroke();
context.fill();
}
function Timer(settings) {
this.settings = settings;
this.timer = null;
this.on = false; //Bool that represents if the timer is running or stoped
this.fps = settings.fps || 30; //Target frames per second value
this.interval = Math.floor(1000 / 30);
this.timeInit = null; //Initial time taken when start is called
return this;
}
Timer.prototype =
{
run: function () {
var $this = this;
this.settings.run();
this.timeInit += this.interval;
this.timer = setTimeout(
function () { $this.run() },
this.timeInit - (new Date).getTime()
);
},
start: function () {
if (this.timer == null) {
this.timeInit = (new Date).getTime();
this.run();
this.on = true;
}
},
stop: function () {
clearTimeout(this.timer);
this.timer = null;
this.on = false;
},
toggle: function () {
if (this.on) { this.stop(); }
else { this.start(); }
}
}
var timer = new Timer({
fps: 30,
run: function () {
//---------------------------------------------run game code here------------------------------------------------------
//Currently Chorme is playing a catch up game with the frames to be drawn when the user leaves the browser window and then returns
//A simple canvas animation is drawn here to try and figure out how to solve this issue. (Most likely related to the timer implimentation)
//Once figured out probably the only code in this loop should be something like
//updateGameLogic();
//updateGameCanvas();
frameCount++;
if (drawingCanvas.getContext) {
// Initaliase a 2-dimensional drawing context
//Canvas commands go here
context.clearRect((x - 52), 48, (x + 52), 104);
// Create the yellow face
context.strokeStyle = "#000000";
context.fillStyle = "Green";
context.beginPath();
if (right) {
x = x + 6;
if (x > 500)
right = false;
} else {
x = x - 6;
if (x < 100)
right = true;
}
context.arc(x, 100, 50, 0, Math.PI * 2, true);
context.closePath();
context.stroke();
context.fill();
}
document.getElementById("frameCount").innerHTML = frameCount;
//---------------------------------------------end of game loop--------------------------------------------------------
}
});
document.getElementById("button1").onclick = function () { timer.toggle(); };
frameCount++;
document.getElementById("frameCount").innerHTML = frameCount;
</script>
</body>
</html>
-------------Update ---------------------
I have used requestanimation frame and that has solved the frame rate problam but I still get weird ghosting/bluring when the animation is running. any idea how I should be drawing this thing?
Okay, so part of your problem is that when you switch tabs, Chrome throttles down its performance.
Basically, when you leave, Chrome slows all of the calculations on the page to 1 or 2 fps (battery-saver, and more performance for the current tab).
Using setTimeout in the way that you have is basically scheduling all of these calls, which sit and wait for the user to come back (or at most are only running at 1fps).
When the user comes back, you've got hundreds of these stacked calls, waiting to be handled, and because they've all been scheduled earlier, they've all passed their "wait" time, so they're all going to execute as fast as possible (fast-forward), until the stack is emptied to where you have to start waiting 32ms for the next call.
A solution to this is to stop the timer when someone leaves -- pause the game.
On some browsers which support canvas games in meaningful ways, there is also support for a PageVisibility API. You should look into it.
For other browsers, it'll be less simple, but you can tie to a blur event on the window for example.
Just be sure that when you restart, you also clear your interval for your updates.
Ultimately, I'd suggest moving over to `requestAnimationFrame, because it will intelligently handle frame rate, and also handle the throttling you see, due to the stacked calls, but your timer looks like a decent substitute for browsers which don't yet have it.
As for blurriness, that needs more insight.
Reasons off the top of my head, if you're talking about images, are either that your canvas' width/height are being set in CSS, somewhere, or your sprites aren't being used at a 1:1 scale from the image they're pulled from.
It can also come down to sub-pixel positioning of your images, or rotation.
Hope that helps a little.
...actually, after looking at your code again, try removing "width" and "height" from your canvas in HTML, and instead, change canvas.width = 800; canvas.height = 500; in JS, and see if that helps any.