I have an audio script with play/pause, I want to make the audio stop when I click on the square button at the left, and to add the timing to the right
here is the code: https://codepen.io/Amirafik/pen/YzxQZQw
HTML
<div class="title">
Dina Mohamed
</div>
<div class="stop"></div>
<div id="audioButton">
<div id="playerContainer">
<div class="listen">LISTEN</div>
</div>
</div>
<div class="duration">
00:12
</div>
<br>_____________________________________________________</br>
<div class="note">
<p>All items were more than perfect, we loved the experience and will order ONE OAK services again in the future for sure. <!--<span style="color:#F04E36"><br> Dina sent us an amazing feedback about her experience, tap the play button to listen to her cheerful words.</span></p>-->
</div
CSS
#import url('https://fonts.googleapis.com/css?family=montserrat:100,200,300,400,500,600,700,800,900');
body {
background: #ffffff;
color: #000000;
font-size: 16px ;
font-family: "montserrat" ;
font-weight: 500;
-webkit-tap-highlight-color: transparent;
}
a {
color: #F04E36;
}
.title {
max-width: 700px;
margin: 0 auto;
color: #000000;
font-weight:700;
display:inline-block;
}
.note {
max-width: 380px;
margin: 0 auto;
color: #000000;
display:inline-block;
}
.circle-audio-player {
cursor: pointer;
width:25px;
padding:0px;
margin-top:-67%;
margin-bottom:-50%;
margin-left:-7px;
background-color:#EDEBE7;
border-radius:50%;
vertical-align:middle;
}
#playerContainer {
padding: 0px;
vertical-align:middle;
}
#audioButton {
border-radius: 50px;
border: 2px solid #000000;
padding: 10px;
max-width: 85px;
height: 10px;
display: inline-block;
vertical-align:middle;
margin-left:2px;
}
.listen {
margin-left: 5px;
color: #000000;
font-weight:700;
display:inline-block;
float:right;
vertical-align:middle;
margin-top:-5%;
font-size: 14px ;
}
.stop {
max-width: 500px;
margin-left:10px;
height: 10px;
width: 10px;
background-color: #000000;
font-weight:500;
font-size: 14px ;
display:inline-block;
vertical-align:middle;
}
.duration {
max-width: 500px;
margin-left: 2px;
color: #000000;
font-weight:500;
font-size: 14px ;
display:inline-block;
}
JS
// settings
var DEFAULTS = {
borderColor: "#EDEBE7",
playedColor: "#F04E36",
backgroundColor: "#d3cdc2",
iconColor: "#000000",
borderWidth: 2,
size: 48,
className: 'circle-audio-player'
};
// reused values
var pi = Math.PI;
var doublePi = pi * 2;
var arcOffset = -pi / 2;
var animTime = 200;
var loaderTime = 1800;
var CircleAudioPlayer = function (options) {
options = options || {};
for (var property in DEFAULTS) {
this[property] = options[property] || DEFAULTS[property];
}
// create some things we need
this._canvas = document.createElement('canvas');
this._canvas.setAttribute('class', this.className + ' is-loading');
this._canvas.addEventListener('mousedown', (function () {
if (this.playing) {
this.pause();
}
else {
this.play();
}
}).bind(this));
this._ctx = this._canvas.getContext('2d');
// set up initial stuff
this.setAudio(options.audio);
this.setSize(this.size);
// redraw loop
(function cAPAnimationLoop (now) {
// check if we need to update anything
if (this.animating) {
this._updateAnimations(now);
}
if (this._forceDraw || this.playing || this.animating || this.loading) {
this._draw();
this._forceDraw = false;
}
requestAnimationFrame(cAPAnimationLoop.bind(this));
}).call(this, new Date().getTime());
};
CircleAudioPlayer.prototype = {
// private methods
_animateIcon: function (to, from) {
// define a few things the first time
this._animationProps = {
animStart: null,
from: from,
to: to
};
if (from) {
this.animating = true;
}
else {
this._animationProps.current = this._icons[to].slice();
this.draw();
}
},
_updateAnimations: function (now) {
this._animationProps.animStart = this._animationProps.animStart || now;
var deltaTime = now - this._animationProps.animStart;
var perc = (1 - Math.cos(deltaTime / animTime * pi / 2));
if (deltaTime >= animTime) {
this.animating = false;
perc = 1;
this._animationProps.current = this._icons[this._animationProps.to].slice();
this.draw();
}
else {
var from = this._icons[this._animationProps.from];
var current = [];
for (var i = 0; i < from.length; i++) {
current.push([]);
for (var j = 0; j < from[i].length; j++) {
current[i].push([]);
var to = this._icons[this._animationProps.to][i][j];
current[i][j][0] = from[i][j][0] + (to[0] - from[i][j][0]) * perc;
current[i][j][1] = from[i][j][1] + (to[1] - from[i][j][1]) * perc;
}
}
this._animationProps.current = current;
}
},
_draw: function (progress) {
// common settings
if (isNaN(progress)) {
progress = this.audio.currentTime / this.audio.duration || 0;
}
// clear existing
this._ctx.clearRect(0, 0, this.size, this.size);
// draw bg
this._ctx.beginPath();
this._ctx.arc(this._halfSize, this._halfSize, this._halfSize - (this.borderWidth / 2), 0, doublePi);
this._ctx.closePath();
this._ctx.fillStyle = this.backgroundColor;
this._ctx.fill();
// draw border
// our active path is already the full circle, so just stroke it
this._ctx.lineWidth = this.borderWidth;
this._ctx.strokeStyle = this.borderColor;
this._ctx.stroke();
// play progress
if (progress > 0) {
this._ctx.beginPath();
this._ctx.arc(this._halfSize, this._halfSize, this._halfSize - (this.borderWidth / 2), arcOffset, arcOffset + doublePi * progress);
this._ctx.strokeStyle = this.playedColor;
this._ctx.stroke();
}
// icons
this._ctx.fillStyle = this.iconColor;
if (this.loading) {
var loaderOffset = -Math.cos((new Date().getTime() % (loaderTime)) / (loaderTime) * pi) * doublePi - (pi / 3) - (pi / 2);
this._ctx.beginPath();
this._ctx.arc(this._halfSize, this._halfSize, this._halfSize / 3, loaderOffset, loaderOffset + pi / 3 * 2);
this._ctx.strokeStyle = this.iconColor;
this._ctx.stroke();
}
else {
this._ctx.beginPath();
var icon = (this._animationProps && this._animationProps.current) || this._icons.play;
for (var i = 0; i < icon.length; i++) {
this._ctx.moveTo(icon[i][0][0], icon[i][0][1]);
for (var j = 1; j < icon[i].length; j++) {
this._ctx.lineTo(icon[i][j][0], icon[i][j][1]);
}
}
// this._ctx.closePath();
this._ctx.fill();
// stroke to fill in for retina
this._ctx.strokeStyle = this.iconColor;
this._ctx.lineWidth = 2;
this._ctx.lineJoin = 'miter';
this._ctx.stroke();
}
},
_setState: function (state) {
this.playing = false;
this.loading = false;
if (state === 'playing') {
this.playing = true;
this._animateIcon('pause', 'play');
}
else if (state === 'loading') {
this.loading = true;
}
else if (this.state !== 'loading') {
this._animateIcon('play', 'pause');
}
else {
this._animateIcon('play', null);
}
this.state = state;
this._canvas.setAttribute('class', this.className + ' is-' + state);
this.draw();
},
// public methods
draw: function () {
this._forceDraw = true;
},
setSize: function (size) {
this.size = size;
this._halfSize = size / 2; // we do this a lot. it's not heavy, but why repeat?
this._canvas.width = size;
this._canvas.height = size;
// set icon paths
var iconSize = this.size / 2;
var pauseGap = iconSize / 10;
var playLeft = Math.cos(pi / 3 * 2) * (iconSize / 2) + this._halfSize;
var playRight = iconSize / 2 + this._halfSize;
var playHalf = (playRight - playLeft) / 2 + playLeft;
var top = this._halfSize - Math.sin(pi / 3 * 2) * (iconSize / 2);
var bottom = this.size - top;
var pauseLeft = this._halfSize - iconSize / 3;
var pauseRight = this.size - pauseLeft;
this._icons = {
play: [
[
[playLeft, top],
[playHalf, (this._halfSize - top) / 2 + top],
[playHalf, (this._halfSize - top) / 2 + this._halfSize],
[playLeft, bottom]
],
[
[playHalf, (this._halfSize - top) / 2 + top],
[playRight, this._halfSize],
[playRight, this._halfSize],
[playHalf, (this._halfSize - top) / 2 + this._halfSize]
]
],
pause: [
[
[pauseLeft, top + pauseGap],
[this._halfSize - pauseGap, top + pauseGap],
[this._halfSize - pauseGap, bottom - pauseGap],
[pauseLeft, bottom - pauseGap]
],
[
[this._halfSize + pauseGap, top + pauseGap],
[pauseRight, top + pauseGap],
[pauseRight, bottom - pauseGap],
[this._halfSize + pauseGap, bottom - pauseGap]
]
]
};
if (this._animationProps && this._animationProps.current) {
this._animateIcon(this._animationProps.to);
}
if (!this.playing) {
this.draw();
}
},
setAudio: function (audioUrl) {
this.audio = new Audio(audioUrl);
this._setState('loading');
this.audio.addEventListener('canplaythrough', (function () {
this._setState('paused');
}).bind(this));
this.audio.addEventListener('play', (function () {
this._setState('playing');
}).bind(this));
this.audio.addEventListener('pause', (function () {
// reset when finished
if (this.audio.currentTime === this.audio.duration) {
this.audio.currentTime = 0;
}
this._setState('paused');
}).bind(this));
},
appendTo: function (element) {
element.appendChild(this._canvas);
},
play: function () {
this.audio.play();
},
pause: function () {
this.audio.pause();
}
};
// now init one as an example
var cap = new CircleAudioPlayer({
audio: 'https://www.siriusxm.com/content/dam/sxm-com/audio/test/audio-previews/audio_test03.mp3.png',
size: 120,
borderWidth: 8
});
cap.appendTo(playerContainer);
You can simply use AudioElement.pause() to pause an running element, and the next AudioElement.play() will start from where you left off.
You can essentially set the currentTime property of the audio element to start from the beginning
A simple demonstration of how it works
const pause = document.getElementById('pause');
const stop = document.getElementById('stop');
const play = document.getElementById('play');
const container = document.getElementById('player');
const duration = document.getElementById('duration');
const audio = new Audio('https://www.siriusxm.com/content/dam/sxm-com/audio/test/audio-previews/audio_test03.mp3.png');
let played = 0;
let playing = true;
const wait = (ms) => new Promise(resolve => setTimeout(resolve, ms));
run = async function () {
while(playing) {
if (played == Math.floor(audio.duration)) break;
duration.innerText = `${played} / ${Math.floor(audio.duration)}`;
played++;
await wait(1000);
}
}
container.appendChild(audio);
stop.addEventListener('click', () => {
duration.innerText = `0 / ${Math.floor(audio.duration)}`
audio.pause();
audio.currentTime = 0;
played = 0;
playing = false;
});
pause.addEventListener('click', () => {
audio.pause();
playing = false;
});
play.addEventListener('click', () => {
playing = true
audio.play();
run();
});
<div id="player"></div>
<div id="duration">0.0</div>
<button id="play">play</button>
<button id="stop">stop</button>
<button id="pause">pause</button>
I have a bug in this code somewhere that cause the ship to fly faster and faster in space after returning from the planet. I cant figure this one out.
I set the speed to 0.1 so that its super slow in space. When you click on the planet, i run a function that will move canvas's off screen and use zindex to brong a div tag to the top of the stack. When you land and return to orbit, the ship will move slightly faster. After doing it about 10-15 times the ship moves far greater than the 0.1 speed that is set. I will include the html, js and css so you can run it to test.
Here is the whole code.
// Canvas Context's
var canvasMS = document.getElementById('MainScreen_cvs');
var ctxMain = canvasMS.getContext('2d');
var canvasShip = document.getElementById('Ship_cvs');
var ctxShip = canvasShip.getContext('2d');
var PlanetDiv = document.getElementById('PlanetDiv');
var OrbitReturn = document.getElementById('OrbitReturn');
var canvasPlanets = document.getElementById('Planets_cvs');
var ctxPlanets = canvasPlanets.getContext('2d');
var canvasHUD = document.getElementById('HUD_cvs');
var ctxHUD = canvasHUD.getContext('2d');
var canvasSurface = document.getElementById('Surface_cvs');
var ctxSurface = canvasSurface.getContext('2d');
// ----------------------------------End Canvas Context
var Player1;
var Planet1;
var planetClicked;
var gameWidth = canvasMS.width;
var gameHeight = canvasMS.height;
var mouseX = 10000;
var mouseY = 10000;
var SpaceMapX = 10;
var SpaceMapY = 10;
var SurfaceMap = 0;
var SurfaceMap2 = -1600;
var inSpace = true;
var onSurface = false;
var requestAnimFrame = window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.msRequestAnimationFrame ||
window.oRequestAnimationFrame;
// Load Images
var imgMap = new Image();
imgMap.src = 'images/bg1.png';
var imgButtons = new Image();
imgButtons.src = 'images/button_sprite.png';
var imgBlueWindow = new Image();
imgBlueWindow.src = 'images/blue_window.png';
var imgSprite = new Image();
imgSprite.src = 'images/sprite.png';
var imgPlanets = new Image();
imgPlanets.src = 'images/earthlike_p1.png';
var imgBluesky1 = new Image();
imgBluesky1.src = 'images/bluesky1.png';
var imgBluesky2 = new Image();
imgBluesky2.src = 'images/bluesky2.png';
imgMap.addEventListener('load',init,false);
// ------------- End Loading Images
//-------------------- Create Game Objects ----------------
function CreateGameObjects(){
Player1 = new Ship();
Planet1 = new Planet();
};
//---------------END CREATING GAME OBJECTS------------------
function init(){ //----------------------------------------------- GAME INITIALIZATION
document.addEventListener('keydown',checkKeyDown,false);
document.addEventListener('keyup',checkKeyUp,false);
document.addEventListener("mousedown", checkMouseDown, false);
document.addEventListener("mouseup", checkMouseUp, false);
CreateGameObjects();
Loop();
};
function Loop() { // ---------------- Main Game Loop
clearCtx();
DrawGameObjects();
requestAnimFrame(Loop);
};
function planetSurface(){
if(onSurface){
clearCtx();
HUD();
Player1.draw();
if(mouseY < 21 && mouseX > 693){
ReturntoOrbit();
}
planetClicked.drawSurfaceImg();
var CloseButton = '<button style="float:right;" type="button">Return to Orbit</button>' ;
OrbitReturn.innerHTML = CloseButton;
requestAnimFrame(planetSurface);
}
};
function DrawGameObjects(){
Player1.draw();
Planet1.draw();
HUD();
};
function HUD(){
canvasHUD.style.zIndex = "100";
if (onSurface){
ctxHUD.fillStyle = "#000";
ctxHUD.fillText("locSurface: " + planetClicked.locSurface, 20,30);
}
if (inSpace)
ctxHUD.fillStyle = "#fff";
ctxHUD.fillText("Speed: " + Player1.speed, 60,60);
ctxHUD.fillText("drawX: " + Player1.drawX, 600,40);
ctxHUD.fillText("drawY: " + Player1.drawY, 600,30);
// ctxHUD.fillText("Planet Clicked: " + Planet1.isClicked, 600,50);
}
//----------------------------------------------------------- Objects
/************************************************************************************/
//--------------------------------- SPACE SHIP --------------------------------------
function Ship(){
this.srcX = 0;
this.srcY = 0;
this.srcW = 60;
this.srcH = 60;
this.drawX = 20 ;
this.drawY = 50 ;
this.speed = 0;
this.surfaceSpeed = 10;
this.drift = 0.45;
this.w = 16;
this.h = 16;
this.isUpKey = false;
this.isDownKey = false;
this.isLeftKey = false;
this.isRightKey = false;
this.isSpacebar = false;
this.direction = "n/a";
this.isMoving = false;
this.isClicked = false;
this.surfX = 350;
this.surfY = 200;
};
Ship.prototype.draw = function() {
if(inSpace)
ctxShip.drawImage(imgSprite,this.srcX,this.srcY,this.srcW,this.srcH,this.drawX,this.drawY,this.w,this.h);
if(onSurface)
ctxShip.drawImage(imgSprite,this.srcX,this.srcY,this.srcW,this.srcH,this.surfX,this.surfY,this.w,this.h);
this.checkPos(planetClicked);
};
Ship.prototype.checkPos = function (PlanetX){
if(inSpace){
this.srcY = 0;
this.srcW = 60;
this.w = 16;
this.h = 16;
this.speed = 0.1;
//----------------------------- Move Ship and Map based on the speed of the ship.
if(this.isLeftKey){
this.drawX -= this.speed;
if(SpaceMapX >= 1){
SpaceMapX -= this.speed;
}
}
if(this.isRightKey){
this.drawX += this.speed;
if(SpaceMapX <= 2190)SpaceMapX += this.speed;
}
if(this.isDownKey){
this.drawY += this.speed;
if(SpaceMapY <= 2490)SpaceMapY += this.speed;
}
if (this.isUpKey) {
this.drawY -= this.speed;
if(SpaceMapY >= 1){
SpaceMapY -= this.speed;
}
}
if (SpaceMapY < 0) {SpaceMapY = 0;}
if (SpaceMapX < 0 ) {SpaceMapX = 0}
//--------------------------------------------------------------------END
//-----------------------------------Change Ship Graphic based on direction and map boundaries.
if(this.isUpKey) this.srcX = 360;
if(this.isDownKey) this.srcX = 120;
if(this.isLeftKey) this.srcX = 240;
if(this.isRightKey) this.srcX = 0;
if(this.isUpKey && this.isLeftKey) this.srcX = 300;
if(this.isUpKey && this.isRightKey) this.srcX = 420;
if(this.isDownKey && this.isLeftKey) this.srcX = 180;
if(this.isDownKey && this.isRightKey) this.srcX = 60;
if (this.drawX <= 5) this.drawX = 5;
if (this.drawY <= 5) {this.drawY = 5};
if (this.drawY >= 480) {this.drawY = 480};
if (this.drawX >= 780) {this.drawX = 780};
//----------------------------------------------------------------END
ctxMain.drawImage(imgMap,SpaceMapX,SpaceMapY,gameWidth,gameHeight,0,0,gameWidth,gameHeight);
}
if (onSurface) {
this.srcY = 240;
this.srcW = 92;
this.w = 93;
this.h = 60;
if(this.isLeftKey){
PlanetX.locSurface -= this.surfaceSpeed;
SurfaceMap += this.surfaceSpeed;
SurfaceMap2 += this.surfaceSpeed;
PlanetX.MapDirection = -1;
this.srcX = 93;
}
if(this.isRightKey){
PlanetX.locSurface += this.surfaceSpeed;
SurfaceMap -= this.surfaceSpeed;
SurfaceMap2 -= this.surfaceSpeed;
PlanetX.MapDirection = 1;
this.srcX = 0;
}
}
};
//------------------------------END OF SPACE SHIP ------------------------------------
//----------------------------- PLANET OBJECT INFO ------------------------------------
function Planet(){
this.srcX = 0;
this.srcY = 0;
this.srcW = 100;
this.srcH = 100;
this.w = 50;
this.h = 50;
this.coordX = 100;
this.coordY = 100;
this.planetType = "Small Earthlike Planet."
this.drawX = this.coordX - SpaceMapX;
this.drawY = this.coordY - SpaceMapY;
this.surfaceIMG = imgBluesky1;
this.isClicked = false;
this.locSurface = 0;
};
Planet.prototype.draw = function(){
this.drawX = this.coordX - SpaceMapX;
this.drawY = this.coordY - SpaceMapY;
ifClicked(this);
if(this.isClicked){
PlanetDiv.style.display = "block";
var LandPlanetDivButton = '<button id="LandPlanetDivButton" type="button" onclick="landOnSurface();">Land On Surface</button>';
var ClosePlanetDivButton = '<button id="ClosePlanetDivButton" type="button" onclick="ClosePlanetDiv();">Close (x)</button><br/><p id="PlanetDivText">' ;
PlanetDiv.style.zIndex = "2";
HideCanvas();
planetClicked = this;
PlanetDiv.innerHTML = LandPlanetDivButton + ClosePlanetDivButton + this.planetType; + '</p>';
}
ctxPlanets.drawImage(imgPlanets,this.srcX,this.srcY,this.srcW,this.srcH,this.drawX,this.drawY,this.w,this.h);
};
Planet.prototype.drawSurfaceImg = function(){
if(SurfaceMap2 >= 0) SurfaceMap2 = -1600;
if(SurfaceMap2 < -1600) SurfaceMap2 = -1;
if(SurfaceMap >= 1600) SurfaceMap = 0;
if(SurfaceMap < 0) SurfaceMap = 1599;
ctxSurface.drawImage(this.surfaceIMG, 0, 0, 1600, gameHeight, SurfaceMap, 0, 1600, gameHeight);
ctxSurface.drawImage(this.surfaceIMG, 0, 0, 1600, gameHeight, SurfaceMap2, 0, 1600, gameHeight);
};
//----------------------------- END OF PLANET OBJECT -----------------------------------
//-----end Objects
function randomFromTo(from,to){
return Math.floor(Math.random()*(to-from+1)+from);
};
function closestNum(Num, a){
var num = Num + (gameWidth/2);
var closest = a[0];
var difference = Math.abs (num - closest);
for (var i = 0; i < a.length; i++) {
var difference2 = Math.abs (num - a[i]);
if (difference2 < difference) {
difference = difference2;
closest = a[i];
}
}
return closest;
};
function sortNum(a)
{
var swapped;
do{
swapped = false;
for (var i=0; i < a.length-1; i++) {
if (a[i] > a[i+1]) {
var temp = a[i];
a[i] = a[i+1];
a[i+1] = temp;
swapped = true;
}
}
}while (swapped);
};
function ifClicked(obj){
if(mouseX >= obj.drawX && mouseX <= obj.drawX + obj.w){
if(mouseY >= obj.drawY && mouseY <= obj.drawY + obj.h){
obj.isClicked = true;
}
}
else{
obj.isClicked = false;
}
};
function clearCtx() {
ctxMain.clearRect(0,0,gameWidth,gameHeight);
ctxShip.clearRect(0,0,gameWidth,gameHeight);
ctxPlanets.clearRect(0,0,gameWidth,gameHeight);
ctxHUD.clearRect(0,0,gameWidth,gameHeight);
ctxSurface.clearRect(0,0,gameWidth,gameHeight);
};
function checkKeyDown(e){
var keyID = e.keyCode || e.which;
if(keyID === 38 || keyID === 87){ // up arrow or W key
Player1.isUpKey = true;
Player1.direction = "North";
Player1.isMoving = true;
e.preventDefault();
}
if(keyID === 39|| keyID === 68){ // right arrow or D key
Player1.isRightKey = true;
Player1.direction = "East"
Player1.isMoving = true;
e.preventDefault();
}
if(keyID === 40 || keyID === 83){ // down arrow or S key
Player1.isDownKey = true;
Player1.direction = "South";
Player1.isMoving = true;
e.preventDefault();
}
if(keyID === 37 || keyID === 65){ // left arrow or A key
Player1.isLeftKey = true;
Player1.direction = "West";
Player1.isMoving = true;
e.preventDefault();
}
};
function checkKeyUp(e){
var keyID = e.keyCode || e.which;
if(keyID === 38 || keyID === 87){ // up arrow or W key
Player1.isUpKey = false;
Player1.isMoving = false;
e.preventDefault();
}
if(keyID === 39|| keyID === 68){ // right arrow or D key
Player1.isRightKey = false;
Player1.isMoving = false;
e.preventDefault();
}
if(keyID === 40 || keyID === 83){ // down arrow or S key
Player1.isDownKey = false;
Player1.isMoving = false;
e.preventDefault();
}
if(keyID === 37 || keyID === 65){ // left arrow or A key
Player1.isLeftKey = false;
Player1.isMoving = false;
e.preventDefault();
}
};
function clearMouse(){
mouseX = 10000;
mouseY = 10000;
};
function checkMouseDown(e) {
var mX = (e.clientX - (canvasMS.offsetLeft - canvasMS.scrollLeft));
var mY = (e.clientY - (canvasMS.offsetTop - canvasMS.scrollTop));
if(mX <= gameWidth && mX >= 0) mouseX = mX;
if(mY <= gameHeight && mY >= 0) mouseY = mY;
//mouseIsDown = true;
};
function checkMouseUp(e){
//mouseIsDown = false;
clearMouse();
};
function ClosePlanetDiv (){
PlanetDiv.style.zIndex = "-2";
PlanetDiv.innerHTML = "";
PlanetDiv.style.display = "none";
ShowCanvas();
};
function HideCanvas(){
canvasShip.style.marginTop = "-10000px";
canvasPlanets.style.marginTop = "-10000px";
};
function ShowCanvas(){
canvasShip.style.marginTop = "-500px";
canvasPlanets.style.marginTop = "-500px";
};
function landOnSurface(){
ClosePlanetDiv();
inSpace = false;
onSurface = true;
Player1.srcX = 0;
planetSurface();
canvasSurface.style.display = "block";
OrbitReturn.style.display = "block";
};
function ReturntoOrbit(){
OrbitReturn.style.display = "none";
canvasSurface.style.display = "none";
inSpace = true;
onSurface = false;
Loop();
};
<!doctype html>
<html lang='en'>
<head>
<meta charset="utf-8">
<title>Space Explorer</title>
<link rel="stylesheet" type="text/css" href="style.css">
<script src="Functions.js"></script>
</head>
<body>
<canvas id="MainScreen_cvs" width="800" height="500"></canvas>
<div id="PlanetDiv"></div>
<canvas id="Surface_cvs" width="800" height="500"></canvas>
<canvas id="Ship_cvs" width="800" height="500"></canvas>
<canvas id="Planets_cvs" width="800" height="500"></canvas>
<canvas id="HUD_cvs" width="800" height="500"></canvas>
<div id="OrbitReturn"></div>
<div id="log">
<h1 style="color:blue;">Recent updates will be logged here when made live.</h1>
<hr />
<h3> Wednesday August 3, 2016 </h3>
<ul>
<li> HTML file completed. Working on getting JS files started.</li>
<li> JS files created. </li>
<li>Basic ship & flight functions in place. Basic star map initialized.</li>
</ul>
<hr />
</div>
<script type="text/javascript" src="game.js"></script>
</body>
</html>
body {
background: #303030;
}
#MainScreen_cvs {
position: relative;
display: block;
background: #777777 ;
margin: 30px auto 0px;
z-index: 1;
}
#Surface_cvs{
position: relative;
display: none;
z-index: 1;
margin: -500px auto 0px;
}
#Ship_cvs, #Planets_cvs, #HUD_cvs {
display: block;
position: relative;
margin: -500px auto 0px;
z-index: 1;
}
#log {
display: block;
position: absolute;
top: 560px;
left: 233px;
background: #ffffff;
overflow: scroll;
width: 800px;
height: 300px;
z-index: 3;
}
#OrbitReturn{
display: block;
position: relative;
width: 800px;
height: 500px;
z-index: 3;
margin: -500px auto 0px;
}
#PlanetDiv {
display: block;
position: relative;
width: 800px;
height: 500px;
background-image: url("images/Sky.jpg");
z-index: -2;
margin: -500px auto 0px;
}
#ClosePlanetDivButton{
float: right;
}
#LandPlanetDivButton{
position: absolute;
top: 400px;
left: 325px;
font-size: 20px;
}
#PlanetDivText{
text-indent: 50px;
font-size: 20px;
}
Something is happening with Ship.prototype.checkPos. Each time you land on the planet, it looks like the checking pauses, then starts up when you enter orbit. But this time he checkPos is getting called faster.
I could keep staring at it but you might be able to figure it out from there. I put a console.log('checkPos') at the top of that function and watched it pause and restart.
Ship.prototype.checkPos = function(PlanetX) {
console.log('checkPos');
if (inSpace) {
...
I think it might be here
function ReturntoOrbit() {
OrbitReturn.style.display = "none";
canvasSurface.style.display = "none";
inSpace = true;
onSurface = false;
//Loop(); <--- this little guy. Get rid of him.
};
I want to detect a collision between my ball and my bricks with an array made of numbers. It works but not completely.
If you look at my code, you see an array made of numbers from 0 to 5. 0 means that there is no brick detected and the rest is made of a color. The problem is that my function only detects a collision with the color 1 (black) but not the rest. What is the problem?
var canvas = document.getElementById("mijnCanvas");
var mijnObject = canvas.getContext("2d");
var afbeelding = new Image();
var balkX = (canvas.width/2)-50;
var balkY = canvas.height-40;
var balX = canvas.width/2;
var balY = canvas.height-50;
var radius = 8;
var balNaarX = 5;
var balNaarY = 5;
function makenBalkKort() {
mijnObject.drawImage(afbeelding, balkX, balkY, afbeelding.width, afbeelding.height);
}
afbeelding.src = "Afbeeldingen/BrickSmasher_Balk_Kort.png";
function makenBal() {
mijnObject.beginPath();
var mijnBalGradient = mijnObject.createRadialGradient(balX, balY, 0, balX, balY, 6);
mijnBalGradient.addColorStop(0, "#000000");
mijnBalGradient.addColorStop(1, "#FFFFFF");
mijnObject.fillStyle = mijnBalGradient;
mijnObject.strokeStyle = "#000000";
mijnObject.arc(balX, balY, radius, 0, 2*Math.PI, false);
mijnObject.fill();
mijnObject.stroke();
mijnObject.closePath();
}
function tekenenObjecten() {
mijnObject.clearRect(0, 0, canvas.width, canvas.height);
makenBalkKort();
makenBal();
makenMuur();
collisieMetStenenX();
setTimeout(function() {
if(balX+balNaarX < radius || balX+balNaarX > canvas.width-radius) {
balNaarX = -balNaarX;
}
if(balY+balNaarY < radius) {
balNaarY = -balNaarY;
}
if(balY+balNaarY > balkY-radius) {
if(balX+balNaarX >= balkX && balX+balNaarX <= balkX+afbeelding.width) {
balNaarY = -balNaarY;
}
else {
alert("Game over");
document.location.reload();
}
}
balX += balNaarX;
balY += balNaarY;
}, 1000);
}
setInterval(tekenenObjecten, 20);
window.addEventListener("keydown", function LinksOfRechts() {
mijnObject.clearRect(balkX, balkY, canvas.width, canvas.height);
var balkNaarX = 10;
var code = event.which || event.keyCode;
if(code == 37) {
if(balkX > 0) {
balkX -= balkNaarX;
}
}
else if(code == 39) {
if(balkX < canvas.width-afbeelding.width) {
balkX += balkNaarX;
}
}
mijnObject.drawImage(afbeelding, balkX, balkY, afbeelding.width, afbeelding.height);
});
canvas.addEventListener("click", function balkLangMaken() {
mijnObject.clearRect(balkX, balkY, canvas.width, canvas.height);
afbeelding.src = "Afbeeldingen/BrickSmasher_Balk_Lang.png";
setTimeout(function() {
mijnObject.clearRect(balkX, balkY, canvas.width, canvas.height);
afbeelding.src = "Afbeeldingen/BrickSmasher_Balk_Kort.png";
}, 3000);
});
var stenenPerRij = 27;
var steenHoogte = 20;
var steenBreedte = canvas.width/stenenPerRij;
var stenen = [
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
[0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0],
[0,1,2,3,2,3,2,3,2,3,2,3,2,3,2,3,2,3,2,3,2,3,2,3,2,1,0],
[0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0],
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
[0,1,1,0,0,2,2,2,2,0,0,0,0,0,0,1,0,1,4,4,4,0,1,0,0,0,1],
[1,0,0,1,0,2,0,0,0,2,0,0,0,0,0,1,0,1,0,0,0,0,1,1,0,0,1],
[1,1,1,1,0,2,2,2,2,0,0,0,0,0,0,1,0,1,4,4,0,0,1,0,1,0,1],
[1,0,0,1,0,2,0,2,0,0,0,1,0,0,0,1,0,1,0,0,0,0,1,0,0,1,1],
[1,0,0,1,0,2,0,0,2,2,0,0,1,1,1,0,0,1,4,4,4,0,1,0,0,0,1],
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
];
function makenMuur() {
for(var i = 0; i < stenen.length; i = i+1) {
for(var j = 0; j < stenen[i].length; j = j+1) {
tekenenStenen(j,i,stenen[i][j]);
}
}
}
function tekenenStenen(x,y,stenen) {
switch(stenen) {
case 1:
mijnObject.fillStyle = "#0d0d0d";
break;
case 2:
mijnObject.fillStyle = "#333333";
break;
case 3:
mijnObject.fillStyle = "#595959";
break;
case 4:
mijnObject.fillStyle = "#808080";
break;
case 5:
mijnObject.fillStyle = "#a6a6a6";
break;
default:
mijnObject.clearRect(0, 0, steenBreedte, steenHoogte);
break;
}
if(stenen) {
mijnObject.beginPath();
mijnObject.strokeStyle = "#000000";
mijnObject.rect(x*steenBreedte, y*steenHoogte, steenBreedte, steenHoogte);
mijnObject.fill();
mijnObject.stroke();
mijnObject.closePath();
}
}
function collisieMetStenenX() {
for(var i = 0; i < stenen.length; i = i+1) {
for(var j = 0; j < stenen[i].length; j = j+1) {
if(stenen[i][j] == true) {
var steenX = j*steenBreedte;
var steenY = i*steenHoogte;
if((balX+balNaarX > steenX && balX+balNaarX < steenX+steenBreedte)
&& (balY+balNaarY > steenY && balY+balNaarY < steenY+steenHoogte)) {
balNaarY = -balNaarY;
}
}
}
}
}
Here is my HTML-code:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>BrickSmasher</title>
<style>
canvas {
position: relative;
margin-left: auto;
margin-right: auto;
display: block;
}
</style>
</head>
<body>
<canvas id="mijnCanvas" width="1200" height="600" style="border: 1px solid black"></canvas>
<script src="BrickSmasher.js"></script>
</body>
</html>
Replace this line:
if(stenen[i][j] == true) {
with:
if(stenen[i][j] > 0) {
or simply:
if(stenen[i][j]) {
The reason is that when you compare with true, JavaScript needs to do a conversion. As one side of the equation is numeric, the boolean expression on the other side is converted to the numeric equivalent of true, which is 1. That means there is no equality when stenen[i][j] is 2, 3, ...
The last alternative works, because there the conversion is in the opposite sense: an if condition needs to resolve to a boolean value. So the numerical value is converted to boolean. And there any non-zero value will convert to true.