Im trying to make the image of a trex jump when canavas is clicked
Here is my code
index.html
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta name="viewport" content="width=device-width, initial-scale=1" />
</head>
<body>
<canvas onclick="canjump = true; renderer = requestAnimationFrame(loop); dinoy = 150;" height="250px" width="350px" style="border: 2px solid black" id="canvas"></canvas>
<img src="./dino.png" height="0px" width="0px" id="dinoimg">
<img src="./cacti.png" height="0px" width="0px" id="cactimg">
<script type="text/javascript" src="./main.js"></script>
</body>
</html>
main.js
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
var dinoimage = document.getElementById('dinoimg');
var dinoheight = 100;
var dinowidth = 50;
var dinox = 0;
var dinoy = 150;
var canjump = false;
var renderer;
var jmpv = 15;
function loop() {
if (canjump = true && dinoy <= 150) {
jumpdino();
} else {
dinoy = 151;
jmpv = 15;
canjump = false;
cancelAnimationFrame(renderer);
}
//setcacti();
//checkcollision();
renderer = requestAnimationFrame(loop);
}
function jumpdino() {
ctx.clearRect(0, 0, 350, 250);
ctx.drawImage(dinoimage, dinox, dinoy, dinowidth, dinoheight);
dinoy -= jmpv;
jmpv--;
}
The problem is that everything work as expected for first time but when canvas is clicked after then (second click and after), the image just go up and come down very fast and not smoothly with acceleration like first time.
Please help!!!
Those two fore function calls are commented because they arent implemented yet.
Just fixing the code you have I added a return in the else, the issue was even though you canceled the requestAnimationFrame after the else condition it still would continue and reassign renderer to the loop. So it was always running, each time you clicked it was just adding another instance making it go faster and faster.
function loop() {
if (canjump = true && dinoy <= 150) {
jumpdino();
} else {
dinoy = 151;
jmpv = 15;
canjump = false;
cancelAnimationFrame(renderer);
// You need to exit out.
return;
}
//setcacti();
//checkcollision();
renderer = requestAnimationFrame(loop);
}
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
var dinoheight = 100;
var dinowidth = 50;
var dinox = 0;
var dinoy = 150;
var canjump = false;
var renderer;
var jmpv = 15;
function loop() {
if (canjump = true && dinoy <= 150) {
jumpdino();
} else {
dinoy = 151;
jmpv = 15;
canjump = false;
cancelAnimationFrame(renderer);
return;
}
//setcacti();
//checkcollision();
renderer = requestAnimationFrame(loop);
}
function jumpdino() {
ctx.clearRect(0, 0, 350, 250);
ctx.fillRect(dinox, dinoy, dinowidth, dinoheight);
dinoy -= jmpv;
jmpv--;
}
<canvas onclick="canjump = true; requestAnimationFrame(loop); dinoy = 150;" height="250px" width="350px" style="border: 2px solid black" id="canvas"></canvas>
Personally I'd remove the inline event handler and do something like this in your code as well.
canvas.addEventListener('click', () => {
canjump = true;
dinoy = 150;
loop();
});
Related
I am making a javascript game, using Canvas. However, I got that error(below image) and background image is not shown. I suspect below 4 files, because other files didn't make any trouble. I guess the problem is related with game_state...how can I solve the problem??
I am agonizing for 2days:( plz, help me..
error image1
error image2
index.html
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="utf-8">
<title>Lion Travel</title>
<!--GameFramework-->
<script src="/.c9/gfw/GameFramework.js"></script>
<script src="/.c9/gfw/FrameCounter.js"></script>
<script src="/.c9/gfw/InputSystem.js"></script>
<script src="/.c9/gfw/SoundManager.js"></script>
<script src="/.c9/gfw/GraphicObject.js"></script>
<script src="/.c9/gfw/SpriteAnimation.js"></script>
<script src="/.c9/gfw/ResourcePreLoader.js"></script>
<script src="/.c9/gfw/DebugSystem.js"></script>
<script src="/.c9/gfw/Timer.js"></script>
<script src="/.c9/gfw/FrameSkipper.js"></script>
<script src="/.c9/gfw/TransitionState.js"></script>
<!--GameInit-->
<script src="/.c9/gfw/gfw.js"></script>
<!--Game Logic-->
<script src="/.c9/RS_Title.js"></script>
</head>
<body>
<canvas id="GameCanvas" width="800" height="600">html5 canvas is not supported.</canvas>
</body>
</html>
gfw.js
function onGameInit() {
document.title = "Lion Travel";
GAME_FPS = 30;
debugSystem.debugMode = true;
resourcePreLoader.AddImage("/.c9/title_background.png");
soundSystem.AddSound("/.c9/background.mp3", 1);
after_loading_state = new TitleState();
setInterval(gameLoop, 1000 / GAME_FPS);
}
window.addEventListener("load", onGameInit, false);
RS_Title.js
function TitleState()
{
this.imgBackground = resourcePreLoader.GetImage("/.c9/title_background.png");
soundSystem.PlayBackgroundMusic("/.c9/background.mp3");
return this;
}
TitleState.prototype.Init = function()
{
soundSystem.PlayBackgroundMusic("/.c9/background.mp3");
};
TitleState.prototype.Render = function()
{
var theCanvas = document.getElementById("GameCanvas");
var Context = theCanvas.getContext("2d");
//drawing backgroundimage
Context.drawImage(this.imgBackground, 0, 0);
};
TitleState.prototype.Update = function()
{
};
GameFramework.js
var GAME_FPS;
var game_state = after_loading_state;
function ChangeGameState(nextGameState)
{
//checking essential function
if(nextGameState.Init == undefined)
return;
if(nextGameState.Update == undefined)
return;
if(nextGameState.Render == undefined)
return;
game_state = nextGameState;
game_state.Init();
}
function Update()
{
timerSystem.Update();
game_state.Update();
debugSystem.UseDebugMode();
}
function Render()
{
//drawing
var theCanvas = document.getElementById("GameCanvas");
var Context = theCanvas.getContext("2d");
Context.fillStyle = "#000000";
Context.fillRect(0, 0, 800, 600);
//game state
game_state.Render();
if(debugSystem.debugMode)
{
//showing fps
Context.fillStyle = "#ffffff";
Context.font = '15px Arial';
Context.textBaseline = "top";
Context.fillText("fps: "+ frameCounter.Lastfps, 10, 10);
}
}
function gameLoop()
{
Update();
Render();
frameCounter.countFrame();
}
The issue here is that you are initializing game_state with the object after_loading_state even before after_loading_state is initialized(which is initialized only after the document is loaded). Due to this game_state remains undefined.
To fix this, change var game_state = after_loading_state; in GameFramework.js to var game_state;. And add game_state = after_loading_state; as the first line in gameLoop function. This way, the initialization of variables occur in the correct order.
I'm trying to get my inputhandler to work in Javascript.
What
In my Game.update I currently have this code:
this.Update = function() {
if (input.GetMousePressed()) {
console.log(input.GetMousePosition());
}
}
And this is my inputhandler:
function InputHandler(canvas) {
this.canvas = canvas;
this.mousePressed = false;
this.mouseDown = false;
this.mousePosition = new Position(0, 0);
this.GetMousePosition = function() {
return this.mousePosition;
}
this.SetMousePosition = function(event) {
var rect = this.canvas.getBoundingClientRect();
this.mousePosition = new Position(event.clientX - rect.left, event.clientY - rect.top);
}
this.GetMousePressed = function() {
return this.mousePressed;
}
this.canvas.onmousedown = function(event) {
input.mouseDown = true;
input.SetMousePosition(event);
}
this.canvas.onclick = function(event) {
input.mouseClicked = true;
input.SetMousePosition(event);
}
window.onmouseup = function(event) {
if (input.mouseDown == true) {
input.mousePressed = true;
input.mouseDown = false;
}
}
The first problem is that I dont know how to handle mousePressed and set it to false. Now it stays true forever.
I'm quite new to Javascript and I'm thankful for any change that would make this better or cleaner code or if what Im doing is bad practice.
I'm using addEventListener for normal button pressing and maybe I should for this to?
Not sure why you need mousepressed/mouseup and click events. The only difference between successful pressed/up and click is that click target should be the same element.
So I would either use the first option or the last but not both.
Your mousePressed flag is set to true because it gets assigned true value once you press the mouse. You need to reset it back to false at some point.
Usually, you don't even need this flag since you trigger whatever function you need inside mousepressed event. Not sure why you would save the information that this happened, do you use it somewhere else?
Also, yes using addEventListener would be better.
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<style>
body {
background-color: black;
}
canvas {
position: absolute;
margin: auto;
left: 0;
right: 0;
border: solid 1px white;
border-radius: 10px;
}
</style>
</head>
<body>
<canvas id="canvas"></canvas>
<script type="application/javascript">
var imageWidth = 180;
var imageHeight = 160;
var canvas = null;
var ctx = null;
var mouseDown = false;
var mouseX = 0;
var mouseY = 0;
var bounds = null;
function canvas_onmousedown(e) {
mouseDown = true;
}
function canvas_onmousemove(e) {
if (mouseDown) {
mouseX = e.clientX - bounds.left;
mouseY = e.clientY - bounds.top;
}
}
function canvas_onmouseup(e) {
mouseDown = false;
}
function loop() {
ctx.fillStyle = "gray";
ctx.fillRect(0,0,imageWidth,imageHeight);
if (mouseDown) {
ctx.fillStyle = "yellow";
} else {
ctx.fillStyle = "black";
}
ctx.fillRect(mouseX - 25,mouseY - 25,50,50);
requestAnimationFrame(loop);
}
window.onload = function() {
canvas = document.getElementById("canvas");
canvas.width = imageWidth;
canvas.height = imageHeight;
canvas.onmousedown = canvas_onmousedown;
canvas.onmousemove = canvas_onmousemove;
canvas.onmouseup = canvas_onmouseup;
ctx = canvas.getContext("2d");
bounds = canvas.getBoundingClientRect();
requestAnimationFrame(loop);
}
</script>
</body>
</html>
I am making a game with html and javascript. Just for clarification, this is not a duplicate or anything. Nothing has the answer I need. Also before I explain, I want to say I have no trouble with the key listener, my game knows when a key is pressed and when it is released. Okay, I have 5 frames of a character walking. I have a while loop that basically says while the key D is pressed or Right arrow is pressed, then increment the frames to make it look like the character is walking. Then it has a setTimeout function that pauses for 1/10 of a second. This should make it look like the character is walking. I know it has something to do with the setTimeout() function. Here is the while loop:
while (keys[68] || keys[39]) {
charFrame++;
setTimeout(function() {
}, 100);
}
Then here is my code:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Sparring Spartans</title>
<style type="text/css">
</style>
</head>
<body>
<canvas id="canvas" width="1000" height="600"></canvas>
<script type="text/javascript">
var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");
var width = canvas.width;
var height = canvas.height;
var groundX = 0, groundY = 400;
var playerx = width/2, playery = groundY-120;
var charFrame = 1;
var speed = 4;
var keys = [];
window.addEventListener("keydown", function(e) {
keys[e.keyCode] = true;
}, false);
window.addEventListener("keyup", function(e) {
delete keys[e.keyCode];
}, false);
var spartan1 = new Image();
spartan1.src = "spartan1.png";
var spartan2 = new Image();
spartan2.src = "spartan2.png";
var spartan3 = new Image();
spartan3.src = "spartan3.png";
var spartan4 = new Image();
spartan4.src = "spartan4.png";
var spartan5 = new Image();
spartan5.src = "spartan5.png";
var stone = new Image();
stone.src = "stone.png";
function game() {
update();
render();
}
function player() {
if (charFrame === 1) {
context.drawImage(spartan1, playerx, playery);
} else if (charFrame === 2) {
context.drawImage(spartan2, playerx, playery);
} else if (charFrame === 3) {
context.drawImage(spartan3, playerx, playery);
} else if (charFrame === 4) {
context.drawImage(spartan4, playerx, playery);
} else if (charFrame === 5) {
context.drawImage(spartan5, playerx, playery);
}
}
function ground() {
for (var i = 0; i <= 1000; i += 55) {
context.drawImage(stone, i, groundY);
}
for (var i = 0; i <= 1000; i += 55) {
context.drawImage(stone, i, groundY+55);
}
for (var i = 0; i <= 1000; i += 55) {
context.drawImage(stone, i, groundY+110);
}
for (var i = 0; i <= 1000; i += 55) {
context.drawImage(stone, i, groundY+165);
}
}
function manager() {
ground();
while (keys[68] || keys[39]) {
charFrame++;
setTimeout(function() {
}, 100);
}
player();
}
function update() {
manager();
player();
}
function render() {
context.fillStyle = "#AFE4FF";
context.fillRect(0, 0, width, height);
manager();
}
setInterval(function() {
game();
}, 1000/30);
</script>
</body>
</html>
What am I doing wrong? I know it HAS to be the setTimeout, but I have tried to fix this problem many times. The images don't even change.
Because your manager function gets called 30 times per second, you should check your keypress once per frame using an if statement instead of a loop:
function manager() {
ground();
if (keys[68] || keys[39]) {
charFrame++;
}
}
In addition, your manager function is getting called twice per frame, once in the update function and once in the render function. Also, your player function is called both in update and in manager, again twice per frame. Your code will need some refactoring in order to work properly, to make sure nothing gets called twice per frame.
I've been trying to create a game with falling blocks that will stack on top of each other. The blocks will fall into one of 6 columns and need to stop falling down the screen when they collide with the top block on that column. I've been trying to get the y-coordinate of the top block, but that causes a problem because its still getting the newest created block and not the last finished block. Any help would be greatly appreciated!
var FPS = 60;
setInterval(function() {
//update();
draw();
}, 1000/FPS);
var y = 30;
//draw the screen
function draw() {
if(+new Date() > lastTime + minWait){
var column = Math.floor(Math.random()*6)
lastTime = +new Date();
blocks.push(new Block(5 + column*40, 30,40,40, 5, "red","black"));
}
context.clearRect(0,0,canvas.width, canvas.height);
blocks.forEach(function(e){
e.update();
e.render();
});
};
var blocks = [];
var lastTime = +new Date();
var minWait = 1000;
var topBlock = 310;
function columnTop(column){
for(var i=0; i < blocks.length; i++){
if(blocks[i].x === (5 + 40*columnTop)){
if(blocks[i].y < topBlock){
topBlock = blocks[i].y
}
}
}
}
//block functions
Block.prototype.update = function(){
var topCol1 = columnTop(1);
var topCol2 = columnTop(2);
var topCol3 = columnTop(3);
var topCol4 = columnTop(4);
var topCol5 = columnTop(5);
var topCol6 = columnTop(6);
if(this.y < 310){
this.y+= this.dy
}else{
this.dy = 0;
}
};
Block.prototype.render = function(){
Block(this.x, this.y, this.w, this.h, this.r, this.fillstyle, this.strokestyle);
};
Maintain a maximum-Y value for each column.
maximum-Y is the y-position of the last stacked block.
Whenever a block exceeds the maximum-Y, force that block to sit atop the maximum-Y.
Then reduce maximum-Y by that blocks height.
if( block.y + block.height > maxY ){
block.y = maxY - block.height;
maxY = block.y;
}
Here's code and a Demo: http://jsfiddle.net/m1erickson/FMv2q/
<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" media="all" href="css/reset.css" />
<script src="http://code.jquery.com/jquery.min.js"></script>
<style>
body{ background-color: ivory; }
canvas{border:1px solid red;}
</style>
<script>
$(function(){
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
function Blocks(floor,colCount){
this.blocks=[];
this.floor=floor;
this.cols=[];
this.continueRAF=true;
for(var i=0;i<colCount;i++){
this.cols.push({maxY:floor,needsNewBlock:true});
}
}
function animate(){
if(blocks.continueRAF){ requestAnimationFrame(animate); }
for(var i=0;i<blocks.cols.length;i++){
if(blocks.cols[i].needsNewBlock){
blocks.cols[i].needsNewBlock=false;
blocks.blocks.push(new Block(i));
}
}
ctx.clearRect(0,0,canvas.width,canvas.height);
var fallingCount=0;
for(var i=0;i<blocks.blocks.length;i++){
var block=blocks.blocks[i];
fallingCount+=block.fall();
ctx.fillStyle=block.fill;
ctx.fillRect(block.x,block.y,block.w,block.h);
}
if(fallingCount==0 && blocks.continueRAF){
blocks.continueRAF=false;
alert("All done after "+blocks.blocks.length+" blocks fell.");
}
}
function Block(column){
this.column=column;
this.x=this.column*50;
this.w=parseInt(Math.random()*20+15);
this.h=parseInt(Math.random()*15+5);
this.y=-this.h;
this.vy=parseInt(Math.random()*3+4);
this.fill=randomColor();;
this.isFalling=true;
}
Block.prototype.fall=function(){
if(!this.isFalling){return(0);}
var col=blocks.cols[this.column];
if(this.y+this.h+this.vy>col.maxY){
this.isFalling=false;
this.y=col.maxY-this.h;
col.maxY=this.y;
if(col.maxY>35){
col.needsNewBlock=true;
}
}else{
this.y+=this.vy;
}
return(1);
}
var blocks=new Blocks(350,6);
animate();
function randomColor(){
return('#'+Math.floor(Math.random()*16777215).toString(16));
}
}); // end $(function(){});
</script>
</head>
<body>
<canvas id="canvas" width=350 height=350></canvas>
</body>
</html>
I'm working on a soccer webcam game in Canvas, still using headtrackr (https://github.com/auduno/headtrackr)
Here it is online; http://www.chrissnoek.com/ubicomp/webcam.html
so far I managed to check if my rectangle hits my ball, then the counter goes +1
The only thing is, I can't reposition my ball if the rectangle hits it.
I tried it this way, but the ball constantly redrawn, so as the rectangle.
bal.x = Math.floor(Math.random()* (640) + 20);
bal.y = Math.floor(Math.random()* (120) + 20);
But that doesn't work. Here is my full code;
Any suggestions to move the ball when it is hit?
<!doctype html>
<html lang="en">
<head>
<title>facetracking</title>
<meta http-equiv="X-UA-Compatible" content="IE=Edge"/>
<meta charset="utf-8">
<script src="js/animate.js"></script>
<script src="js/delta.js"></script>
<script src="./js/headtrackr.js"></script>
</head>
<body>
<span id="counter">0</span>
<canvas id="compare" width="640" height="480" style="display:none"></canvas>
<video id="vid" autoplay loop width="640" height="480" style="width: 640px"></video>
<canvas id="overlay" width="640" height="480"></canvas>
<canvas id="Baloverlay" width="640" height="480"></canvas>
<canvas id="bal" width="640" height="480"></canvas>
<canvas id="debug" width="640" height="480"></canvas>
<p id='gUMMessage'></p>
<p>Status : <span id='headtrackerMessage'></span></p>
<p>
<input type="button" onclick="htracker.stop();htracker.start();" value="reinitiate facedetection"></input>
<br/><br/>
<input type="checkbox" onclick="showProbabilityCanvas()" value="asdfasd"></input>Show probability-map
</p>
<script>
// set up video and canvas elements needed
var videoInput = document.getElementById('vid');
var canvasInput = document.getElementById('compare');
var canvasOverlay = document.getElementById('overlay');
var balOverlay = document.getElementById('bal');
var debugOverlay = document.getElementById('debug');
var overlayContext = canvasOverlay.getContext('2d');
var balOverlay = document.getElementById('Baloverlay');
var balContext = balOverlay.getContext('2d');
var counter = document.getElementById('counter'),
count = 0;
canvasOverlay.style.position = "absolute";
canvasOverlay.style.top = '0px';
canvasOverlay.style.zIndex = '100001';
canvasOverlay.style.display = 'block';
balOverlay.style.position = "absolute";
balOverlay.style.top = '0px';
balOverlay.style.zIndex = '100002';
balOverlay.style.display = 'block';
debugOverlay.style.position = "absolute";
debugOverlay.style.top = '0px';
debugOverlay.style.zIndex = '100003';
debugOverlay.style.display = 'none';
// add some custom messaging
statusMessages = {
"whitebalance" : "checking for stability of camera whitebalance",
"detecting" : "Detecting face",
"hints" : "Hmm. Detecting the face is taking a long time",
"redetecting" : "Lost track of face, redetecting",
"lost" : "Lost track of face",
"found" : "Tracking face"
};
supportMessages = {
"no getUserMedia" : "Unfortunately, <a href='http://dev.w3.org/2011/webrtc/editor/getusermedia.html'>getUserMedia</a> is not supported in your browser. Try <a href='http://www.opera.com/browser/'>downloading Opera 12</a> or <a href='http://caniuse.com/stream'>another browser that supports getUserMedia</a>. Now using fallback video for facedetection.",
"no camera" : "No camera found. Using fallback video for facedetection."
};
document.addEventListener("headtrackrStatus", function(event) {
if (event.status in supportMessages) {
var messagep = document.getElementById('gUMMessage');
messagep.innerHTML = supportMessages[event.status];
} else if (event.status in statusMessages) {
var messagep = document.getElementById('headtrackerMessage');
messagep.innerHTML = statusMessages[event.status];
}
}, true);
// the face tracking setup
var htracker = new headtrackr.Tracker({altVideo : {ogv : "./media/capture5.ogv", mp4 : "./media/capture5.mp4"}, calcAngles : true, ui : false, headPosition : false, debug : debugOverlay});
htracker.init(videoInput, canvasInput);
htracker.start();
// for each facetracking event received draw rectangle around tracked face on canvas
document.addEventListener("facetrackingEvent", function( event ) {
// clear canvas
overlayContext.clearRect(0,0,640,480);
// once we have stable tracking, draw rectangle
if (event.detection == "CS") {
overlayContext.translate(event.x, event.y)
//overlayContext.rotate(event.angle-(Math.PI/2));
overlayContext.strokeStyle = "#00CC00";
overlayContext.strokeRect((-(event.width/2)) >> 0, (-(event.height/2)) >> 0, event.width, event.height);
//overlayContext.rotate((Math.PI/2)-event.angle);
overlayContext.translate(-event.x, -event.y);
var bal = new ball();
lookForBallInbound(event.x, event.y, event.width, event.height);
}
});
// turn off or on the canvas showing probability
function showProbabilityCanvas() {
var debugCanvas = document.getElementById('debug');
if (debugCanvas.style.display == 'none') {
debugCanvas.style.display = 'block';
} else {
debugCanvas.style.display = 'none';
}
}
/*==============================================
////////// KIJK OF BAL BINNEN VAK VALT ////////
==============================================*/
function lookForBallInbound(boxX,boxY,boxWidth,boxHeight) {
var rightCornerX = boxX - (boxWidth / 2),
topY = boxY - (boxHeight / 2);
if(rightCornerX <= xxx){
if((rightCornerX + boxWidth) <= xxx) {
return false;
} else {
// balls is in the box at the x axis
// Now check for Y
if (topY <= yyy) {
// Top is also inbound, => AWESOME <=
/*========================================
RECALCULATE BALL POSITION
========================================*/
bal.x = Math.floor(Math.random()* (640) + 20);
bal.y = Math.floor(Math.random()* (120) + 20);
/*========================================
INCREASE AND OUTPUT COUNTER
========================================*/
count++;
counter.innerHTML = '';
counter.innerHTML = count;
}
}
}
}
var xxx = Math.floor(Math.random()* (640) + 20);
var yyy = Math.floor(Math.random()* (120) + 20);
var ballRadius = 20;
function ball() {
console.log('Ball recalculating');
balContext.beginPath();
balContext.arc(xxx, yyy, ballRadius, 0, 2 * Math.PI, false);
balContext.fillStyle = 'green';
balContext.fill();
}
</script>
</body>
</html>
Something like this should work. Note that ball is defined as a global variable.
var videoInput = document.getElementById('vid');
var canvasInput = document.getElementById('compare');
var canvasOverlay = document.getElementById('overlay');
var debugOverlay = document.getElementById('debug');
var overlayContext = canvasOverlay.getContext('2d');
var balOverlay = document.getElementById('Baloverlay');
var balContext = balOverlay.getContext('2d');
var counter = document.getElementById('counter'),
count = 0,
ball,
statusMessages,
supportMessages,
htracker;
canvasOverlay.style.position = "absolute";
canvasOverlay.style.top = '0px';
canvasOverlay.style.zIndex = '100001';
canvasOverlay.style.display = 'block';
balOverlay.style.position = "absolute";
balOverlay.style.top = '0px';
balOverlay.style.zIndex = '100002';
balOverlay.style.display = 'block';
debugOverlay.style.position = "absolute";
debugOverlay.style.top = '0px';
debugOverlay.style.zIndex = '100003';
debugOverlay.style.display = 'none';
// add some custom messaging
statusMessages = {
"whitebalance": "checking for stability of camera whitebalance",
"detecting": "Detecting face",
"hints": "Hmm. Detecting the face is taking a long time",
"redetecting": "Lost track of face, redetecting",
"lost": "Lost track of face",
"found": "Tracking face"
};
supportMessages = {
"no getUserMedia": "Unfortunately, <a href='http://dev.w3.org/2011/webrtc/editor/getusermedia.html'>getUserMedia</a> is not supported in your browser. Try <a href='http://www.opera.com/browser/'>downloading Opera 12</a> or <a href='http://caniuse.com/stream'>another browser that supports getUserMedia</a>. Now using fallback video for facedetection.",
"no camera": "No camera found. Using fallback video for facedetection."
};
document.addEventListener("headtrackrStatus", function(event) {
var messagep;
if (event.status in supportMessages) {
messagep = document.getElementById('gUMMessage');
messagep.innerHTML = supportMessages[event.status];
} else if (event.status in statusMessages) {
messagep = document.getElementById('headtrackerMessage');
messagep.innerHTML = statusMessages[event.status];
}
}, true);
// the face tracking setup
htracker = new headtrackr.Tracker({
altVideo: {
ogv: "./media/capture5.ogv",
mp4: "./media/capture5.mp4"
},
calcAngles: true,
ui: false,
headPosition: false,
debug: debugOverlay
});
htracker.init(videoInput, canvasInput);
htracker.start();
// for each facetracking event received draw rectangle around tracked face on canvas
document.addEventListener("facetrackingEvent", function(event) {
// clear canvas
overlayContext.clearRect(0, 0, 640, 480);
// once we have stable tracking, draw rectangle
if (event.detection == "CS") {
overlayContext.translate(event.x, event.y);
//overlayContext.rotate(event.angle-(Math.PI/2));
overlayContext.strokeStyle = "#00CC00";
overlayContext.strokeRect((-(event.width / 2)) >> 0, (-(event.height / 2)) >> 0, event.width, event.height);
//overlayContext.rotate((Math.PI/2)-event.angle);
overlayContext.translate(-event.x, -event.y);
if (!ball) { // if there is no ball then make one
ball = new Ball();
}
lookForBallInbound(event.x, event.y, event.width, event.height);
}
});
// turn off or on the canvas showing probability
function showProbabilityCanvas() {
var debugCanvas = document.getElementById('debug');
if (debugCanvas.style.display == 'none') {
debugCanvas.style.display = 'block';
} else {
debugCanvas.style.display = 'none';
}
}
/*==============================================
////////// KIJK OF BAL BINNEN VAK VALT ////////
==============================================*/
function lookForBallInbound(boxX, boxY, boxWidth, boxHeight) {
var leftX = boxX - boxWidth / 2, rightX = leftX + boxWidth,
topY = boxY - boxHeight / 2, bottomY = topY + boxHeight;
if (!ball) return;
if (leftX <= ball.x && rightX >= ball.x &&
topY <= ball.y && bottomY >= ball.y) {
ball = new Ball();
// ^ replace the existing ball with a randomly positioned new one
count++;
counter.innerHTML = count;
}
}
function Ball() {
console.log('making new ball');
this.x = Math.floor(Math.random() * 640 + 20);
this.y = Math.floor(Math.random() * 120 + 20);
this.radius = 20;
this.draw = function() {
balContext.clearRect(0, 0, 640, 480);
balContext.beginPath();
balContext.arc(this.x, this.y, this.radius, 0, 2 * Math.PI, false);
balContext.fillStyle = 'green';
balContext.fill();
}
this.draw();
}