Center a div containing a script - javascript

I'm trying to center a p5.js script in the middle of a page. I tried wrapping it with a div, and centering that, but it doesn't work
<body>
<div id="game"><script src="snakegame.js" type="text/javascript"></script></div>
<div id="score_wrap"><h1 class="score">SCORE: <div id="score"></div></h1></div>
<div id="hscore_wrap"><h1 class="score">HI-SCORE: <div id="hiscore"></div></h1></div>
</body>
This is what I tried to do
#game {
width: 900px;
height: 900px;
position: absolute;
top:0;
bottom: 0;
left: 0;
right: 0;
margin: auto;
}
.score {
font-family: "Bungee", sans-serif;
float: left;
color: #fff;
}
#score_wrap {
float: left;
}
#hscore_wrap {
float: right;
}
body {
background-color : #1048a3;
}
THIS IS INSIDE snakegame.js:
var s;
var scl = 20;
var food;
var pkeyCode = '';
// MAIN CODE FOR THE GAME
function setup() {
frameRate(9);
createCanvas(600, 600);
s = new Snake();
pickLocation();
}
function pickLocation () {
var cols = floor(width/scl);
var rows = floor(height/scl);
food = createVector(floor(random(cols)), floor(random(rows)));
food.mult(scl);
}
function draw() {
background(51);
s.update();
s.show();
if(s.eat(food)) {
s.score += 1;
if(s.score >= s.hiscore) s.hiscore = s.score;
pickLocation();
}
fill(255, 40, 100);
rect(food.x, food.y, scl, scl);
}
function keyPressed() {
if(keyCode === UP_ARROW && pkeyCode != 'DOWN_ARROW'){
s.dir(0, -1);
pkeyCode = 'UP_ARROW';
} else if (keyCode === DOWN_ARROW && pkeyCode != 'UP_ARROW'){
s.dir(0, 1);
pkeyCode = 'DOWN_ARROW';
} else if (keyCode === RIGHT_ARROW && pkeyCode != 'LEFT_ARROW'){
s.dir(1, 0);
pkeyCode = 'RIGHT_ARROW';
} else if (keyCode === LEFT_ARROW && pkeyCode != 'RIGHT_ARROW'){
s.dir(-1, 0);
pkeyCode = 'LEFT_ARROW';
} /* else if (keyCode === ENTER){
console.log('Cheating');
s.total++;
s.score++;
} */
}
// FUNCTIONS RELATING TO THE SNAKE, AND SNAKE PARTS ARE DEFINED HERE
function Snake() {
this.score = 0;
this.hiscore = 0;
this.x = 20;
this.y = 20;
this.xspeed = 1;
this.yspeed = 0;
this.total = 0;
this.tail = [];
this.dir = function(x, y) {
this.xspeed = x;
this.yspeed = y;
}
this.eat = function(pos) {
var d = dist(this.x, this.y, pos.x, pos.y);
if(d < 1) {
this.total++;
return true;
}
else {
return false;
}
}
this.dying = function() {
this.total = 0;
this.tail = [];
this.score = 0;
this.x = scl*3;
this.y = scl*3;
}
this.death = function() {
for (var i = 0; i < this.tail.length; i++) {
var pos = this.tail[i];
var d = dist(this.x, this.y, pos.x, pos.y);
if (d < 1) {
this.dying();
}
}
if(this.x >= width || this.y >= height) {
this.dying();
} else if (this.x < 0 || this.y < 0) {
this.dying();
}
}
this.update = function() {
for (var i = 0; i < this.tail.length - 1; i++) {
this.tail[i] = this.tail[i + 1];
}
this.tail[this.total - 1] = createVector(this.x, this.y);
this.x += this.xspeed*scl;
this.y += this.yspeed*scl;
s.death();
this.x = constrain(this.x, 0, width-scl);
this.y = constrain(this.y, 0, height-scl);
}
this.show = function() {
fill(200, 255, 200);
for (var i = 0; i < this.total; i++){
rect(this.tail[i].x, this.tail[i].y, scl, scl);
}
fill(255, 255, 255);
rect(this.x, this.y, scl, scl);
document.getElementById("score").innerHTML = this.score;
document.getElementById("hiscore").innerHTML = this.hiscore;
}
}
Sorry for the awful formatting, I'm new here

is this what you mean?
I put a border around it so you can see it as the js file is not loaded here
I also wrapped the score comments in a div so that they play nice on wider screens
#game {
width: 900px;
height: 900px;
max-width: 100%;
margin: 0 auto;
border: 1px solid white;
}
.scorecontainer {
max-width: 900px;
margin: 0 auto
}
.score {
font-family: "Bungee", sans-serif;
color: #fff;
}
#score {
float: left;
}
#hiscore {
float: right;
}
body {
background-color: #1048a3;
}
<body>
<div id="game">
<script src="snakegame.js" type="text/javascript"></script>
</div>
<div class="scorecontainer score">
<h1 id="score">SCORE: </h1>
<h1 id="hiscore">HI-SCORE: </h1>
</div>
</body>

Related

How to create a game over screen for a basic HTML/JS game?

I have been making an Atari Breakout inspired game based off of a tutorial. I was wondering how to make a "GAME OVER" screen that will show up once the player dies. The code that I have has a variable that I created called "DrawDeath()". I have it coded so that text appears when you die but for some reason it never shows up.
var interval = setInterval(draw, 10);
var canvas = document.getElementById("myCanvas"); //Variables for the canvas, ball, paddle, keys, and bricks
var ctx = canvas.getContext("2d");
var ballRadius = 10;
var x = canvas.width / 2;
var y = canvas.height - 30;
var dx = 2;
var dy = -2;
var paddleHeight = 10;
var paddleWidth = 75;
var paddleX = (canvas.width - paddleWidth) / 2;
var rightPressed = false;
var leftPressed = false;
var brickRowCount = 3;
var brickColumnCount = 5;
var brickWidth = 75;
var brickHeight = 20;
var brickPadding = 10;
var brickOffsetTop = 30;
var brickOffsetLeft = 30;
var score = 0;
var bricks = [];
for (var c = 0; c < brickColumnCount; c++) {
bricks[c] = [];
for (var r = 0; r < brickRowCount; r++) {
bricks[c][r] = { x: 0, y: 0, status: 1 };
}
}
document.addEventListener("keydown", keyDownHandler, false); //Listening for pressed keys
document.addEventListener("keyup", keyUpHandler, false);
function keyDownHandler(e) {
if (e.code == "ArrowRight") { //If key is pressed
rightPressed = true;
}
if (e.code == 'ArrowLeft') {
leftPressed = true;
}
else if (e.code == 'ArrowDown') {
downPressed = true;
}
}
function keyUpHandler(e) {
if (e.code == "ArrowRight") { //If key is up
rightPressed = false;
}
if (e.code == 'ArrowLeft') {
leftPressed = false;
}
else if (e.code == 'ArrowDown') {
downPressed = false;
}
}
function collisionDetection() {
for (var c = 0; c < brickColumnCount; c++) {
for (var r = 0; r < brickRowCount; r++) {
var b = bricks[c][r];
if (b.status == 1) {
if (x > b.x && x < b.x + brickWidth && y > b.y && y < b.y + brickHeight) {
dy = -dy;
b.status = 0;
score++;
if (score == brickRowCount * brickColumnCount) {
drawDeath();
}
}
}
}
}
}
function drawDeath() {
ctx.font = "32px Courier New";
ctx.fillStyle = "#000000";
ctx.fillText("HAHA YU LOOZD (pres doun arouw tu x-it)");
if (downPressed = true)
document.location.reload();
clearInterval(interval);
}
function drawScore() {
ctx.font = "16px Courier New";
ctx.fillStyle = "#0E17E8";
ctx.fillText("Scores is: " + score, 8, 20);
}
function drawBall() {
ctx.beginPath();
ctx.arc(x, y, ballRadius, 0, Math.PI * 2); //Drawing the Ball
ctx.fillStyle = "#32CD32";
ctx.fill();
ctx.closePath();
}
function drawPaddle() {
ctx.beginPath();
ctx.rect(paddleX, canvas.height - paddleHeight, paddleWidth, paddleHeight); //Drawing the Paddle
ctx.fillStyle = "#0095DD";
ctx.fill();
ctx.closePath();
}
function drawBricks() {
for (var c = 0; c < brickColumnCount; c++) {
for (var r = 0; r < brickRowCount; r++) {
if (bricks[c][r].status == 1) {
var brickX = (c * (brickWidth + brickPadding)) + brickOffsetLeft;
var brickY = (r * (brickHeight + brickPadding)) + brickOffsetTop;
bricks[c][r].x = brickX;
bricks[c][r].y = brickY;
ctx.beginPath();
ctx.rect(brickX, brickY, brickWidth, brickHeight);
if (randomNumber == 1)
ctx.fillStyle = "#0095DD";
if (randomNumber == 2)
ctx.fillStyle = "#FF0000";
if (randomNumber == 3)
ctx.fillStyle = "#FF8A00";
if (randomNumber == 4)
ctx.fillStyle = "0100FF";
ctx.fill()
ctx.closePath();
}
}
}
}
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height); //Clears the screen after each motion
drawBall();
drawPaddle();
drawBricks();
drawScore();
collisionDetection();
//dx = dx + (Math.floor(Math.random() * 5 - 2));
var cx = dx + (Math.floor(Math.random() * 5 - 2));
if (x + dx > canvas.width - ballRadius || x + dx < ballRadius) { //Bounces the ball
dx = -dx;
}
if (y + dy < ballRadius) {
dy = -dy;
} else if (y + dy > canvas.height - ballRadius) {
if (x > paddleX && x < paddleX + paddleWidth) { //Paddle Collision features
dy = -dy;
dx = cx;
}
else {
Text("HAHA YU LOOZD");
document.location.reload(); //Death Detection
clearInterval(interval);
}
}
if (rightPressed && paddleX < canvas.width - paddleWidth) { //Paddle Controls
paddleX += 7;
}
else if (leftPressed && paddleX > 0) {
paddleX -= 7;
}
x += dx;
y += dy;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Bad Gramarrs</title>
<style>
* {
padding: 0;
margin: 0;
}
canvas {
background: #eee;
display: block;
margin: 0 auto;
}
#main {
display: none;
}
#newGame, #creditBtn, #backBtn {
text-align: center;
vertical-align: middle;
border: 2px solid goldenrod;
border-radius: 7px;
background-color: gold;
color: orangeRed;
font-size: 32px;
font-weight: bold;
font-family: "Courier New";
width: 5em;
margin: 5px auto;
}
#theHead {
text-align: center;
margin: unset;
color: orange;
font-size: 2em;
font-family: "Courier New";
}
#credits {
text-align: center;
margin: unset;
color: orange;
font-size: 2em;
font-family: "Courier New";
display: none;
background-color: inherit;
}
#backBtn {
display: none;
}
</style>
</head>
<body>
<div id="theHead">Bad Gramarrs</div>
<div id="newGame" onclick="runGame()" onmouseover="this.style.backgroundColor = 'goldenrod'" onmouseout="this.style.backgroundColor = 'gold'">Strt Gaem</div>
<div id="creditBtn" onmouseover="this.style.backgroundColor = 'goldenrod'" onmouseout="this.style.backgroundColor = 'gold'" onclick="showCredits()">Credets</div>
<div id="credits">Bad Gramarrs: Maed buy mi</div>
<div id="backBtn" onmouseover="this.style.backgroundColor = 'goldenrod'" onmouseout="this.style.backgroundColor = 'gold'" onclick="goBack()">Back</div>
<div id="main">
<canvas id="myCanvas" width="480" height="320"></canvas>
</div>
<script src="atari.js"></script>
<script>
var runGame = function () {
document.getElementById("newGame").style.display = "none";
document.getElementById("theHead").style.display = "none";
document.getElementById("credits").style.display = "none";
document.getElementById("main").style.display = "block";
document.getElementById("creditBtn").style.display = "none";
randomNumber = Math.floor(Math.random() * 4 + 1);
};
var showCredits = function () {
document.getElementById("theHead").style.display = "none";
document.getElementById("creditBtn").style.display = "none";
document.getElementById("newGame").style.display = "none";
document.getElementById("credits").style.display = "block";
document.getElementById("backBtn").style.display = "block";
};
var goBack = function () {
document.getElementById("backBtn").style.display = "none";
document.getElementById("credits").style.display = "none";
document.getElementById("theHead").style.display = "block";
document.getElementById("newGame").style.display = "block";
document.getElementById("creditBtn").style.display = "block";
};
</script>
</body>
</html>
You have some errors in your code so I correct what the console showed. I have also changed the code to use requestAnimationFrame. Once a gameOver status has been triggered the requestAnimationFrame will stop running and setInterval will run the drawDeath function. You also have an error in your game over text as you were missing the x and y coordinates.
Additionally I added the downPressed variable that was missing so you could restart the game.
//var interval = setInterval(draw, 10);
let gameOver = false;
var canvas = document.getElementById("myCanvas"); //Variables for the canvas, ball, paddle, keys, and bricks
var ctx = canvas.getContext("2d");
var ballRadius = 10;
var x = canvas.width / 2;
var y = canvas.height - 30;
var dx = 2;
var dy = -2;
var paddleHeight = 10;
var paddleWidth = 75;
var paddleX = (canvas.width - paddleWidth) / 2;
var rightPressed = false;
var leftPressed = false;
var downPressed = false;
var brickRowCount = 3;
var brickColumnCount = 5;
var brickWidth = 75;
var brickHeight = 20;
var brickPadding = 10;
var brickOffsetTop = 30;
var brickOffsetLeft = 30;
var score = 0;
var bricks = [];
for (var c = 0; c < brickColumnCount; c++) {
bricks[c] = [];
for (var r = 0; r < brickRowCount; r++) {
bricks[c][r] = { x: 0, y: 0, status: 1 };
}
}
document.addEventListener("keydown", keyDownHandler, false); //Listening for pressed keys
document.addEventListener("keyup", keyUpHandler, false);
function keyDownHandler(e) {
if (e.code == "ArrowRight") { //If key is pressed
rightPressed = true;
}
if (e.code == 'ArrowLeft') {
leftPressed = true;
}
else if (e.code == 'ArrowDown') {
downPressed = true;
console.log('down')
}
}
function keyUpHandler(e) {
if (e.code == "ArrowRight") { //If key is up
rightPressed = false;
}
if (e.code == 'ArrowLeft') {
leftPressed = false;
}
else if (e.code == 'ArrowDown') {
downPressed = false;
}
}
function collisionDetection() {
for (var c = 0; c < brickColumnCount; c++) {
for (var r = 0; r < brickRowCount; r++) {
var b = bricks[c][r];
if (b.status == 1) {
if (x > b.x && x < b.x + brickWidth && y > b.y && y < b.y + brickHeight) {
dy = -dy;
b.status = 0;
score++;
if (score == brickRowCount * brickColumnCount) {
gameOver = true;
}
}
}
}
}
}
function drawDeath() {
ctx.font = "20px Courier New";
ctx.textAlign = 'center';
ctx.fillStyle = "#000000";
ctx.fillText("HAHA YU LOOZD (pres doun arouw tu x-it)", canvas.width/2, canvas.height/2);
if (downPressed == true)
document.location.reload();
}
function drawScore() {
ctx.font = "16px Courier New";
ctx.fillStyle = "#0E17E8";
ctx.fillText("Scores is: " + score, 8, 20);
}
function drawBall() {
ctx.beginPath();
ctx.arc(x, y, ballRadius, 0, Math.PI * 2); //Drawing the Ball
ctx.fillStyle = "#32CD32";
ctx.fill();
ctx.closePath();
}
function drawPaddle() {
ctx.beginPath();
ctx.rect(paddleX, canvas.height - paddleHeight, paddleWidth, paddleHeight); //Drawing the Paddle
ctx.fillStyle = "#0095DD";
ctx.fill();
ctx.closePath();
}
function drawBricks() {
let randomNumber;
for (var c = 0; c < brickColumnCount; c++) {
for (var r = 0; r < brickRowCount; r++) {
if (bricks[c][r].status == 1) {
var brickX = (c * (brickWidth + brickPadding)) + brickOffsetLeft;
var brickY = (r * (brickHeight + brickPadding)) + brickOffsetTop;
bricks[c][r].x = brickX;
bricks[c][r].y = brickY;
ctx.beginPath();
ctx.rect(brickX, brickY, brickWidth, brickHeight);
if (randomNumber == 1)
ctx.fillStyle = "#0095DD";
if (randomNumber == 2)
ctx.fillStyle = "#FF0000";
if (randomNumber == 3)
ctx.fillStyle = "#FF8A00";
if (randomNumber == 4)
ctx.fillStyle = "0100FF";
ctx.fill()
ctx.closePath();
}
}
}
}
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height); //Clears the screen after each motion
drawBall();
drawPaddle();
drawBricks();
drawScore();
collisionDetection();
//dx = dx + (Math.floor(Math.random() * 5 - 2));
var cx = dx + (Math.floor(Math.random() * 5 - 2));
if (x + dx > canvas.width - ballRadius || x + dx < ballRadius) { //Bounces the ball
dx = -dx;
}
if (y + dy < ballRadius) {
dy = -dy;
} else if (y + dy > canvas.height - ballRadius) {
if (x > paddleX && x < paddleX + paddleWidth) { //Paddle Collision features
dy = -dy;
dx = cx;
}
else {
gameOver = true;
setInterval(drawDeath, 10) //Death Detecti
}
}
if (rightPressed && paddleX < canvas.width - paddleWidth) { //Paddle Controls
paddleX += 7;
}
else if (leftPressed && paddleX > 0) {
paddleX -= 7;
}
x += dx;
y += dy;
if (!gameOver) requestAnimationFrame(draw)
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Bad Gramarrs</title>
<style>
* {
padding: 0;
margin: 0;
}
canvas {
background: #eee;
display: block;
margin: 0 auto;
}
#main {
display: none;
}
#newGame, #creditBtn, #backBtn {
text-align: center;
vertical-align: middle;
border: 2px solid goldenrod;
border-radius: 7px;
background-color: gold;
color: orangeRed;
font-size: 32px;
font-weight: bold;
font-family: "Courier New";
width: 5em;
margin: 5px auto;
}
#theHead {
text-align: center;
margin: unset;
color: orange;
font-size: 2em;
font-family: "Courier New";
}
#credits {
text-align: center;
margin: unset;
color: orange;
font-size: 2em;
font-family: "Courier New";
display: none;
background-color: inherit;
}
#backBtn {
display: none;
}
</style>
</head>
<body>
<div id="theHead">Bad Gramarrs</div>
<div id="newGame" onclick="runGame()" onmouseover="this.style.backgroundColor = 'goldenrod'" onmouseout="this.style.backgroundColor = 'gold'">Strt Gaem</div>
<div id="creditBtn" onmouseover="this.style.backgroundColor = 'goldenrod'" onmouseout="this.style.backgroundColor = 'gold'" onclick="showCredits()">Credets</div>
<div id="credits">Bad Gramarrs: Maed buy mi</div>
<div id="backBtn" onmouseover="this.style.backgroundColor = 'goldenrod'" onmouseout="this.style.backgroundColor = 'gold'" onclick="goBack()">Back</div>
<div id="main">
<canvas id="myCanvas" width="480" height="320"></canvas>
</div>
<script src="atari.js"></script>
<script>
var runGame = function () {
document.getElementById("newGame").style.display = "none";
document.getElementById("theHead").style.display = "none";
document.getElementById("credits").style.display = "none";
document.getElementById("main").style.display = "block";
document.getElementById("creditBtn").style.display = "none";
randomNumber = Math.floor(Math.random() * 4 + 1);
draw();
};
var showCredits = function () {
document.getElementById("theHead").style.display = "none";
document.getElementById("creditBtn").style.display = "none";
document.getElementById("newGame").style.display = "none";
document.getElementById("credits").style.display = "block";
document.getElementById("backBtn").style.display = "block";
};
var goBack = function () {
document.getElementById("backBtn").style.display = "none";
document.getElementById("credits").style.display = "none";
document.getElementById("theHead").style.display = "block";
document.getElementById("newGame").style.display = "block";
document.getElementById("creditBtn").style.display = "block";
};
</script>
</body>
</html>

I have a issue in my canvas. i want to change the color of particles. currently they are in black color. How i can change..?

I have a issue in my canvas. i want to change the color of particles. currently they are in black color. How i can change..?
here is my code please let me know if u have any solution.
I have a issue in my canvas. i want to change the color of particles. currently they are in black color. How i can change..?
here is my code please let me know if u have any solution. http://jsfiddle.net/gbcL0uks/
<head>
<title>
Text Particles
</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.css" />
<link rel="stylesheet" href="https://cdn.bootcss.com/hover.css/2.3.1/css/hover-min.css">
<meta property="og:title" content="Text Particles" />
<meta property="og:description" content="Some cool canvas pixel manipulation" />
<meta property="og:image" content="http://william.hoza.us/images/text-small.png" />
<style>
#import url('https://fonts.googleapis.com/css?family=Bree+Serif');
body {
font-family: 'Bree Serif', serif;
}
.float {
position: absolute;
left: 20px;
}
.menu {
position: absolute;
top: 20px;
right: 20px;
cursor: pointer;
}
.fa-bars {
font-size: 24px;
border: 2px solid #333333;
padding: 12px;
transition: .4s;
}
.fa-bars:hover {
background: #333333;
color: #f7d600;
}
.overlay {
height: 100%;
width: 100%;
position: fixed;
z-index: 1;
top: 0;
left: -100%;
background-color: rgb(0, 0, 0);
background-color: rgba(0, 0, 0, 0.9);
overflow-x: hidden;
transition: 0.5s;
}
.overlay-content {
position: relative;
top: 50%;
width: 100%;
text-align: center;
margin-top: 30px;
transform: translate(0, -100%);
}
.overlay a {
padding: 8px;
text-decoration: none;
font-size: 6rem;
color: #818181;
display: inline-block;
transition: 0.3s;
margin: 0 3rem;
}
.overlay a:hover,
.overlay a:focus {
color: #f1f1f1;
}
.overlay .closebtn {
position: absolute;
top: 20px;
right: 0;
font-size: 60px;
}
#media screen and (max-height: 450px) {
.overlay a {
font-size: 20px
}
.overlay .closebtn {
font-size: 40px;
top: 15px;
right: 0;
}
}
</style>
</head>
<body style="margin:0px; background:#f7d600;">
<div class="float">
<h1>Herbialis</h1>
</div>
<!-- <div class="menu">
<i class="fa fa-bars"></i>
</div> -->
<div id="myNav" class="overlay">
×
<div class="overlay-content">
About
Products
Contact
</div>
</div>
<div class="menu">
<i class="fa fa-bars" onclick="openNav()"></i>
</div>
<canvas id="canv" onmousemove="canv_mousemove(event);" onmouseout="mx=-1;my=-1;">
you need a canvas-enabled browser, such as Google Chrome
</canvas>
<canvas id="wordCanv" width="500px" height="500px" style="border:1px solid black;display:none;">
</canvas>
<textarea id="wordsTxt" style="position:absolute;left:-100;top:-100;" onblur="init();" onkeyup="init();" onclick="init();"></textarea>
<script type="text/javascript">
var l = document.location + "";
l = l.replace(/%20/g, " ");
var index = l.indexOf('?t=');
if (index == -1) document.location = l + "?t=Hello world";
var pixels = new Array();
var canv = $('canv');
var ctx = canv.getContext('2d');
var wordCanv = $('wordCanv');
var wordCtx = wordCanv.getContext('2d');
var mx = -1;
var my = -1;
var words = "";
var txt = new Array();
var cw = 0;
var ch = 0;
var resolution = 1;
var n = 0;
var timerRunning = false;
var resHalfFloor = 0;
var resHalfCeil = 0;
function canv_mousemove(evt) {
mx = evt.clientX - canv.offsetLeft;
my = evt.clientY - canv.offsetTop;
}
function Pixel(homeX, homeY) {
this.homeX = homeX;
this.homeY = homeY;
this.x = Math.random() * cw;
this.y = Math.random() * ch;
//tmp
this.xVelocity = Math.random() * 10 - 5;
this.yVelocity = Math.random() * 10 - 5;
}
Pixel.prototype.move = function () {
var homeDX = this.homeX - this.x;
var homeDY = this.homeY - this.y;
var homeDistance = Math.sqrt(Math.pow(homeDX, 2) + Math.pow(homeDY, 2));
var homeForce = homeDistance * 0.01;
var homeAngle = Math.atan2(homeDY, homeDX);
var cursorForce = 0;
var cursorAngle = 0;
if (mx >= 0) {
var cursorDX = this.x - mx;
var cursorDY = this.y - my;
var cursorDistanceSquared = Math.pow(cursorDX, 2) + Math.pow(cursorDY, 2);
cursorForce = Math.min(10000 / cursorDistanceSquared, 10000);
cursorAngle = Math.atan2(cursorDY, cursorDX);
} else {
cursorForce = 0;
cursorAngle = 0;
}
this.xVelocity += homeForce * Math.cos(homeAngle) + cursorForce * Math.cos(cursorAngle);
this.yVelocity += homeForce * Math.sin(homeAngle) + cursorForce * Math.sin(cursorAngle);
this.xVelocity *= 0.92;
this.yVelocity *= 0.92;
this.x += this.xVelocity;
this.y += this.yVelocity;
}
function $(id) {
return document.getElementById(id);
}
function timer() {
if (!timerRunning) {
timerRunning = true;
setTimeout(timer, 33);
for (var i = 0; i < pixels.length; i++) {
pixels[i].move();
}
drawPixels();
wordsTxt.focus();
n++;
if (n % 10 == 0 && (cw != document.body.clientWidth || ch != document.body.clientHeight)) body_resize();
timerRunning = false;
} else {
setTimeout(timer, 10);
}
}
function drawPixels() {
var imageData = ctx.createImageData(cw, ch);
var actualData = imageData.data;
var index;
var goodX;
var goodY;
var realX;
var realY;
for (var i = 0; i < pixels.length; i++) {
goodX = Math.floor(pixels[i].x);
goodY = Math.floor(pixels[i].y);
for (realX = goodX - resHalfFloor; realX <= goodX + resHalfCeil && realX >= 0 && realX < cw; realX++) {
for (realY = goodY - resHalfFloor; realY <= goodY + resHalfCeil && realY >= 0 && realY < ch; realY++) {
index = (realY * imageData.width + realX) * 4;
actualData[index + 3] = 255;
}
}
}
imageData.data = actualData;
ctx.putImageData(imageData, 0, 0);
}
function readWords() {
words = $('wordsTxt').value;
txt = words.split('\n');
}
function init() {
readWords();
var fontSize = 200;
var wordWidth = 0;
do {
wordWidth = 0;
fontSize -= 5;
wordCtx.font = fontSize + "px sans-serif";
for (var i = 0; i < txt.length; i++) {
var w = wordCtx.measureText(txt[i]).width;
if (w > wordWidth) wordWidth = w;
}
} while (wordWidth > cw - 50 || fontSize * txt.length > ch - 50)
wordCtx.clearRect(0, 0, cw, ch);
wordCtx.textAlign = "center";
wordCtx.textBaseline = "middle";
for (var i = 0; i < txt.length; i++) {
wordCtx.fillText(txt[i], cw / 2, ch / 2 - fontSize * (txt.length / 2 - (i + 0.5)));
}
var index = 0;
var imageData = wordCtx.getImageData(0, 0, cw, ch);
for (var x = 0; x < imageData.width; x += resolution) //var i=0;i<imageData.data.length;i+=4)
{
for (var y = 0; y < imageData.height; y += resolution) {
i = (y * imageData.width + x) * 4;
if (imageData.data[i + 3] > 128) {
if (index >= pixels.length) {
pixels[index] = new Pixel(x, y);
} else {
pixels[index].homeX = x;
pixels[index].homeY = y;
}
index++;
}
}
}
pixels.splice(index, pixels.length - index);
}
function body_resize() {
cw = document.body.clientWidth;
ch = document.body.clientHeight;
canv.width = cw;
canv.height = ch;
wordCanv.width = cw;
wordCanv.height = ch;
init();
}
wordsTxt.focus();
wordsTxt.value = l.substring(index + 3);
resHalfFloor = Math.floor(resolution / 2);
resHalfCeil = Math.ceil(resolution / 2);
body_resize();
timer();
</script>
<script>
function openNav() {
document.getElementById("myNav").style.left = "0";
}
function closeNav() {
document.getElementById("myNav").style.left = "-100%";
}
</script>
</body>
</html>
Add 3 color components to image data. For example, for orange color:
for (realX = goodX - resHalfFloor; realX <= goodX + resHalfCeil && realX >= 0 && realX < cw; realX++) {
for (realY = goodY - resHalfFloor; realY <= goodY + resHalfCeil && realY >= 0 && realY < ch; realY++) {
index = (realY * imageData.width + realX) * 4;
actualData[index + 0] = 253; // Red component
actualData[index + 1] = 106; // Green component
actualData[index + 2] = 2; // Blue component
actualData[index + 3] = 255;
}
}

CSS and Javascript animation from codepen not working

I have the following code from a codepen post that I have tried to re-create using a single html page. The design shows up fine, but the animation doesn't seem to work.
The codepen link is here:
https://codepen.io/MarcoGuglielmelli/pen/lLCxy
The code I have (copied from the above) and I have used the compiled CSS from codepen is here:
<html>
<head>
<style>
/* Header */
.large-header {
position: relative;
width: 100%;
background: #333;
overflow: hidden;
background-size: cover;
background-position: center center;
z-index: 1;
}
#large-header {
background-image: url("https://www.marcoguglie.it/Codepen/AnimatedHeaderBg/demo-1/img/demo-1-bg.jpg");
}
.main-title {
position: absolute;
margin: 0;
padding: 0;
color: #f9f1e9;
text-align: center;
top: 50%;
left: 50%;
-webkit-transform: translate3d(-50%, -50%, 0);
transform: translate3d(-50%, -50%, 0);
}
.demo-1 .main-title {
text-transform: uppercase;
font-size: 4.2em;
letter-spacing: 0.1em;
}
.main-title .thin {
font-weight: 200;
}
#media only screen and (max-width: 768px) {
.demo-1 .main-title {
font-size: 3em;
}
}
</style>
</head>
<body>
<div id="large-header" class="large-header">
<canvas id="demo-canvas"></canvas>
<h1 class="main-title"><span class="thin">TitleGoes <span class="thin">.here</span></h1>
</div>
<script>
(function() {
var width, height, largeHeader, canvas, ctx, points, target, animateHeader = true;
// Main
initHeader();
initAnimation();
addListeners();
function initHeader() {
width = window.innerWidth;
height = window.innerHeight;
target = {x: width/2, y: height/2};
largeHeader = document.getElementById('large-header');
largeHeader.style.height = height+'px';
canvas = document.getElementById('demo-canvas');
canvas.width = width;
canvas.height = height;
ctx = canvas.getContext('2d');
// create points
points = [];
for(var x = 0; x < width; x = x + width/20) {
for(var y = 0; y < height; y = y + height/20) {
var px = x + Math.random()*width/20;
var py = y + Math.random()*height/20;
var p = {x: px, originX: px, y: py, originY: py };
points.push(p);
}
}
// for each point find the 5 closest points
for(var i = 0; i < points.length; i++) {
var closest = [];
var p1 = points[i];
for(var j = 0; j < points.length; j++) {
var p2 = points[j]
if(!(p1 == p2)) {
var placed = false;
for(var k = 0; k < 5; k++) {
if(!placed) {
if(closest[k] == undefined) {
closest[k] = p2;
placed = true;
}
}
}
for(var k = 0; k < 5; k++) {
if(!placed) {
if(getDistance(p1, p2) < getDistance(p1, closest[k])) {
closest[k] = p2;
placed = true;
}
}
}
}
}
p1.closest = closest;
}
// assign a circle to each point
for(var i in points) {
var c = new Circle(points[i], 2+Math.random()*2, 'rgba(255,255,255,0.3)');
points[i].circle = c;
}
}
// Event handling
function addListeners() {
if(!('ontouchstart' in window)) {
window.addEventListener('mousemove', mouseMove);
}
window.addEventListener('scroll', scrollCheck);
window.addEventListener('resize', resize);
}
function mouseMove(e) {
var posx = posy = 0;
if (e.pageX || e.pageY) {
posx = e.pageX;
posy = e.pageY;
}
else if (e.clientX || e.clientY) {
posx = e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;
posy = e.clientY + document.body.scrollTop + document.documentElement.scrollTop;
}
target.x = posx;
target.y = posy;
}
function scrollCheck() {
if(document.body.scrollTop > height) animateHeader = false;
else animateHeader = true;
}
function resize() {
width = window.innerWidth;
height = window.innerHeight;
largeHeader.style.height = height+'px';
canvas.width = width;
canvas.height = height;
}
// animation
function initAnimation() {
animate();
for(var i in points) {
shiftPoint(points[i]);
}
}
function animate() {
if(animateHeader) {
ctx.clearRect(0,0,width,height);
for(var i in points) {
// detect points in range
if(Math.abs(getDistance(target, points[i])) < 4000) {
points[i].active = 0.3;
points[i].circle.active = 0.6;
} else if(Math.abs(getDistance(target, points[i])) < 20000) {
points[i].active = 0.1;
points[i].circle.active = 0.3;
} else if(Math.abs(getDistance(target, points[i])) < 40000) {
points[i].active = 0.02;
points[i].circle.active = 0.1;
} else {
points[i].active = 0;
points[i].circle.active = 0;
}
drawLines(points[i]);
points[i].circle.draw();
}
}
requestAnimationFrame(animate);
}
function shiftPoint(p) {
TweenLite.to(p, 1+1*Math.random(), {x:p.originX-50+Math.random()*100,
y: p.originY-50+Math.random()*100, ease:Circ.easeInOut,
onComplete: function() {
shiftPoint(p);
}});
}
// Canvas manipulation
function drawLines(p) {
if(!p.active) return;
for(var i in p.closest) {
ctx.beginPath();
ctx.moveTo(p.x, p.y);
ctx.lineTo(p.closest[i].x, p.closest[i].y);
ctx.strokeStyle = 'rgba(156,217,249,'+ p.active+')';
ctx.stroke();
}
}
function Circle(pos,rad,color) {
var _this = this;
// constructor
(function() {
_this.pos = pos || null;
_this.radius = rad || null;
_this.color = color || null;
})();
this.draw = function() {
if(!_this.active) return;
ctx.beginPath();
ctx.arc(_this.pos.x, _this.pos.y, _this.radius, 0, 2 * Math.PI, false);
ctx.fillStyle = 'rgba(156,217,249,'+ _this.active+')';
ctx.fill();
};
}
// Util
function getDistance(p1, p2) {
return Math.pow(p1.x - p2.x, 2) + Math.pow(p1.y - p2.y, 2);
}
})();
</script>
</body>
</html>
Can someone point to the error (why is there no animation?) and how can I fix it?
This codepen has a number of external resources listed. Try clicking on the 'cog' icon to the top left of each of the three windows, and you will see the external resources:
Try adding this to your <head>
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Raleway:200,400,800" />
<link rel="stylesheet" href="https://www.marcoguglie.it/Codepen/AnimatedHeaderBg/demo-1/css/demo.css" />
<script src="https://www.marcoguglie.it/Codepen/AnimatedHeaderBg/demo-1/js/EasePack.min.js"></script>
<script src="https://www.marcoguglie.it/Codepen/AnimatedHeaderBg/demo-1/js/rAF.js"></script>
<script src="https://www.marcoguglie.it/Codepen/AnimatedHeaderBg/demo-1/js/TweenLite.min.js"></script>

Can't figure out where to draw image in Javascript code

I am having issues trying to place an image as an object for an "asteroid avoidance" game. I was able to get the game itself to work based on what was written in my book "Foundation: HTML5 Canvas for Games and Entertainment". I want to go one step beyond what was written in the book. I want to replace the triangle shaped ship with that of an image. However, I am unable to figure out where to put the code for this.draw. My professor showed us a way to do it. When I try to implement it into my code it doesn't want to work properly. May I ask for some advice on how to place the image as the ship?
Here is my working code from the book, before I made any this.draw edits:(http://jsbin.com/tukejopofo/1/)
$(document).ready(function() {
var canvas = $("#gameCanvas");
var context = canvas.get(0).getContext("2d");
//canvas dimensions
var canvasWidth = canvas.width();
var canvasHeight = canvas.height();
var playGame;
var asteroids;
var numAsteroids;
var player;
var score;
var scoreTimeout;
var arrowUp = 38;
var arrowRight = 39;
var arrowDown = 40;
var arrowLeft = 37;
//game UI
var ui = $("#gameUI");
var uiIntro = $("#gameIntro");
var uiStats = $("#gameStats");
var uiComplete = $("#gameComplete");
var uiPlay = $("#gamePlay");
var uiReset = $(".gameReset");
var uiScore = $(".gameScore");
var soundBackground = $("#gameSoundBackground").get(0);
var soundThrust = $("#gameSoundThrust").get(0);
var soundDeath = $("#gameSoundDeath").get(0);
var Asteroid = function(x, y, radius, vX) {
this.x = x;
this.y = y;
this.radius = radius;
this.vX = vX;
};
var Player = function(x, y) {
this.x = x;
this.y = y;
this.width = 24;
this.height = 24;
this.halfWidth = this.width / 2;
this.halfHeight = this.height / 2;
this.flameLength1 = 20;
this.flameLength2 = 20;
this.vX = 0;
this.vY = 0;
this.moveRight = false;
this.moveUp = false;
this.moveDown = false;
this.moveLeft = false;
};
//Reset and start the game
function startGame() {
//Reset game stats
uiScore.html("0");
uiStats.show();
//set up initial game settings
playGame = false;
asteroids = new Array();
numAsteroids = 10;
score = 0;
player = new Player(150, canvasHeight / 2, 50, 50);
for (var i = 0; i < numAsteroids; i++) {
var radius = 5 + (Math.random() * 10);
var x = canvasWidth + radius + Math.floor(Math.random() * canvasWidth);
var y = Math.floor(Math.random() * canvasHeight);
var vX = -5 - (Math.random() * 5);
asteroids.push(new Asteroid(x, y, radius, vX));
};
$(window).keydown(function(e) {
var keyCode = e.keyCode;
if (!playGame) {
playGame = true;
soundBackground.currentTime = 0;
soundBackground.play();
animate();
timer();
};
if (keyCode == arrowRight) {
player.moveRight = true;
if (soundThrust.paused) {
soundThrust.currentTime = 0;
soundThrust.play();
}
} else if (keyCode == arrowLeft) {
player.moveLeft = true;
} else if (keyCode == arrowUp) {
player.moveUp = true;
} else if (keyCode == arrowDown) {
player.moveDown = true;
}
});
$(window).keyup(function(e) {
var keyCode = e.keyCode;
if (!playGame) {
playGame = true;
animate();
};
if (keyCode == arrowRight) {
player.moveRight = false;
if (keyCode == arrowRight) {
player.moveRight = false;
soundThrust.pause();
}
} else if (keyCode == arrowUp) {
player.moveUp = false;
} else if (keyCode == arrowDown) {
player.moveDown = false;
} else if (keyCode == arrowLeft) {
player.moveLeft = false;
}
});
//start the animation loop
animate();
};
//initialize the game environment
function init() {
uiStats.hide();
uiComplete.hide();
uiPlay.click(function(e) {
e.preventDefault();
uiIntro.hide();
startGame();
});
uiReset.click(function(e) {
e.preventDefault();
uiComplete.hide();
$(window).unbind("keyup");
$(window).unbind("keydown");
soundThrust.pause();
soundBackground.pause();
clearTimeout(scoreTimeout);
startGame();
});
};
function timer() {
if (playGame) {
scoreTimeout = setTimeout(function() {
uiScore.html(++score);
if (score % 5 == 0) {
numAsteroids += 5;
}
timer();
}, 1000);
};
};
//Animation loop that does all the fun stuff
function animate() {
//Clear
context.clearRect(0, 0, canvasWidth, canvasHeight);
var asteroidsLength = asteroids.length;
for (var i = 0; i < asteroidsLength; i++) {
var tmpAsteroid = asteroids[i];
tmpAsteroid.x += tmpAsteroid.vX;
if (tmpAsteroid.x + tmpAsteroid.radius < 0) { //creates bounderies to prevent player from leaving the canvas
tmpAsteroid.radius = 5 + (Math.random() * 10);
tmpAsteroid.x = canvasWidth + tmpAsteroid.radius;
tmpAsteroid.y = Math.floor(Math.random() * canvasHeight);
tmpAsteroid.vX = -5 - (Math.random() * 5);
}
var dX = player.x - tmpAsteroid.x;
var dY = player.y - tmpAsteroid.y;
var distance = Math.sqrt((dX * dX) + (dY * dY));
if (distance < player.halfWidth + tmpAsteroid.radius) { //checks for collision
soundThrust.pause()
soundDeath.currentTime = 0;
soundDeath.play();
//Game over
playGame = false;
clearTimeout(scoreTimeout);
uiStats.hide();
uiComplete.show();
soundBackground.pause();
$(window).unbind("keyup"); //unbinds keys to stop player movement at the end of the game
$(window).unbind("keydown");
};
context.fillStyle = "rgb(255, 255, 255)";
context.beginPath();
context.arc(tmpAsteroid.x, tmpAsteroid.y, tmpAsteroid.radius, 0, Math.PI * 2, true);
context.fill();
};
player.vX = 0;
player.vY = 0;
if (player.moveRight) {
player.vX = 3;
};
if (player.moveLeft) {
player.vX = -3;
};
if (player.moveUp) {
player.vY = -3;
};
if (player.moveDown) {
player.vY = 3;
};
player.x += player.vX;
player.y += player.vY;
if (player.x - player.halfWidth < 20) {
player.x = 20 + player.halfWidth;
} else if (player.x + player.halfWidth > canvasWidth - 20) {
player.x = canvasWidth - 20 - player.halfWidth;
}
if (player.y - player.halfHeight < 20) {
player.y = 20 + player.halfHeight;
} else if (player.y + player.halfHeight > canvasHeight - 20) {
player.y = canvasHeight - 20 - player.halfHeight;
}
if (player.moveRight) {
context.save();
context.translate(player.x - player.halfWidth, player.y);
if (player.flameLength1 == 20) {
player.flameLength1 = 15;
(player.flameLength2 == 20)
player.flameLength2 = 15;
} else {
player.flameLength1 = 20;
player.flameLength2 = 20;
};
context.fillStyle = "orange";
context.beginPath();
context.moveTo(0, -12);
context.lineTo(-player.flameLength1, -7);
context.lineTo(0, -5);
context.closePath();
context.fill();
context.fillStyle = "orange";
context.beginPath();
context.moveTo(0, 12);
context.lineTo(-player.flameLength2, 7);
context.lineTo(0, 5);
context.closePath();
context.fill();
context.restore();
};
//draw ship
context.fillStyle = "rgb(255, 0, 0)";
context.beginPath();
context.moveTo(player.x + player.halfWidth, player.y);
context.lineTo(player.x - player.halfWidth, player.y - player.halfHeight);
context.lineTo(player.x - player.halfWidth, player.y + player.halfHeight);
context.closePath();
context.fill();
while (asteroids.length < numAsteroids) { //adds asteroids as the difficulty increases
var radius = 5 + (Math.random() * 10)
var x = Math.floor(Math.random() * canvasWidth) + canvasWidth + radius;
var y = Math.floor(Math.random() * canvasHeight);
var vX = -5 - (Math.random() * 5);
asteroids.push(new Asteroid(x, y, radius, vX));
}
if (playGame) {
//run the animation loop again in 33 milliseconds
setTimeout(animate, 24);
};
};
init();
});
* {
margin: 0;
padding: 0;
}
html,
body {
height: 100%;
width: 100%;
}
canvas {
display: block;
}
body {
background: #000;
color: #fff;
font-family: Verdana, Arial, sans-serif;
font-size: 18px;
}
h1 {
font-size: 30px;
}
h6 {
font-size: 15px;
}
p {
margin: 0 20px;
}
a {
color: #fff;
text-decoration: none;
}
a:hover {
text-decoration: underline;
}
a.button {
background: #185da8;
border-radius: 5px;
display: block;
font-size: 30px;
margin: 40px 0 0 350px;
padding: 10px;
width: 200px;
text-align: center;
}
a.button:hover {
background: #2488f5;
color: #fff;
text-decoration: none;
}
#game {
height: 600px;
left: 50%;
margin: -250px 0 0 -500px;
position: relative;
top: 50%;
width: 980px;
}
#gameCanvas {
background: #001022;
border: 5px solid green;
background-image: url(../images/space.jpg);
background-position: center top;
background-repeat: no-repeat;
background-size: cover;
}
#gameUI {
height: 600px;
position: absolute;
width: 980px;
}
#gameIntro,
#gameComplete {
background: rgba(0, 0, 0, 0.5);
margin: 100px 0 0 10px;
padding: 40px 0;
text-align: center;
}
#gameStats {
font-size: 14px;
margin: 20px 0;
}
#gameStats .gameReset {
margin: 20px 20px 0 0;
position: absolute;
right: 0;
top: 0;
}
<body>
<div id="game">
<div id="gameUI">
<div id="gameIntro">
<h1>Debris Fields of Spiral Galaxy</h1>
<h6>A <i>Galaxy Smuggler's Run</i> Game</h6>
<hr>
<p>You are Captain Amadaeus delivering goods to a dependent planet on the other side of a debris field</p>
<p>Click <i>"Play"</i> and then press any key to start.</p>
<p><a id="gamePlay" class="button" href="">Play!</a>
</p>
</div>
<div id="gameStats">
<p><b>Time: </b><span class="gameScore"></span> seconds</p>
<p><a class="gameReset" href="">Reset</a>
</p>
</div>
<div id="gameComplete">
<h1>Game Over!</h1>
<p>You survived for <span class="gameScore"></span> seconds.</p>
<p>Would you like to give it another go?</p>
<p><a class="gameReset button" href="">Play Again?</a>
</p>
</div>
</div>
<canvas id="gameCanvas" width="980" height="600">
</canvas>
<audio id="gameSoundBackground" loop>
<source src="sounds/background.ogg">
<source src="sounds/background.mp3">
</audio>
<audio id="gameSoundThrust" loop>
<source src="sounds/thrust.ogg">
<source src="sounds/thrust.mp3">
</audio>
<audio id="gameSoundDeath">
<source src="sounds/death.ogg">
<source src="sounds/death.mp3">
</audio>
</div>
</body>
and here is my Professor's code for drawing an image:(http://jsbin.com/rapayufafe/1/)
// JS file for the ship
function Ship() {
this.x = 100;
this.y = 100;
this.color = "yellow";
this.fillStyle = "white";
this.vx = 0;
this.vy = 0;
this.ax = 1;
this.ay = 1;
//function "move" that will add velocity to the position of the ship
this.move = function() {
this.x += this.vx;
this.y += this.vy;
}//end move function
//draw the ship
this.draw=function () {
//ship var
var imageObj = new Image();
imageObj.src = "images/ship.png";
//save the current state of the canvas
context.save();
//moving the point of origin (0,0) to the ships x and y coordinates
context.translate(this.x,this.y);
context.lineStyle = this.color;
context.fillStyle = this.fillStyle;
/*context.beginPath();
context.moveTo(25,0);
context.lineTo(-25,25)
context.lineTo(-25,-25)*/
//draw ship
context.drawImage(imageObj,-25,-25,50,50);
context.closePath();
context.stroke();
context.fill();
context.restore();
}//end of draw ship
}//end ship function
/*var asteroidsLength = asteroids.length;
for (var i = 0; i < asteroidsLength; i++) {
var tmpAsteroid = asteroids[i];
context.fillStyle = "gray";
context.beginPath();
context.arc(tmpAsteroid.x, tmpAsteroid.y, tmpAsteroid.radius, 0, Math.PI*2, true);
context.closePath();
context.fill();
};*/
As you can see in your starting code, you have a section looking like this:
//draw ship
context.fillStyle = "rgb(255, 0, 0)";
context.beginPath();
context.moveTo(player.x + player.halfWidth, player.y);
context.lineTo(player.x - player.halfWidth, player.y - player.halfHeight);
context.lineTo(player.x - player.halfWidth, player.y + player.halfHeight);
context.closePath();
context.fill();
Just replace that code with the code for drawing an image.
var imageObj = new Image();
imageObj.src = "images/ship.png";
context.drawImage(imageObj,player.x,player.y);
Although, I'd recommend declaring the imageObj and setting the source at the top of your code where you declare the rest of your variables so that you don't load the image every time you want to draw the ship.

Removing mousemove

I'm developing an app to help autistic children prepare to learn to write. It's very straight forward. They just need to draw a line straight down. I have it working very similar to "connect the dots" where they start at a green light, progress to yellow and then to red. However, on my webpage using a mouse everything works great because the "dots" are "touched" using the mouseover, like so:
<script type="text/javascript" src="jquery-1.4.2.min.js"></script>
<script src="jquery.min.js" type="text/javascript"></script>
<script src="jquery.jplayer.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(function() {
var dots = [13, 15, 13, 25, 13, 55, -1, -1,
45, 15, 45, 40, -1, -1,
70, 15, 70, 40, -1, -1,
80, 15, 80, 40, 80, 60, -1, -1];
function contains(arr, value) {
for (var i = 0; i < arr.length; i++) {
if (arr[i] == value) {
return true;
}
}
return false;
}
function getRandomPoints(totalPoints) {
var indexes = new Array();
for (var i = 0; i < totalPoints; i++) {
var done = false;
while (!done) {
var index = Math.floor(Math.random() * dots.length);
if (index % 2 != 0) {
index++;
if (index > dots.length) {
continue;
}
}
if (!contains(indexes, index)) {
indexes.push(index);
done = true;
}
}
}
return indexes.sort(function(a, b) {
return a - b;
});
}
function displayGrid(ctx) {
var gridSize = 20, width = 900;
for (var ypos = 0; ypos < width; ypos += gridSize) {
ctx.moveTo(0, ypos);
ctx.lineTo(width, ypos);
}
for (var xpos = 0; xpos < width; xpos += gridSize) {
ctx.moveTo(xpos, 0);
ctx.lineTo(xpos, width);
}
ctx.strokeStyle = "#eee";
ctx.lineWidth = .7;
ctx.stroke();
}
function addPoint(index, x1, y1) {
for (var i = 0; i < points.length; i++) {
var x2 = points[i].x, y2 = points[i].y;
var d1 = Math.sqrt(Math.pow(y2 - y1, 2) + Math.pow(x2 - x1, 2));
var d2 = radius * 2 + 2;
if (d2 > d1) {
return false;
}
}
points.push({ 'x': x1, 'y': y1, 'index': index });
return true;
}
//Initialization....
var $graph = $('#graph'), gpos = $graph.position();
var $timer = $('#timer');
var points = new Array();
var ctx = $graph.get(0).getContext("2d");
//Parameters...
var indexes = getRandomPoints(7), ratio = 3, hops = 0, point = 0, maxTotalHops = 60, radius = 12;
var lineWidth = 11.5;
var xDisplacement = 0, yDisplacement = 0;
var borderColor = 'rgb(0,102,204)';
//Display the character's fixed lines...
ctx.beginPath();
ctx.translate(xDisplacement, yDisplacement);
ctx.lineWidth = lineWidth;
for (var i = 0; i < dots.length; i += 2) {
var newLine = dots[i] == -1;
if (newLine) {
i += 2;
}
var x = ratio * dots[i], y = ratio * dots[i + 1];
if (hops == 0 && contains(indexes, i)) {
hops++;
ctx.moveTo(x, y);
continue;
}
if (newLine || i == 0) {
ctx.moveTo(x, y);
}
else {
if (hops == 0) {
ctx.lineTo(x, y);
}
else {
ctx.strokeStyle = borderColor;
ctx.stroke();
ctx.beginPath();
if (addPoint(i, x, y)) {
var cx = gpos.left + xDisplacement - radius + 1 + x;
var cy = gpos.top + yDisplacement - radius + 1 + y;
$('<span></span>')
.addClass('circle')
.html(++point)
.data('pos', { 'x': cx, 'y': cy })
.css({ 'top': 0, 'left': 0 })
.insertAfter($graph);
}
}
}
if (hops > maxTotalHops) {
hops = 0;
}
else if (hops > 0) {
hops++;
}
}
ctx.strokeStyle = borderColor;
ctx.stroke();
//Create and initialize hotspots...
var passed = 0;
$('.circle').each(function() {
var pos = $(this).data('pos');
$(this).animate({
left: pos.x,
top: pos.y
}, 700);
}).mousemove(function() { // <====================== this part
var index = parseInt($(this).text());
if (passed != index - 1) {
return;
}
$(this).css({
'color': '#c00',
'font-weight': 'bold'
}).animate({
left: 0,
top: 0,
opacity: 0
}, 1000);
ctx.beginPath();
var start, end, done = passed + 1 == points.length;
if (done) /*The entire hotspots are detected...*/{
start = 0;
end = dots.length - 2;
clearInterval(tid);
$timer.html('Well done, it took ' + $timer.html() + ' seconds!').animate({
left: gpos.left + $graph.width() - $timer.width() - 20
}, 1000);
}
else {
start = passed == 0 ? points[passed].index - 4 : points[passed - 1].index;
end = points[passed].index;
}
for (var i = start; i <= end; i += 2) {
var newLine = dots[i] == -1;
if (newLine) {
i += 2;
}
var x = ratio * dots[i], y = ratio * dots[i + 1];
if (newLine || i == start) {
ctx.moveTo(x, y);
}
else {
ctx.lineTo(x, y);
}
}
ctx.lineWidth = lineWidth;
ctx.strokeStyle = borderColor;
ctx.stroke();
if (done) {
$('.filled').css({
left: gpos.left + xDisplacement + 10,
top: gpos.top + yDisplacement + 150
}).fadeIn('slow');
}
passed++;
});
//Initialize timer...
$timer.css({
top: gpos.top + 10,
left: gpos.left + 10
});
var timer = 0, tid = setInterval(function() {
timer += 30 / 1000;
$timer.html(timer.toFixed(2));
}, 30);
});
</script>
<style type="text/css">
.circle {
background: url('start.png');
width: 24px;
height: 24px;
text-align: center;
font-size: .8em;
line-height: 24px;
display: block;
position: absolute;
cursor: pointer;
color: #333;
z-index: 100;
}
.filled {
background: url('train.gif');
position: absolute;
width: 172px;
height: 251px;
display: none;
}
#timer {
position: absolute;
font-family: Arial;
font-weight: bold;
font-size: 1em;
background: #c00;
color: #fff;
padding: 5px;
text-align: center;
-moz-border-radius: 5px;
-webkit-border-radius: 5px;
font-variant: small-caps;
}
#graph {
background: url('vlinesbackground.jpg');
left: 5px;
top: 20px;
position: relative;
border: 1px dotted #ddd;
}
</style>
But I'm trying to replace the mousemove so the app can be used on the iphone. I've worked out everything else but triggering the "dots" and although I've looked at all the touchstart/touchmove info I can google, nothing appears to be working. Suggestions? Thanks!

Categories