i am trying to get alert from the main big circle alone. The alert should not come from the small circles.
How to get alert from the big circle alone? and Text for small circle should be in the bottom the each circle. For me its showing in the top right corner of the circles. Can anyone help me to solve this thing?
Thanks in advance
var noop = function() {
return this;
};
function UserCanceledError() {
this.name = 'UserCanceledError';
this.message = 'User canceled dialog';
}
UserCanceledError.prototype = Object.create(Error.prototype);
function Dialog() {
this.setCallbacks(noop, noop);
}
Dialog.prototype.setCallbacks = function(okCallback, cancelCallback) {
this._okCallback = okCallback;
return this;
};
Dialog.prototype.waitForUser = function() {
var _this = this;
return new Promise(function(resolve, reject) {
_this.setCallbacks(resolve, reject);
});
};
Dialog.prototype.show = noop;
Dialog.prototype.hide = noop;
function PromptDialog() {
Dialog.call(this);
this.el = document.getElementById('dialog');
this.messageEl = this.el.querySelector('.message');
this.okButton = this.el.querySelector('button.ok');
this.attachDomEvents();
}
PromptDialog.prototype = Object.create(Dialog.prototype);
PromptDialog.prototype.attachDomEvents = function() {
var _this = this;
this.okButton.addEventListener('click', function() {
_this.hide();
console.log('Ok clicked!!');
});
};
PromptDialog.prototype.show = function(message) {
this.messageEl.innerHTML = '' + message;
this.el.className = '';
return this;
};
PromptDialog.prototype.hide = function() {
this.el.className = 'hidden';
return this;
};
var prompt = new PromptDialog();
const getBall = (x, y, dx, dy, r, color) => ({x, y, dx, dy, r, color});
const drawBall = (ball, ctx) => {
ctx.beginPath();
ctx.arc(ball.x, ball.y, ball.r, 0, Math.PI * 2, false);
ctx.fillStyle = ball.collider ? "red" : ball.color;
ctx.fill();
ctx.closePath();
}
const updatePos = (ball, containerR) => {
ball.x += ball.dx;
ball.y += ball.dy;
const dx = ball.x - containerR;
const dy = ball.y - containerR;
if (Math.sqrt(dx * dx + dy * dy) >= containerR - ball.r) {
const v = Math.sqrt(ball.dx * ball.dx + ball.dy * ball.dy);
const angleToCollisionPoint = Math.atan2(-dy, dx);
const oldAngle = Math.atan2(-ball.dy, ball.dx);
const newAngle = 2 * angleToCollisionPoint - oldAngle;
ball.dx = -v * Math.cos(newAngle);
ball.dy = v * Math.sin(newAngle);
}
}
function makeArea(domid, radius, ballsNumber) {
const ctx = document.getElementById(domid).getContext("2d");
const containerR = radius;
const size = radius * 2
ctx.canvas.width = ctx.canvas.height = size;
ctx.globalAlpha = 1;
let balls = [];
for(var i=0 ; i<ballsNumber ; ++i) {
const r = Math.random()*radius*0.5;
const t = Math.random()*Math.PI*2;
balls.push(getBall(radius + Math.cos(t)*r, radius + Math.sin(t)*r, 0.1, 0.1, 5, "Green"));
}
return {
ctx: ctx,
radius: radius,
balls: balls
}
}
const collides = (a, b) => (Math.hypot(Math.abs(a.x - b.x), Math.abs(a.y - b.y)) < (a.r + b.r));
const areas = [
makeArea("Canvas", 150, 10, true),
makeArea("Canvas1", 80, 4, false),
makeArea("Canvas2", 80, 4, false),
makeArea("Canvas3", 80, 4, false),
makeArea("Canvas4", 80, 4, false)
];
function engine() {
//console.clear(); // Clear console test messages
mydiv.textContent =" ";
areas.forEach((area) =>{
const ctx = area.ctx;
ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
area.balls.forEach((a, ai) => {
a.collider = undefined;
area.balls.forEach((b, bi) => {
if (bi === ai) return; // Don't look at self
if (collides(a, b)) a.collider = b; // Store the colliding B ball
});
if (a.collider) { // If ball has a collider:
//mydiv.textContent = ("Alert");
//beep();
prompt.show('ALERT!!!!! Not Maintaining Distance')
.waitForUser()
.then(function(name) {
output.innerHTML = '' + name;
})
.catch(function(e) {
console.log('Unknown error', e);
})
.finally(function() {
prompt.hide();
});
//console.log(`${a.color[0]} → ← ${a.collider.color[0]}`);
}
updatePos(a, area.radius);
drawBall(a, ctx);
});
});
requestAnimationFrame(engine);
}
engine();
canvas {
background: #eee;
margin: 0 auto;
border-radius: 50%;
box-shadow: 0 0 0 4px #000;
}
.row {
display: flex;
}
.Row {
display: flex;
flex-direction: row;
margin-left: 40%;
margin-top: 8%;
float: right;
}
#Canvas1, #Canvas2, #Canvas3, #Canvas4 {
background: #eee;
border-radius: 50%;
border: solid 0px #000;
margin: 2px;
}
<div class="Row">
<div>
<canvas id="Canvas"></canvas>
</div>
<div>
<div class="row">
<canvas id="Canvas1"></canvas>
<span> xyz</span>
<canvas id="Canvas2"></canvas>
<span> xyz1</span>
</div>
<div class="row">
<canvas id="Canvas3"></canvas>
<span> xyz2</span>
<canvas id="Canvas4"></canvas>
<span>xyz3</span>
</div>
</div>
</div>
<div id="mydiv"></div>
<div id="dialog" class="hidden">
<div class="message"></div>
<div>
<button class="ok">OK</button>
</div>
</div>
Regarding your second question:
The <span>s are just children of .row, like the canvas is. You could "group" them with the canvas and make their position absolute:
/* important stuff: */
.group {
position: relative;
}
.group span {
position: absolute;
left: 0;
right: 0;
bottom: 5px;
text-align: center;
}
/* only for testing: */
#canvas1 {
background: #eee;
width: 100%;
height: 100%
}
.row {
width: 200px;
height: 200px;
display: flex;
}
<div class="row">
<div class="group">
<canvas id="canvas1"></canvas>
<span>xyz</span>
</div>
</div>
About the alert from the big circle:
If you're extending your forEach on all areas with a variable for the index ...
areas.forEach((area, areaindex) => {
... you could check for index zero later:
if (a.collider && areaindex == 0)
Related
I am trying to place a big circle in the center of the screen and four other circles on the right side. How can I achieve this? Also, there should be balls bouncing inside the small circles on the right, and only one ball is inside each of them instead of several. An alert should be triggered by the big main circle. From the small circles, there should be no alert. How can I solve this problem? I am thankful for any help. Thanks in advance.
var noop = function() {
return this;
};
function UserCanceledError() {
this.name = 'UserCanceledError';
this.message = 'User canceled dialog';
}
UserCanceledError.prototype = Object.create(Error.prototype);
function Dialog() {
this.setCallbacks(noop, noop);
}
Dialog.prototype.setCallbacks = function(okCallback, cancelCallback) {
this._okCallback = okCallback;
return this;
};
Dialog.prototype.waitForUser = function() {
var _this = this;
return new Promise(function(resolve, reject) {
_this.setCallbacks(resolve, reject);
});
};
Dialog.prototype.show = noop;
Dialog.prototype.hide = noop;
function PromptDialog() {
Dialog.call(this);
this.el = document.getElementById('dialog');
this.messageEl = this.el.querySelector('.message');
this.okButton = this.el.querySelector('button.ok');
this.attachDomEvents();
}
PromptDialog.prototype = Object.create(Dialog.prototype);
PromptDialog.prototype.attachDomEvents = function() {
var _this = this;
this.okButton.addEventListener('click', function() {
_this.hide();
console.log('Ok clicked!!');
});
};
PromptDialog.prototype.show = function(message) {
this.messageEl.innerHTML = '' + message;
this.el.className = '';
return this;
};
PromptDialog.prototype.hide = function() {
this.el.className = 'hidden';
return this;
};
const ctx = document.getElementById("Canvas").getContext("2d");
const containerR = 150;
const size = containerR * 2
ctx.canvas.width = ctx.canvas.height = size;
ctx.globalAlpha = 0.8;
//Adding fourcircles to the right
const ctx1 = document.getElementById("Canvas1").getContext("2d");
const ctx2 = document.getElementById("Canvas2").getContext("2d");
const ctx3 = document.getElementById("Canvas3").getContext("2d");
const ctx4 = document.getElementById("Canvas4").getContext("2d");
const containerR2 = 80;
const size2 = containerR2 * 2
ctx1.canvas.width = ctx1.canvas.height = size2;
ctx2.canvas.width = ctx2.canvas.height = size2;
ctx3.canvas.width = ctx3.canvas.height = size2;
ctx4.canvas.width = ctx4.canvas.height = size2;
ctx1.globalAlpha = 0.8;
ctx2.globalAlpha = 0.8;
ctx3.globalAlpha = 0.8;
ctx4.globalAlpha = 0.8;
var prompt = new PromptDialog();
const getBall = (x, y, dx, dy, r, color) => ({x, y, dx, dy, r, color});
const balls = [
getBall(size / 2, size - 30, 0.1, 0.1, 8, "Green"),
getBall(size / 3, size - 50, 0.1, 0.1, 8, "Green"),
getBall(size / 4, size - 60, 0.1, 0.1, 8, "Green"),
getBall(size / 2, size / 5, 0.1, 0.1, 8, "Green"),
];
const drawBall = (ball) => {
ctx.beginPath();
ctx.arc(ball.x, ball.y, ball.r, 0, Math.PI * 2, false);
ctx.fillStyle = ball.collider ? "red" : ball.color;
ctx.fill();
ctx.closePath();
ctx1.beginPath();
ctx1.arc(ball.x, ball.y, ball.r, 0, Math.PI * 2, false);
ctx1.fillStyle = ball.collider ? "red" : ball.color;
ctx1.fill();
ctx1.closePath();
ctx2.beginPath();
ctx2.arc(ball.x, ball.y, ball.r, 0, Math.PI * 2, false);
ctx2.fillStyle = ball.collider ? "red" : ball.color;
ctx2.fill();
ctx2.closePath();
ctx3.beginPath();
ctx3.arc(ball.x, ball.y, ball.r, 0, Math.PI * 2, false);
ctx3.fillStyle = ball.collider ? "red" : ball.color;
ctx3.fill();
ctx3.closePath();
ctx4.beginPath();
ctx4.arc(ball.x, ball.y, ball.r, 0, Math.PI * 2, false);
ctx4.fillStyle = ball.collider ? "red" : ball.color;
ctx4.fill();
ctx4.closePath();
}
const updatePos = (ball) => {
ball.x += ball.dx;
ball.y += ball.dy;
const dx = ball.x - containerR;
const dy = ball.y - containerR;
if (Math.sqrt(dx * dx + dy * dy) >= containerR - ball.r) {
const v = Math.sqrt(ball.dx * ball.dx + ball.dy * ball.dy);
const angleToCollisionPoint = Math.atan2(-dy, dx);
const oldAngle = Math.atan2(-ball.dy, ball.dx);
const newAngle = 2 * angleToCollisionPoint - oldAngle;
ball.dx = -v * Math.cos(newAngle);
ball.dy = v * Math.sin(newAngle);
}
}
const collides = (a, b) => (Math.hypot(Math.abs(a.x - b.x), Math.abs(a.y - b.y)) < (a.r + b.r));
function engine() {
//console.clear(); // Clear console test messages
mydiv.textContent =" ";
ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
ctx1.clearRect(0, 0, ctx1.canvas.width, ctx1.canvas.height);
ctx2.clearRect(0, 0, ctx2.canvas.width, ctx2.canvas.height);
ctx3.clearRect(0, 0, ctx3.canvas.width, ctx3.canvas.height);
ctx4.clearRect(0, 0, ctx4.canvas.width, ctx4.canvas.height);
balls.forEach((a, ai) => {
a.collider = undefined;
balls.forEach((b, bi) => {
if (bi === ai) return; // Don't look at self
if (collides(a, b)) a.collider = b; // Store the colliding B ball
});
if (a.collider) { // If ball has a collider:
//mydiv.textContent = ("Alert");
beep();
prompt.show('ALERT!!!!! Not Maintaining Distance')
.waitForUser()
.then(function(name) {
output.innerHTML = '' + name;
})
.catch(function(e) {
console.log('Unknown error', e);
})
.finally(function() {
prompt.hide();
});
//console.log(`${a.color[0]} → ← ${a.collider.color[0]}`);
}
updatePos(a);
drawBall(a);
});
requestAnimationFrame(engine);
}
engine();
canvas {
background: #eee;
margin: 0 auto;
border-radius: 50%;
box-shadow: 0 0 0 4px #000;
}
.row {
display: flex;
}
.container1 {
display: flex;
flex-direction: column;
margin-left: 70%;
margin-top: 8%;
float: right;
}
#Canvas1, #Canvas2, #Canvas3, #Canvas4 {
background: #eee;
border-radius: 50%;
border: solid 1px #000;
margin: 4px;
}
<div class="column">
<canvas id="Canvas"></canvas>
</div>
<div class="container1">
<div class="row">
<canvas id="Canvas1"></canvas>
<div><p>abc</p></div>
<canvas id="Canvas2"></canvas>
<div><p>def</p></div>
</div>
<div class="row">
<canvas id="Canvas3"></canvas>
<div><p>hij</p></div>
<canvas id="Canvas4"></canvas>
<div><p>klm</p></div>
</div>
</div>
<div id="mydiv"></div>
<div id="y"></div>
<div id="dx"></div>
<div id="dy"></div>
<div id="dialog" class="hidden">
<div class="message"></div>
<div>
<button class="ok">OK</button>
</div>
</div>
There are a lot of errors in the provided code:
beep() fonction is not defined, it prevents the alert system to work.
there is only one list of the same 4 balls for the 5 canvas, so you see the same 4 balls in all canvas.
updatePos uses containerR that is a global variable (radius of the big circle), calculations can only be done for the big circle.
drawBall draws the same single ball in the 5 contexts
Fixed code, with random initial positions for balls :
function PromptDialog(dialog) {
this.el = document.getElementById(dialog);
this.messageEl = this.el.querySelector('.message');
this.okButton = this.el.querySelector('button.ok');
this.attachDomEvents();
}
PromptDialog.prototype.attachDomEvents = function() {
this.okButton.addEventListener('click', () => {
this.hide();
//console.log('Ok clicked!!');
});
};
PromptDialog.prototype.show = function(message) {
this.messageEl.innerHTML = '' + message;
this.el.className = '';
};
PromptDialog.prototype.hide = function() {
this.el.className = 'hidden';
};
var prompt = new PromptDialog('dialog');
const getBall = (x, y, dx, dy, r, color) => ({x, y, dx, dy, r, color});
const drawBall = (ball, ctx) => {
ctx.beginPath();
ctx.arc(ball.x, ball.y, ball.r, 0, Math.PI * 2, false);
ctx.fillStyle = ball.collider ? "red" : ball.color;
ctx.fill();
ctx.closePath();
}
const updatePos = (ball, containerR) => {
ball.x += ball.dx;
ball.y += ball.dy;
const dx = ball.x - containerR;
const dy = ball.y - containerR;
if (Math.sqrt(dx * dx + dy * dy) >= containerR - ball.r) {
const v = Math.sqrt(ball.dx * ball.dx + ball.dy * ball.dy);
const angleToCollisionPoint = Math.atan2(-dy, dx);
const oldAngle = Math.atan2(-ball.dy, ball.dx);
const newAngle = 2 * angleToCollisionPoint - oldAngle;
ball.dx = -v * Math.cos(newAngle);
ball.dy = v * Math.sin(newAngle);
}
}
function makeArea(domid, radius, ballsNumber, alerts) {
const ctx = document.getElementById(domid).getContext("2d");
const containerR = radius;
const size = radius * 2
ctx.canvas.width = ctx.canvas.height = size;
ctx.globalAlpha = 0.8;
const balls = [];
const speed = 0.1;
for(var i=0 ; i<ballsNumber ; ++i) {
const r = Math.random()*radius*0.5;
const t = Math.random()*Math.PI*2;
const t2 = Math.random()*Math.PI*2;
balls.push(
getBall(
radius + Math.cos(t)*r,
radius + Math.sin(t)*r,
Math.cos(t2)*speed,
Math.sin(t2)*speed,
8,
"Green")
);
}
return {
ctx: ctx,
radius: radius,
balls: balls,
alerts:alerts
}
}
const collides = (a, b) => (Math.hypot(Math.abs(a.x - b.x), Math.abs(a.y - b.y)) < (a.r + b.r));
const areas = [
makeArea("Canvas", 150, 4, true),
makeArea("Canvas1", 80, 4, false),
makeArea("Canvas2", 80, 4, false),
makeArea("Canvas3", 80, 4, false),
makeArea("Canvas4", 80, 4, false)
];
function engine() {
//console.clear(); // Clear console test messages
areas.forEach((area) =>{
const ctx = area.ctx;
ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
area.balls.forEach((a, ai) => {
a.collider = undefined;
area.balls.forEach((b, bi) => {
if (bi === ai) return; // Don't look at self
if (collides(a, b)) a.collider = b; // Store the colliding B ball
});
if (a.collider && area.alerts) { // If ball has a collider:
//beep();
prompt.show('ALERT!!!!! Not Maintaining Distance');
//console.log(`${a.color[0]} → ← ${a.collider.color[0]}`);
}
updatePos(a, area.radius);
drawBall(a, ctx);
});
});
requestAnimationFrame(engine);
}
engine();
canvas {
background: #eee;
margin: 0 auto;
border-radius: 50%;
box-shadow: 0 0 0 4px #000;
}
.row {
display: flex;
}
.hidden {
display:none;
}
#Canvas1, #Canvas2, #Canvas3, #Canvas4 {
background: #eee;
border-radius: 50%;
border: solid 1px #000;
margin: 4px;
}
<div class="row">
<div>
<canvas id="Canvas"></canvas>
</div>
<div>
<div class="row">
<canvas id="Canvas1"></canvas>
<div><p>abc</p></div>
<canvas id="Canvas2"></canvas>
<div><p>def</p></div>
</div>
<div class="row">
<canvas id="Canvas3"></canvas>
<div><p>hij</p></div>
<canvas id="Canvas4"></canvas>
<div><p>klm</p></div>
</div>
</div>
</div>
<div id="dialog" class="hidden">
<div class="message"></div>
<div>
<button class="ok">OK</button>
</div>
</div>
I have written a code for a game based on a html canvas. When I run it, I do not get the canvas game loaded onto the canvas. Instead I get the below error in my console:-
Uncaught TypeError: Cannot read property 'start' of undefined
I have given my code below. Can someone please explain me what might be the reason?
<script>
var context;
var canvas;
var ctx;
var speed = urlParam('speed');
if (speed == null)
speed = 40
$('#speed').val(speed);
calculateBubble(parseInt(speed));
var redSBLatter;
var redSBFormer;
var redSBWindowFormer;
var redSBWindowLatter;
var blueSB;
var blueSWindow;
function startGame(bubbleLength, windowLength) {
redSBWindowFormer = new slidingWindow(60, windowLength * 2, "black", 5, 120);
redSBWindowLatter = new slidingWindow(60, 40, "black", 5, 80);
redSBFormer = new component(30, bubbleLength, "red", 20, 120);
redSBLatter = new component(30, 30, "red", 20, 90);
blueSWindow = new slidingWindow(60, 70, "black", 120, 10);
blueSB = new component(20, 40, "blue", 140, 20);
myGameArea.start();
}
var myGameArea = {
start: function () {
canvas = document.getElementById("canvas");
context = canvas.getContext("2d");
//myCanvas.width = "480";
//myCanvas.height = "480";
document.body.insertBefore(canvas, document.body.childNodes[0]);
interval = setInterval(updateGameArea, 20);
},
clear: function () {
context.clearRect(0, 0, canvas.width, canvas.height);
}
}
function urlParam(name) {
var results = new RegExp('[\?&]' + name + '=([^&#]*)').exec(window.location.href);
if (results == null) {
return null;
}
else {
return decodeURI(results[1]) || 0;
}
}
function component(width, height, color, x, y) {
this.width = width;
this.height = height;
this.speedX = 0;
this.speedY = 0;
this.x = x;
this.y = y;
this.update = function () {
ctx = myGameArea.context;
ctx.fillStyle = color;
ctx.fillRect(this.x, this.y, this.width, this.height);
}
this.newPos = function () {
this.x += this.speedX;
this.y += this.speedY;
}
}
function slidingWindow(width, height, color, x, y) {
this.width = width;
this.height = height;
this.speedX = 0;
this.speedY = 0;
this.x = x;
this.y = y;
this.update = function () {
ctx = myGameArea.context;
ctx.beginPath();
//ctx.globalAlpha = 0.2;
ctx.lineWidth = "3";
ctx.strokeStyle = color;
ctx.rect(this.x, this.y, this.width, this.height);
ctx.stroke();
}
this.newPos = function () {
this.x += this.speedX;
this.y += this.speedY;
}
}
function updateGameArea() {
myGameArea.clear();
redSBLatter.newPos();
redSBLatter.update();
redSBFormer.newPos();
redSBFormer.update();
redSBWindowLatter.newPos();
redSBWindowLatter.update();
redSBWindowFormer.newPos();
redSBWindowFormer.update();
blueSB.newPos();
blueSB.update();
blueSWindow.newPos();
blueSWindow.update();
}
function redmoveup() {
redSBLatter.speedY = -1;
redSBFormer.speedY = -1;
redSBWindowLatter.speedY = -1;
redSBWindowFormer.speedY = -1;
}
function bluemoveup() {
blueSB.speedY = -1;
blueSWindow.speedY = -1;
}
function redmovedown() {
redSBLatter.speedY = 1;
redSBFormer.speedY = 1;
redSBWindowLatter.speedY = 1;
redSBWindowFormer.speedY = 1;
}
function bluemovedown() {
blueSB.speedY = 1;
blueSWindow.speedY = 1;
}
function redmoveleft() {
redSBLatter.speedX = -1;
redSBFormer.speedX = -1;
redSBWindowLatter.speedX = -1;
redSBWindowFormer.speedX = -1;
}
function bluemoveleft() {
blueSB.speedX = -1;
blueSWindow.speedX = -1;
}
function redmoveright() {
redSBLatter.speedX = 1;
redSBFormer.speedX = 1;
redSBWindowLatter.speedX = 1;
redSBWindowFormer.speedX = 1;
}
function bluemoveright() {
blueSB.speedX = 1;
blueSWindow.speedX = 1;
}
function clearmove() {
redSBLatter.speedX = 0;
redSBLatter.speedY = 0;
redSBFormer.speedX = 0;
redSBFormer.speedY = 0;
redSBWindowLatter.speedX = 0;
redSBWindowLatter.speedY = 0;
redSBWindowFormer.speedX = 0;
redSBWindowFormer.speedY = 0;
blueSB.speedX = 0;
blueSB.speedY = 0;
blueSWindow.speedX = 0;
blueSWindow.speedY = 0;
}
/** function calculateBubble() {
var kmh = document.getElementById("speed").value;
if (kmh <= 0) {
var bubble = 5.84;
var window = bubble * 5;
document.getElementById("bubble").innerHTML = bubble;
document.getElementById("window").innerHTML = window;
return startGame(20, 20);
}
else {
//var v = getMph(kmh);
var v = kmh / 1.6093;
var feet = 2.2 * v + ((v * v) / 20);
var bubblemeters = feet / 3.28;
var bubble = parseFloat(bubblemeters.toFixed(2));
document.getElementById("bubble").innerHTML = bubble;
calculateWindow(bubble);
return bubblemeters;
}
}**/
function calculateBubble(kmh) {
var v = kmh / 1.6093;
var feet = 2.2 * v + ((v * v) / 20)
var meters = feet / 3.28;
$('#sBubble').empty();
$('#sBubble').append("Safety bubble : " + meters.toFixed(2) + " m");
calculateWindow(meters);
}
function calculateWindow(bubble) {
var windowMeters = bubble + 5;
var window = parseFloat(windowMeters.toFixed());
document.getElementById("window").innerHTML = window;
startGame(bubble, window);
}
</script>
<style type="text/css">
#canvas {
border: 1px solid #d3d3d3;
background-color: #f1f1f1;
}
.grid-container {
display: grid;
grid-template-columns: auto auto auto;
background-color: #2196F3;
padding: 10px;
}
.grid-item {
background-color: rgba(255, 255, 255, 0.8);
border: 1px solid rgba(0, 0, 0, 0.8);
padding: 20px;
font-size: 30px;
text-align: center;
}
</style>
<!DOCTYPE html>
<html>
<head>
<title>Staging Area Simulation</title>
<meta charset="UTF-8">
<script src="public_html/jquery.js"></script>
</head>
<!--<body onload="startGame()">-->
<body>
<div class="grid-container">
<div>
<canvas id="canvas" width="480" height="480">
</canvas>
</div>
<div>
<h3>Enter Parameters</h3>
<p id="sBubble">Safety bubble : 0.0 m</p>
Sliding Window :<p id="window"></p>
<form method="get" id="form">
speed : <input type="text" id="speed" name="speed" /> <br /><br />
Vehicle Length : <input type="text" id="vLength" name="vLength" value="3.84m" disabled />
<br /><br />
Vehicle Width : <input type="text" id="vWidth" name="vWidth" value="1.74m" disabled />
<br /><br />
<button name="data" type="submit">Calculate</button>
</form>
</div>
<div style="text-align:center;width:480px;">
<h3>
Red Controllers </h3>
<button onmousedown="redmoveup()" onmouseup="clearmove()">UP</button><br><br>
<button onmousedown="redmoveleft()" onmouseup="clearmove()">LEFT</button>
<button onmousedown="redmoveright()" onmouseup="clearmove()">RIGHT</button><br><br>
<button onmousedown="redmovedown()" onmouseup="clearmove()">DOWN</button>
</div>
<div style="text-align:center;width:480px;">
<h3> Blue Controllers</h3>
<button onmousedown="bluemoveup()" onmouseup="clearmove()">UP</button><br><br>
<button onmousedown="bluemoveleft()" onmouseup="clearmove()">LEFT</button>
<button onmousedown="bluemoveright()" onmouseup="clearmove()">RIGHT</button><br><br>
<button onmousedown="bluemovedown()" onmouseup="clearmove()">DOWN</button>
</div>
</div>
</body>
</html>
i have a html script with button and onclick function script that should take me to google.com, but it doesn't seem to work. Been stuck with this for hours. Im also new to HTML.
Tried everything. Line 336 and 353 should be the needed content. And line 136 should be the button itself. I don't understand whats wrong. Anyone ever have had this issue?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link rel="shortcut icon" type="image/x-icon/text/javascript" href="https://static.codepen.io/assets/favicon/favicon-aec34940fbc1a6e787974dcd360f2c6b63348d4b1f4e06c77743096d55480f33.ico" />
<link rel="mask-icon" type="" href="https://static.codepen.io/assets/favicon/logo-pin-8f3771b1072e3c38bd662872f6b673a722f4b3ca2421637d5596661b4e2132cc.svg" color="#111" />
<title>SpyBanter - SpyBanter's Official WebSite</title>
<style type="text/css">
body {
overflow: hidden;
margin: 0;
}
body:before {
content: '';
background: #c4252a url(http://subtlepatterns2015.subtlepatterns.netdna-cdn.com/patterns/cheap_diagonal_fabric.png);
background-blend-mode: multiply;
mix-blend-mode: multiply;
position: absolute;
left: 0;
top: 0;
width: 100%;
height: 100%;
z-index: 10;
}
canvas {
opacity: 0;
transition: 1s opacity cubic-bezier(0.55, 0, 0.1, 1);
}
canvas.ready {
opacity: 0.4;
}
.intro {
position: absolute;
padding: 20px;
-webkit-transform: translate(-50%, -50%);
transform: translate(-50%, -50%);
left: 50%;
top: 50%;
text-align: center;
color: #fafafa;
z-index: 10;
width: 100%;
max-width: 700px;
font-family: "HelveticaNeue-Light", "Helvetica Neue Light", "Helvetica Neue", Helvetica, Arial, "Lucida Grande", sans-serif;
text-shadow: 0px 5px 20px black;
}
.intro h1 {
font-size: 40px;
font-weight: 300;
letter-spacing: 2px;
}
.intro p {
letter-spacing: 1px;
line-height: 24px;
}
#btnclose {
background-color: indianred;
border-color: darkred;
}
}
#btnnup:hover, #btnsisu:hover, #btncmd:hover {
background-color: #3e8e41;
}
#btnnup:active, #btnsisu:active, #btncmd:active {
background-color: #3e8e41;
box-shadow: 0 5px #666;
transform: translateY(4px);
}
#btnsisu {
left: 108px;
top: 105px;
}
#btncmd {
left: -311px;
top: -88px;
}
#content {
width: 100%;
height: auto;
min-height: 580px;
}
</style>
<script>
window.console = window.console || function(t) {};
</script>
<script>
if (document.location.search.match(/type=embed/gi)) {
window.parent.postMessage("resize", "*");
}
</script>
</head>
<body translate="no">
<canvas id="canvas" data-image="http://unsplash.it/g/450/200/?random=1"></canvas>
<div class="intro">
<h1>Interactive mosaic background</h1>
<p>Had to do this effect in a recent project and wanted to share it with you :). To change the background, edit the data-image on the canvas tag. You can also change the magnet effect intensity by changing the magnet variable</p>
<button id="btncmd">Videos</button>
</div>
<script src="https://static.codepen.io/assets/common/stopExecutionOnTimeout-de7e2ef6bfefd24b79a3f68b414b87b8db5b08439cac3f1012092b2290c719cd.js"></script>
<script type="application/javascript">
(function () {
// Variables
var Photo, addListeners, canvas, createGrid, ctx, gridItem, grids, height, img, imgInfo, imgSrc, imgs, init, magnet, mouse, populateCanvas, render, resizeCanvas, rotateAndPaintImage, updateMouse, useGrid, width;
canvas = document.getElementById('canvas');
ctx = canvas.getContext('2d');
width = canvas.width = window.innerWidth;
height = canvas.height = window.innerHeight;
imgSrc = canvas.dataset.image;
img = new Image();
useGrid = true;
imgInfo = {};
imgs = [];
grids = [];
magnet = 2000;
mouse = {
x: 1,
y: 0 };
init = function () {
addListeners();
img.onload = function (e) {
var numberToShow;
// Check for firefox.
imgInfo.width = e.path ? e.path[0].width : e.target.width;
imgInfo.height = e.path ? e.path[0].height : e.target.height;
numberToShow = Math.ceil(window.innerWidth / imgInfo.width) * Math.ceil(window.innerHeight / imgInfo.height);
if (useGrid) {
createGrid();
}
populateCanvas(numberToShow * 4);
canvas.classList.add('ready');
return render();
};
return img.src = imgSrc;
};
addListeners = function () {
window.addEventListener('resize', resizeCanvas);
window.addEventListener('mousemove', updateMouse);
return window.addEventListener('touchmove', updateMouse);
};
updateMouse = function (e) {
mouse.x = e.clientX;
return mouse.y = e.clientY;
};
resizeCanvas = function () {
width = canvas.width = window.innerWidth;
return height = canvas.height = window.innerHeight;
};
populateCanvas = function (nb) {
var i, p, results;
i = 0;
results = [];
while (i <= nb) {
p = new Photo();
imgs.push(p);
results.push(i++);
}
return results;
};
createGrid = function () {
var c, grid, i, imgScale, item, j, k, l, r, ref, ref1, ref2, results, x, y;
imgScale = 0.5;
grid = {
row: Math.ceil(window.innerWidth / (imgInfo.width * imgScale)),
cols: Math.ceil(window.innerHeight / (imgInfo.height * imgScale)),
rowWidth: imgInfo.width * imgScale,
colHeight: imgInfo.height * imgScale };
for (r = j = 0, ref = grid.row; 0 <= ref ? j < ref : j > ref; r = 0 <= ref ? ++j : --j) {
x = r * grid.rowWidth;
for (c = k = 0, ref1 = grid.cols; 0 <= ref1 ? k < ref1 : k > ref1; c = 0 <= ref1 ? ++k : --k) {
y = c * grid.colHeight;
item = new gridItem(x, y, grid.rowWidth, grid.colHeight);
grids.push(item);
}
}
results = [];
for (i = l = 0, ref2 = grids.length; 0 <= ref2 ? l < ref2 : l > ref2; i = 0 <= ref2 ? ++l : --l) {
results.push(grids[i].draw());
}
return results;
};
gridItem = function (x = 0, y = 0, w, h) {
this.draw = function () {
ctx.drawImage(img, x, y, w, h);
};
};
Photo = function () {
var TO_RADIANS, finalX, finalY, forceX, forceY, h, r, seed, w, x, y;
seed = Math.random() * (2.5 - 0.7) + 0.7;
w = imgInfo.width / seed;
h = imgInfo.height / seed;
x = window.innerWidth * Math.random();
finalX = x;
y = window.innerHeight * Math.random();
finalY = y;
console.log(`INIT Y :: ${finalY} || INIT X :: ${finalX}`);
r = Math.random() * (180 - -180) + -180;
forceX = 0;
forceY = 0;
TO_RADIANS = Math.PI / 180;
this.update = function () {
var distance, dx, dy, powerX, powerY, x0, x1, y0, y1;
x0 = x;
y0 = y;
x1 = mouse.x;
y1 = mouse.y;
dx = x1 - x0;
dy = y1 - y0;
distance = Math.sqrt(dx * dx + dy * dy);
powerX = x0 - dx / distance * magnet / distance;
powerY = y0 - dy / distance * magnet / distance;
forceX = (forceX + (finalX - x0) / 2) / 2.1;
forceY = (forceY + (finalY - y0) / 2) / 2.2;
x = powerX + forceX;
y = powerY + forceY;
};
this.draw = function () {
return rotateAndPaintImage(ctx, img, r * TO_RADIANS, x, y, w / 2, h / 2, w, h);
};
};
rotateAndPaintImage = function (context, image, angle, positionX, positionY, axisX, axisY, widthX, widthY) {
context.translate(positionX, positionY);
context.rotate(angle);
context.drawImage(image, -axisX, -axisY, widthX, widthY);
context.rotate(-angle);
return context.translate(-positionX, -positionY);
};
render = function () {
var x, y;
x = 0;
y = 0;
ctx.clearRect(0, 0, width, height);
while (y < grids.length) {
grids[y].draw();
y++;
}
while (x < imgs.length) {
imgs[x].update();
imgs[x].draw();
x++;
}
return requestAnimationFrame(render);
};
init();
}).call(this);
cmd = function () {
window.location.href = "https://www.google.com/";
}
function cmd() {
window.location.href = "https://www.google.com/";
}
btnclose.onclick = cmd;
btnnup.onclick = cmd;
btncmd.onclick = cmd;
//# sourceURL=coffeescript
//# sourceURL=pen.js
</script>
<script type="application/javascript">
window.onload = function() {
main.style.opacity = "1";
}
function show(){
main.style.opacity = "1";
}
function close() {
main.style.opacity = "0";
$.post('http://tt_help/close', JSON.stringify({
}));
}
function cmd() {
window.location.href = "https://www.google.com/";
}
function sisukord() {
let id = $(this).attr('content');
console.log(id)
let docs = `https://docs.google.com/document/d/e/2PACX-1vSXxzowHucTNRBwduXT-pDoGQT4blGJhOvgnzIYmpEe2DwU4mimf84RZ8orvUGpm2vPsPDdkkVAnFkq/pub?embedded=true${id}`;
$('#main iframe').attr('src', docs);
}
window.addEventListener('message', function(event) {
if (event.data.type == "open") {
main.style.opacity = "1";
}
});
btnclose.onclick = cmd;
btncmd.onclick = cmd;
btnsisu.onclick = cmd;
</script>
</body>
If you're trying to make a button that takes you to google.com, I would advise you to use an a tag, not a button tag. The tag automatically links you to your desired destination when clicked.
Example:
Example
If you want the link to look like a button, then simply look at the css options. I would advise you to look here: https://www.w3schools.com/css/css_link.asp
a {
background-image:linear-gradient(to bottom, lightblue, aquamarine);
padding:5px;
text-decoration:none;
color:black;
padding-right:50px;
padding-left:50px;
margin-top: 50px;
margin-left: 50px;
display: inline-block;
font-size:25px;
border-radius:5px;
box-shadow: 1px 1px green;
}
Example
If you are determined to use a <button> tag, then all you need to do is within that button tag add an onclick attribute. So, you would change your code to <button id="btncmd" onclick="cmd()">Videos</button>.
Example of what you want:
function cmd() {
window.location.href = "https://www.example.com/"; // I'm using example but you can use google.
}
<button id="btncmd" onclick="cmd()">Videos</button>
You did not define btncmd. Adding this line to your code solves the problem:
var btncmd = document.getElementById("btncmd");
I have a small problem and I can't get it to fix.
I developed a element that is following the cursor and way it needs to function is that the border around the cursor needs to stick with the position of the cursor. But the problem I've got right now is that it won't stick when scrolling down.
You can check at the demo below what I mean.
The problem seems that it is not correctly checking the height of the page, thats why its not correctly positioning. Am I right?
const windowW = window.innerWidth;
const windowH = window.innerHeight;
const maxLength = Math.max(windowW, windowH);
const cursorWidth = 100;
const cursorR = cursorWidth >> 1;
const cursorDelay = 10;
const buttons = Array.from(document.querySelectorAll('.border-button'));
const cursor = {
el: document.querySelector('.border-cursor'),
x: windowW >> 1,
y: windowH >> 1,
scaleX: 1,
scaleY: 1,
};
const target = {
x: windowW >> 1,
y: windowH >> 1,
width: cursorWidth,
followMouse: true,
};
const norm = (val, max, min) => (val - min) / (max - min);
const toDegrees = r => r * (180 / Math.PI);
const distanceBetween = (v1, v2) => Math.sqrt((v1.x - v2.x) * (v1.x - v2.x) + (v1.y - v2.y) * (v1.y +- v2.y));
const loop = () => {
const destX = target.x - cursorR;
const destY = target.y - cursorR;
const newX = cursor.x + ((destX - cursor.x) / cursorDelay);
const newY = cursor.y + ((destY - cursor.y) / cursorDelay);
const angle = angleBetween(cursor.x, cursor.y, newX, newY);
if (target.followMouse) {
const distance = Math.abs(distanceBetween(target, cursor));
const scale = norm(distance, maxLength, cursorR);
cursor.scaleX = 1 + scale;
cursor.scaleY = 1 - scale;
} else {
const targetScale = target.width / cursorWidth;
cursor.scaleX += (targetScale - cursor.scaleX) / (cursorDelay / 2);
cursor.scaleY = cursor.scaleX;
}
cursor.x = newX;
cursor.y = newY;
cursor.el.style.transform = `translate(${cursor.x}px, ${cursor.y}px) rotate(${toDegrees(angle)}deg) scale(${cursor.scaleX}, ${cursor.scaleY})`;
requestAnimationFrame(loop);
};
const angleBetween = (x1, y1, x2, y2) => Math.atan2(y2 - y1, x2 - x1);
const onPointerMove = (e) => {
if (!target.followMouse) {
return;
}
const pointer = (e.touches && e.touches.length) ? e.touches[0] : e;
const { clientX: x, clientY: y } = pointer;
target.x = x;
target.y = y;
};
const onPointerOver = (e) => {
const btn = e.target;
const rect = btn.getBoundingClientRect();
target.followMouse = false;
target.x = rect.left + (rect.width >> 1);
target.y = rect.top + (rect.height >> 1);
target.width = Math.max(rect.width, rect.height) + 50;
};
const onPointerOut = () => {
target.followMouse = true;
target.width = cursorWidth;
};
document.body.addEventListener('mousemove', onPointerMove);
document.body.addEventListener('touchmove', onPointerMove);
buttons.forEach((btn) => {
btn.addEventListener('touchstart', onPointerOver);
btn.addEventListener('mouseover', onPointerOver);
btn.addEventListener('touchend', onPointerOut);
btn.addEventListener('mouseout', onPointerOut);
});
loop();
const windowW = window.innerWidth;
const windowH = window.innerHeight;
const maxLength = Math.max(windowW, windowH);
const cursorWidth = 100;
const cursorR = cursorWidth >> 1;
const cursorDelay = 10;
const buttons = Array.from(document.querySelectorAll('.border-button'));
const cursor = {
el: document.querySelector('.border-cursor'),
x: windowW >> 1,
y: windowH >> 1,
scaleX: 1,
scaleY: 1,
};
const target = {
x: windowW >> 1,
y: windowH >> 1,
width: cursorWidth,
followMouse: true,
};
const norm = (val, max, min) => (val - min) / (max - min);
const toDegrees = r => r * (180 / Math.PI);
const distanceBetween = (v1, v2) => Math.sqrt((v1.x - v2.x) * (v1.x - v2.x) + (v1.y - v2.y) * (v1.y +- v2.y));
const loop = () => {
const destX = target.x - cursorR;
const destY = target.y - cursorR;
const newX = cursor.x + ((destX - cursor.x) / cursorDelay);
const newY = cursor.y + ((destY - cursor.y) / cursorDelay);
const angle = angleBetween(cursor.x, cursor.y, newX, newY);
if (target.followMouse) {
const distance = Math.abs(distanceBetween(target, cursor));
const scale = norm(distance, maxLength, cursorR);
cursor.scaleX = 1 + scale;
cursor.scaleY = 1 - scale;
} else {
const targetScale = target.width / cursorWidth;
cursor.scaleX += (targetScale - cursor.scaleX) / (cursorDelay / 2);
cursor.scaleY = cursor.scaleX;
}
cursor.x = newX;
cursor.y = newY;
cursor.el.style.transform = `translate(${cursor.x}px, ${cursor.y}px) rotate(${toDegrees(angle)}deg) scale(${cursor.scaleX}, ${cursor.scaleY})`;
requestAnimationFrame(loop);
};
const angleBetween = (x1, y1, x2, y2) => Math.atan2(y2 - y1, x2 - x1);
const onPointerMove = (e) => {
if (!target.followMouse) {
return;
}
const pointer = (e.touches && e.touches.length) ? e.touches[0] : e;
const { clientX: x, clientY: y } = pointer;
target.x = x;
target.y = y;
};
const onPointerOver = (e) => {
const btn = e.target;
const rect = btn.getBoundingClientRect();
target.followMouse = false;
target.x = rect.left + (rect.width >> 1);
target.y = rect.top + (rect.height >> 1);
target.width = Math.max(rect.width, rect.height) + 50;
};
const onPointerOut = () => {
target.followMouse = true;
target.width = cursorWidth;
};
document.body.addEventListener('mousemove', onPointerMove);
document.body.addEventListener('touchmove', onPointerMove);
buttons.forEach((btn) => {
btn.addEventListener('touchstart', onPointerOver);
btn.addEventListener('mouseover', onPointerOver);
btn.addEventListener('touchend', onPointerOut);
btn.addEventListener('mouseout', onPointerOut);
});
loop();
html,
body {
margin: 0;
padding: 0;
}
.wrapper {
width: 100vw;
min-height: 1500px;
display: flex;
flex-direction: row;
align-items: center;
}
.container {
width: 100%;
display: flex;
padding: 0 1rem;
}
.cursor {
position: absolute;
z-index: 10;
width: 100px;
height: 100px;
border: 2px solid #23bfa0;
border-radius: 50%;
pointer-events: none;
}
.button {
padding: 1rem;
background-color: #23bfa0;
border: none;
box-shadow: 0 0 7px 0px rgba(0, 0, 0, 0.2);
color: white;
font-size: 1.2rem;
cursor: pointer;
transition: box-shadow 0.1s ease-in, transform 0.1s ease-in;
&--small {
padding: 0.75rem;
font-size: 0.75rem;
}
&:hover {
transform: translate(0%, -2px);
box-shadow: 0px 4px 9px 2px rgba(0, 0, 0, 0.2)
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<div class="cursor border-cursor"></div>
<div class="wrapper">
<div class="container">
<button class="button button--small border-button">small</button>
<button class="button border-button">hover me</button>
<button class="button border-button">hover me more</button>
</div>
</div>
</body>
In onPointerMove, try replacing:
const { clientX: x, clientY: y } = pointer;
with:
const { pageX: x, pageY: y } = pointer;
Here's a good post explaining the differences between these values:
https://stackoverflow.com/a/9335517/965834
Also, change:
target.x = rect.left + (rect.width >> 1);
target.y = rect.top + (rect.height >> 1);
into:
target.x = window.scrollX + rect.left + (rect.width >> 1);
target.y = window.scrollY + rect.top + (rect.height >> 1);
This takes into account scrolling when calculating the position of your buttons.
Demo:
const windowW = window.innerWidth;
const windowH = window.innerHeight;
const maxLength = Math.max(windowW, windowH);
const cursorWidth = 100;
const cursorR = cursorWidth >> 1;
const cursorDelay = 10;
const buttons = Array.from(document.querySelectorAll('.border-button'));
const cursor = {
el: document.querySelector('.border-cursor'),
x: windowW >> 1,
y: windowH >> 1,
scaleX: 1,
scaleY: 1,
};
const target = {
x: windowW >> 1,
y: windowH >> 1,
width: cursorWidth,
followMouse: true,
};
const norm = (val, max, min) => (val - min) / (max - min);
const toDegrees = r => r * (180 / Math.PI);
const distanceBetween = (v1, v2) => Math.sqrt((v1.x - v2.x) * (v1.x - v2.x) + (v1.y - v2.y) * (v1.y +- v2.y));
const loop = () => {
const destX = target.x - cursorR;
const destY = target.y - cursorR;
const newX = cursor.x + ((destX - cursor.x) / cursorDelay);
const newY = cursor.y + ((destY - cursor.y) / cursorDelay);
const angle = angleBetween(cursor.x, cursor.y, newX, newY);
if (target.followMouse) {
const distance = Math.abs(distanceBetween(target, cursor));
const scale = norm(distance, maxLength, cursorR);
cursor.scaleX = 1 + scale;
cursor.scaleY = 1 - scale;
} else {
const targetScale = target.width / cursorWidth;
cursor.scaleX += (targetScale - cursor.scaleX) / (cursorDelay / 2);
cursor.scaleY = cursor.scaleX;
}
cursor.x = newX;
cursor.y = newY;
cursor.el.style.transform = `translate(${cursor.x}px, ${cursor.y}px) rotate(${toDegrees(angle)}deg) scale(${cursor.scaleX}, ${cursor.scaleY})`;
requestAnimationFrame(loop);
};
const angleBetween = (x1, y1, x2, y2) => Math.atan2(y2 - y1, x2 - x1);
const onPointerMove = (e) => {
if (!target.followMouse) {
return;
}
const pointer = (e.touches && e.touches.length) ? e.touches[0] : e;
const { pageX: x, pageY: y } = pointer;
target.x = x;
target.y = y;
};
const onPointerOver = (e) => {
const btn = e.target;
const rect = btn.getBoundingClientRect();
target.followMouse = false;
target.x = window.scrollX + rect.left + (rect.width >> 1);
target.y = window.scrollY + rect.top + (rect.height >> 1);
target.width = Math.max(rect.width, rect.height) + 50;
};
const onPointerOut = () => {
target.followMouse = true;
target.width = cursorWidth;
};
document.body.addEventListener('mousemove', onPointerMove);
document.body.addEventListener('touchmove', onPointerMove);
buttons.forEach((btn) => {
btn.addEventListener('touchstart', onPointerOver);
btn.addEventListener('mouseover', onPointerOver);
btn.addEventListener('touchend', onPointerOut);
btn.addEventListener('mouseout', onPointerOut);
});
loop();
html,
body {
margin: 0;
padding: 0;
}
.wrapper {
width: 100vw;
min-height: 1500px;
display: flex;
flex-direction: row;
align-items: center;
}
.container {
width: 100%;
display: flex;
padding: 0 1rem;
}
.cursor {
position: absolute;
z-index: 10;
width: 100px;
height: 100px;
border: 2px solid #23bfa0;
border-radius: 50%;
pointer-events: none;
}
.button {
padding: 1rem;
background-color: #23bfa0;
border: none;
box-shadow: 0 0 7px 0px rgba(0, 0, 0, 0.2);
color: white;
font-size: 1.2rem;
cursor: pointer;
transition: box-shadow 0.1s ease-in, transform 0.1s ease-in;
&--small {
padding: 0.75rem;
font-size: 0.75rem;
}
&:hover {
transform: translate(0%, -2px);
box-shadow: 0px 4px 9px 2px rgba(0, 0, 0, 0.2)
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<div class="cursor border-cursor"></div>
<div class="wrapper">
<div class="container">
<button class="button button--small border-button">small</button>
<button class="button border-button">hover me</button>
<button class="button border-button">hover me more</button>
</div>
</div>
</body>
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.