I am trying to learn JavaScript and found this tutorial:
http://www.lostdecadegames.com/how-to-make-a-simple-html5-canvas-game/
But i can not figure out how to remove the background from the game.
Any help with removing the background would be appreciated! :)
Code that affects the background:
// Background image
var bgReady = false;
var bgImage = new Image();
bgImage.onload = function () {
bgReady = true;
};
bgImage.src = "images/background.png";
// Draw everything
var render = function () {
if (bgReady) {
ctx.drawImage(bgImage, 0, 0);
}
The whole JavaScript file:
http://www.lostdecadegames.com/demos/simple_canvas_game/js/game.js
// Create the canvas
var canvas = document.createElement("canvas");
var ctx = canvas.getContext("2d");
canvas.width = 512;
canvas.height = 480;
document.body.appendChild(canvas);
// Background image
var bgReady = false;
var bgImage = new Image();
bgImage.onload = function () {
bgReady = true;
};
bgImage.src = "images/background.png";
// Hero image
var heroReady = false;
var heroImage = new Image();
heroImage.onload = function () {
heroReady = true;
};
heroImage.src = "images/hero.png";
// Monster image
var monsterReady = false;
var monsterImage = new Image();
monsterImage.onload = function () {
monsterReady = true;
};
monsterImage.src = "images/monster.png";
// Game objects
var hero = {
speed: 256 // movement in pixels per second
};
var monster = {};
var monstersCaught = 0;
// Handle keyboard controls
var keysDown = {};
addEventListener("keydown", function (e) {
keysDown[e.keyCode] = true;
}, false);
addEventListener("keyup", function (e) {
delete keysDown[e.keyCode];
}, false);
// Reset the game when the player catches a monster
var reset = function () {
hero.x = canvas.width / 2;
hero.y = canvas.height / 2;
// Throw the monster somewhere on the screen randomly
monster.x = 32 + (Math.random() * (canvas.width - 64));
monster.y = 32 + (Math.random() * (canvas.height - 64));
};
// Update game objects
var update = function (modifier) {
if (38 in keysDown) { // Player holding up
hero.y -= hero.speed * modifier;
}
if (40 in keysDown) { // Player holding down
hero.y += hero.speed * modifier;
}
if (37 in keysDown) { // Player holding left
hero.x -= hero.speed * modifier;
}
if (39 in keysDown) { // Player holding right
hero.x += hero.speed * modifier;
}
// Are they touching?
if (
hero.x <= (monster.x + 32)
&& monster.x <= (hero.x + 32)
&& hero.y <= (monster.y + 32)
&& monster.y <= (hero.y + 32)
) {
++monstersCaught;
reset();
}
};
// Draw everything
var render = function () {
if (bgReady) {
ctx.drawImage(bgImage, 0, 0);
}
if (heroReady) {
ctx.drawImage(heroImage, hero.x, hero.y);
}
if (monsterReady) {
ctx.drawImage(monsterImage, monster.x, monster.y);
}
// Score
ctx.fillStyle = "rgb(250, 250, 250)";
ctx.font = "24px Helvetica";
ctx.textAlign = "left";
ctx.textBaseline = "top";
ctx.fillText("Goblins caught: " + monstersCaught, 32, 32);
};
// The main game loop
var main = function () {
var now = Date.now();
var delta = now - then;
update(delta / 1000);
render();
then = now;
// Request to do this again ASAP
requestAnimationFrame(main);
};
// Cross-browser support for requestAnimationFrame
var w = window;
requestAnimationFrame = w.requestAnimationFrame || w.webkitRequestAnimationFrame || w.msRequestAnimationFrame || w.mozRequestAnimationFrame;
// Let's play this game!
var then = Date.now();
reset();
main();
Just empty the image source:
bgImage.src='';
Then...
bgImage.onload will never execute,
bgReady will always be false,
if (bgReady){ ctx.drawImage(bgImage, 0, 0); } will never execute,
Your background will remain transparent!
Related
I am currently trying to make an endless runner game, and I've just finished making the jumping mechanics. However, if the player were to hold the up arrow key, or press it before they touched the ground, they are able to mimic the ability to "fly". I am not sure how to prevent them from "flying" if they have not touched the ground yet. If anyone has any ideas, please let me know. My code is below:
let ctx = document.querySelector("canvas").getContext("2d");
// Screen
ctx.canvas.height = 512;
ctx.canvas.width = 512;
// Images
let bg = new Image;
bg.src = "./Background.png";
let fl = new Image;
fl.src = "./Floor.png";
// Player
let y = 256;
let speed = 2.5;
let pl = new Image;
pl.src = "./Idle.png";
pl.onload = function() {
ctx.drawImage(pl, 0, y);
};
// Jumping
let UP = false;
// Ducking
let DOWN = false;
document.onkeydown = function(e) {
if (e.keyCode == 38) UP = true;
if (e.keyCode == 40) DOWN = true;
};
document.onkeyup = function(e) {
if (e.keyCode == 38) UP = false;
if (e.keyCode == 40) DOWN = false;
};
// Frames
function update() {
// Clear
ctx.clearRect(0, 0, 512, 512);
// Background
ctx.drawImage(bg, 0, 0);
// Floor
ctx.drawImage(fl, 0, 384);
ctx.drawImage(fl, 128, 384);
ctx.drawImage(fl, 256, 384);
ctx.drawImage(fl, 384, 384);
// UP
if (UP) {
if (y > 100) {
ctx.drawImage(pl, 0, y -= speed);
} else {
UP = false;
};
} else if (!UP) {
if (y < 256) {
ctx.drawImage(pl, 0, y += speed);
} else {
ctx.drawImage(pl, 0, y);
};
};
// DOWN
if (DOWN) {
pl.src = "./Duck.png";
} else if (!DOWN) {
pl.src = "./Idle.png";
};
};
setInterval(update, 10);
So I have a canvas in my game which will display some text but I would like it to be if you have ever played Clicker Heros when you click theres some damage text displayed but its faded in and out slowly and kinda moves upward while fading out I would like to produce the same effect here
So what I have is a function which is called when the user clicks the Terminal I need the text to produce a similiar behavior but I am very new to canvas and not sure how to do so here is my current code
var canvas = document.getElementById("terminalCanvas");
var terminal = canvas.getContext("2d");
terminal.fillStyle = "#000000";
terminal.fillRect(0,0,150,200);
function WriteToCanvas(){
if(Game.Player.HTMLSupport == 1){
var rand = Math.floor(Math.random() * 122) + 1;
var tag = htmltags[rand];
terminal.font = "20px Comic Sans MS";
terminal.fillStyle = "rgb(0,255,1)";
terminal.textAlign = "center";
terminal.fillText(tag, canvas.width/2, canvas.height/2);
ClearCanvas();
}
}
function ClearCanvas(){
terminal.clearRect(0,0,canvas.width,canvas.height);
terminal.fillStyle = "#000000";
terminal.fillRect(0,0,150,200);
}
A particle system is what you need. Bellow at the top of the code is what you need to do a simple and memory efficient particle system.
Uses a particle pool. Dead particles go to the pool when their time is up. When new particles are needed check if any dead ones are in the pool, if so resurrect them, else create a new one. This avoids incurring the dreaded GC lag that particle systems can make work extra hard.
It may pay that you don't use the fillText (as it is very slow) to render the particle, but pre render and use drawImage. Up to you.
Sorry I dont have time for a deeper explanation
/*=====================================================================================
ANSWER code start
=====================================================================================*/
const LIFETIME = 1 / 180; // 180 frames
const YDIST = -140; // number of pixels to move over the life
const MOVE_CURVE_SHAPE = 1.5;
const FADE_CURVE_SHAPE = 1.5;
const FADE_CURVE_ADVANCE = 0.25; // Want the fade not to start early on the fade curve
var particles = []; // array to hold live particles
var particlePool = []; // to hold the dead
// this function is called once a frame
function display(){ // put code in here
ctx.setTransform(1,0,0,1,0,0); // reset transform
ctx.globalAlpha = 1; // reset alpha
ctx.clearRect(0,0,w,h);
ctx.font = "40px Comic Sans MS";
ctx.fillStyle = "black";
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.fillText("Click mouse to add particles",canvas.width/2, 30);
if(mouse.buttonRaw & 1){
var p;
if(particlePool.length){ // check if the are any dead particles in the pool
p = particlePool.shift(); // if so get the first on in out
}else{ // nothing in the pool so create a new on
p = {};
}
// set up the paticle
var text = (Math.floor(Math.random()* 10) *100) + "!"; // the text to display
p = createParticle(mouse.x,mouse.y,text,p); // set up the particle
particles.push(p); // push it onto the active array
mouse.buttonRaw = 0; // clear mouse down;
}
updateParticles(); // update particles
renderParticles(); // and draw them
}
// sets up a particle x,y startung pos, text the value to display, p and object to hold the data
function createParticle(x,y,text,p){
p.life = 1; // when this get down to zero it is dead
p.x = x;
p.y = y;
p.text = text;
return p;
}
// ease functions
var easeBell = function (x, pow) { // x 0-1 pos > 0
x = x * 2;
if( x > 1){
x = 1 - (x - 1);
var xx = Math.pow(x,pow);
return xx / (xx + Math.pow(1 - x, pow));
}else{
var xx = Math.pow(x,pow);
return xx / (xx + Math.pow(1 - x, pow));
}
}
var ease = function (x, pow) { // x 0-1 pos > 0
var xx = Math.pow(x,pow);
return xx / (xx + Math.pow(1 - x, pow));
}
function updateParticles(){ // update the life and death of the particles
for(var i = 0; i < particles.length; i ++){
var p = particles[i];
p.life -= LIFETIME;
if(p.life <= 0){ // time is up this particle is dead
// move it to the grave
particlePool.push(p);
particles.splice(i,1); // remove it from the array
i -= 1; // adjust i so we dont skip any
}
}
}
function renderParticles(){
ctx.font = "20px Comic Sans MS"
ctx.fillStyle = "#F00";
for(var i = 0; i < particles.length; i ++){ // for each active particle
var p = particles[i];
var fadeCurveVal = 1- p.life;
fadeCurveVal *= (1 - FADE_CURVE_ADVANCE); // scale it down
fadeCurveVal += FADE_CURVE_ADVANCE; // move it forward
ctx.globalAlpha = easeBell(fadeCurveVal,FADE_CURVE_SHAPE); // get the fade fx
var y = p.y + ease((1-p.life)/2,MOVE_CURVE_SHAPE) * YDIST * 2;
ctx.fillText(p.text,p.x,y);
}
}
/*=====================================================================================
ANSWER code End
=====================================================================================*/
/** SimpleFullCanvasMouse.js begin **/
const CANVAS_ELEMENT_ID = "canv";
const U = undefined;
var w, h, cw, ch; // short cut vars
var canvas, ctx, mouse;
var globalTime = 0;
var createCanvas, resizeCanvas, setGlobals;
var L = typeof log === "function" ? log : function(d){ console.log(d); }
createCanvas = function () {
var c,cs;
cs = (c = document.createElement("canvas")).style;
c.id = CANVAS_ELEMENT_ID;
cs.position = "absolute";
cs.top = cs.left = "0px";
cs.zIndex = 1000;
document.body.appendChild(c);
return c;
}
resizeCanvas = function () {
if (canvas === U) { canvas = createCanvas(); }
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
ctx = canvas.getContext("2d");
if (typeof setGlobals === "function") { setGlobals(); }
}
setGlobals = function(){ cw = (w = canvas.width) / 2; ch = (h = canvas.height) / 2; }
mouse = (function(){
function preventDefault(e) { e.preventDefault(); }
var mouse = {
x : 0, y : 0, w : 0, alt : false, shift : false, ctrl : false, buttonRaw : 0,
over : false, // mouse is over the element
bm : [1, 2, 4, 6, 5, 3], // masks for setting and clearing button raw bits;
mouseEvents : "mousemove,mousedown,mouseup,mouseout,mouseover,mousewheel,DOMMouseScroll".split(",")
};
var m = mouse;
function mouseMove(e) {
var t = e.type;
m.x = e.offsetX; m.y = e.offsetY;
if (m.x === U) { m.x = e.clientX; m.y = e.clientY; }
m.alt = e.altKey; m.shift = e.shiftKey; m.ctrl = e.ctrlKey;
if (t === "mousedown") { m.buttonRaw |= m.bm[e.which-1]; }
else if (t === "mouseup") { m.buttonRaw &= m.bm[e.which + 2]; }
else if (t === "mouseout") { m.buttonRaw = 0; m.over = false; }
else if (t === "mouseover") { m.over = true; }
else if (t === "mousewheel") { m.w = e.wheelDelta; }
else if (t === "DOMMouseScroll") { m.w = -e.detail; }
if (m.callbacks) { m.callbacks.forEach(c => c(e)); }
e.preventDefault();
}
m.addCallback = function (callback) {
if (typeof callback === "function") {
if (m.callbacks === U) { m.callbacks = [callback]; }
else { m.callbacks.push(callback); }
} else { throw new TypeError("mouse.addCallback argument must be a function"); }
}
m.start = function (element, blockContextMenu) {
if (m.element !== U) { m.removeMouse(); }
m.element = element === U ? document : element;
m.blockContextMenu = blockContextMenu === U ? false : blockContextMenu;
m.mouseEvents.forEach( n => { m.element.addEventListener(n, mouseMove); } );
if (m.blockContextMenu === true) { m.element.addEventListener("contextmenu", preventDefault, false); }
}
m.remove = function () {
if (m.element !== U) {
m.mouseEvents.forEach(n => { m.element.removeEventListener(n, mouseMove); } );
if (m.contextMenuBlocked === true) { m.element.removeEventListener("contextmenu", preventDefault);}
m.element = m.callbacks = m.contextMenuBlocked = U;
}
}
return mouse;
})();
var done = function(){
window.removeEventListener("resize",resizeCanvas)
mouse.remove();
document.body.removeChild(canvas);
canvas = ctx = mouse = U;
L("All done!")
}
resizeCanvas(); // create and size canvas
mouse.start(canvas,true); // start mouse on canvas and block context menu
window.addEventListener("resize",resizeCanvas); // add resize event
function update(timer){ // Main update loop
globalTime = timer;
display(); // call demo code
// continue until mouse right down
if (!(mouse.buttonRaw & 4)) { requestAnimationFrame(update); } else { done(); }
}
requestAnimationFrame(update);
/** SimpleFullCanvasMouse.js end **/
Why when I run this program only the picture that disappear but the position still exits?. So when i click right, left, up, down button the number of coin still increase (Collecting coin game). Please give me an explanation or example of the correct code. Thank you
//create coin
var coinReady = false;
var coinImage = new Image();
coinImage.onload = function() {
coinReady = true;
}
coinImage.src = "coin1.png";
//first coordinates of coin
var coin = {
x: 0,
y: 0
};
var position = function() {
//throw the coin somewhere on the screen randomly
coin.x = 48 + (Math.random() * (canvas.width - 750 - 96));
coin.y = 48 + (Math.random() * (canvas.height - 96));
};
//collision detection
if (char.x <= (coin.x + 48) && coin.x <= (char.x + 50) && char.y <= (coin.y + 48) && coin.y <= (char.y + 46)) {
numberCoin += 1;
position();
effectSound.play();
//draw image
if (coinReady) {
ctx.drawImage(coinImage, coin.x, coin.y);
}
//clear the image
function Clear_1() {
coinReady = false;
}
//show the coin1
function Time_coin() {
coin1Ready = true;
Clear_1();
}
//function to call Time_coin or to make coin2 exits
function timer1() {
setInterval(Time_coin, 50000);
}
var main = function() {
var now = Date.now();
var delta = now - then;
update(delta / 1000);
render();
timer1();
then = now;
//request to do this again as soon as possible
requestAnimationFrame(main);
};
//Cross-browser support for requestAnimationFrame
var w = window;
requestAnimationFrame = w.requestAnimationFrame || w.webkitRequestAnimationFrame || w.msRequestAnimationFrame || w.mozRequestAnimationFrame;
//Play the game
var then = Date.now();
position();
main();
}
The Problem
I am creating a game that involves dodging projectiles. The player is in control of an image of a ship and I dont want the ship to move exactly together as this looks very unrealistic.
The Question
Is there a way to control how fast the image moves, how can i slow the movemnt of the image down?
The Code
var game = create_game();
game.init();
//music
var snd = new Audio("Menu.mp3");
snd.loop = true;
snd.play();
document.getElementById('mute').addEventListener('click', function (evt) {
if ( snd.muted ) {
snd.muted = false
evt.target.innerHTML = 'mute'
}
else {
snd.muted = true
evt.target.innerHTML = 'unmute'
}
})
function create_game() {
debugger;
var level = 1;
var projectiles_per_level = 1;
var min_speed_per_level = 1;
var max_speed_per_level = 2;
var last_projectile_time = 0;
var next_projectile_time = 0;
var width = 600;
var height = 500;
var delay = 1000;
var item_width = 30;
var item_height = 30;
var total_projectiles = 0;
var projectile_img = new Image();
var projectile_w = 30;
var projectile_h = 30;
var player_img = new Image();
var c, ctx;
var projectiles = [];
var player = {
x: 200,
y: 400,
score: 0
};
function init() {
projectile_img.src = "projectile.png";
player_img.src = "player.png";
level = 1;
total_projectiles = 0;
projectiles = [];
c = document.getElementById("c");
ctx = c.getContext("2d");
ctx.fillStyle = "#ff6600";
ctx.fillRect(0, 0, 500, 600);
c.addEventListener("mousemove", function (e) {
//moving over the canvas.
var bounding_box = c.getBoundingClientRect();
player.x = (e.clientX - bounding_box.left) * (c.width / bounding_box.width) - player_img.width / 2;
}, false);
setupProjectiles();
requestAnimationFrame(tick);
}
function setupProjectiles() {
var max_projectiles = level * projectiles_per_level;
while (projectiles.length < max_projectiles) {
initProjectile(projectiles.length);
}
}
function initProjectile(index) {
var max_speed = max_speed_per_level * level;
var min_speed = min_speed_per_level * level;
projectiles[index] = {
x: Math.round(Math.random() * (width - 2 * projectile_w)) + projectile_w,
y: -projectile_h,
v: Math.round(Math.random() * (max_speed - min_speed)) + min_speed,
delay: Date.now() + Math.random() * delay
}
total_projectiles++;
}
function collision(projectile) {
if (projectile.y + projectile_img.height < player.y + 74) {
return false;
}
if (projectile.y > player.y + 74) {
return false;
}
if (projectile.x + projectile_img.width < player.x + 177) {
return false;
}
if (projectile.x > player.x + 177) {
return false;
}
return true;
}
function maybeIncreaseDifficulty() {
level = Math.max(1, Math.ceil(player.score / 10));
setupProjectiles();
}
function tick() {
var i;
var projectile;
var dateNow = Date.now();
c.width = c.width;
for (i = 0; i < projectiles.length; i++) {
projectile = projectiles[i];
if (dateNow > projectile.delay) {
projectile.y += projectile.v;
if (collision(projectile)) {
initProjectile(i);
player.score++;
} else if (projectile.y > height) {
initProjectile(i);
} else {
ctx.drawImage(projectile_img, projectile.x, projectile.y);
}
}
}
ctx.font = "bold 24px sans-serif";
ctx.fillStyle = "#ff6600";
ctx.fillText(player.score, c.width - 50, 50);
ctx.fillText("Level: " + level, 20, 50);
ctx.drawImage(player_img, player.x, player.y);
maybeIncreaseDifficulty();
requestAnimationFrame(tick);
}
return {
init: init
};
}
https://jsfiddle.net/a6nmy804/4/ (Broken)
Throttle the player's movement using a "timeout" countdown
Create a global var playerFreezeCountdown=0.
In mousemove change player.x only if playerFreezeCountdown<=0.
If playerFreezeCountdown>0 you don't change player.x.
If playerFreezeCountdown<=0 you both change player.x and also set playerFreezeCountdown to a desired "tick timeout" value: playerFreezeCountdown=5. This timeout will cause prevent the player from moving their ship until 5 ticks have passed.
In tick, always decrement playerFreezeCountdown--. This will indirectly allow a change to player.x after when playerFreezeCountdown is decremented to zero or below zero.
I need to upload the image onto the canvas, but the image keeps on coming beside the canvas instead of inside it. I made a code for that to happen but does not work. Thanks in advance.
Js:
//Link Canvas
var canvas = document.getElementById('gameCanvas');
var context = canvas.getContext('2d');
var width = $('#gameCanvas').width();
var height = $('#gameCanvas').height();
//Car Image
var car = new Image();
car.src = "http://images.clipartpanda.com/car-top-view-clipart-red-racing-car-top-view-fe3a.png";
//Car x,y Position
var x = 220;
var y = 200;
//Car Speed and angle
var speed = 7;
var angle = 0;
var mod = 0;
//Keyboard Listeners
window.addEventListener("keydown", keypress_handler, false);
window.addEventListener("keyup", keyup_handler, false);
var moveInterval = setInterval(function () {
draw();
}, 30);
//Draw Car
function draw() {
context.clearRect(0, 0, canvas.width, canvas.height);
//Rotate Car When Turning
x += (speed * mod) * Math.cos(Math.PI / 180 * angle);
y += (speed * mod) * Math.sin(Math.PI / 180 * angle);
context.save();
context.translate(x, y);
context.rotate(Math.PI / 180 * angle);
context.drawImage(car, -(car.width / 2), -(car.height / 2));
context.restore();
}
//Keyboard Function
function keyup_handler(event) {
console.log('a');
if (event.keyCode == 38 || event.keyCode == 40) {
mod = 0;
}
}
//Keyboard keys to operate car
function keypress_handler(event) {
console.log(event.keyCode);
if (event.keyCode == 38) { //Up arrow
mod = 1;
}
if (event.keyCode == 40) { //Down arrow
mod = -1;
}
if (event.keyCode == 37) { //Left Arrow
angle -= 5;
}
if (event.keyCode == 39) { //Right Arrow
angle += 5;
}
}
function update() {
window.requestAnimationFrame(update);
x += speed;
y += speed;
if (x >= $('#gameCanvas')){
speed = 0;
}
if (y >= $('#gameCanvas')){
speed = -1.0 * speed;
speed = 0;
}
}
Code That does not work:
var URL = [
"http://thumb101.shutterstock.com/display_pic_with_logo/69386/69386,1162932792,3/stock-photo-lone-car-in-four-lanes-from-above-2128171.jpg",
];
var canvas
var imgs = URL.map(function(URL) {
var img = new Image();
img.src = URL;
document.body.appendChild(img);
return img;
});
var canvas = document.getElementById("canvas"),
ctx = canvas.getContext("2d");
var background = new Image();
background.src = "http://thumb101.shutterstock.com/display_pic_with_logo/69386/69386,1162932792,3/stock-photo-lone-car-in-four-lanes-from-above-2128171.jpg";
// Make sure the image is loaded first otherwise nothing will draw.
background.onload = function(){
ctx.drawImage(background,0,0);
}
var background = new Image();
background.src = "http://thumb101.shutterstock.com/display_pic_with_logo/69386/69386,1162932792,3/stock-photo-lone-car-in-four-lanes-from-above-2128171.jpg";
// Make sure the image is loaded first otherwise nothing will draw.
background.onload = function(){
context.drawImage(background,0,0);
}