Related
I am trying to add a colour gradient to the canvas text in this code but nothing I've tried works.
I am new to this so am having difficulties finding the solution.
Is this effect even possible? I have found the code to change the text colour using
ctx.fillStyle = gradient;
but it doesn't seem to be working. I'm not even sure where to insert it.
Does anyone know how to achieve this?
window.onresize = function() {
resize();
return true;
};
var pixels = []
var canv = $('canv')
var ctx = canv.getContext('2d')
var wordCanv = $('wordCanv')
var wordCtx = wordCanv.getContext('2d')
var mx = -1
var my = -1
var words = ''
var txt = []
var cw = 0
var ch = 0
var resolution = 1
var n = 0
var timerRunning = false
var resHalfFloor = 0
var resHalfCeil = 0
var width = 600
var height = 600
function canv_mousemove(evt) {
mx = evt.clientX - canv.offsetLeft
my = evt.clientY - canv.offsetTop
}
function Pixel(homeX, homeY) {
this.homeX = homeX
this.homeY = homeY
this.x = Math.random() * cw
this.y = Math.random() * ch
this.xVelocity = Math.random() * 10 - 5
this.yVelocity = Math.random() * 10 - 5
}
Pixel.prototype.move = function() {
var homeDX = this.homeX - this.x
var homeDY = this.homeY - this.y
var homeDistance = Math.sqrt(Math.pow(homeDX, 2) + Math.pow(homeDY, 2))
var homeForce = homeDistance * 0.01
var homeAngle = Math.atan2(homeDY, homeDX)
var cursorForce = 0
var cursorAngle = 0
if (mx >= 0) {
var cursorDX = this.x - mx
var cursorDY = this.y - my
var cursorDistanceSquared = Math.pow(cursorDX, 2) + Math.pow(cursorDY, 2)
cursorForce = Math.min(10000 / cursorDistanceSquared, 10000)
cursorAngle = Math.atan2(cursorDY, cursorDX)
} else {
cursorForce = 0
cursorAngle = 0
}
this.xVelocity +=
homeForce * Math.cos(homeAngle) + cursorForce * Math.cos(cursorAngle)
this.yVelocity +=
homeForce * Math.sin(homeAngle) + cursorForce * Math.sin(cursorAngle)
this.xVelocity *= 0.92
this.yVelocity *= 0.92
this.x += this.xVelocity
this.y += this.yVelocity
}
function $(id) {
return document.getElementById(id)
}
function timer() {
if (!timerRunning) {
timerRunning = true
setTimeout(timer, 33)
for (var i = 0; i < pixels.length; i++) {
pixels[i].move()
}
drawPixels()
n++
if (
n % 10 == 0 &&
(cw != width || ch != height)
)
body_resize()
timerRunning = false
} else {
setTimeout(timer, 5)
}
}
function drawPixels() {
var imageData = ctx.createImageData(cw, ch)
var actualData = imageData.data
var index
var goodX
var goodY
var realX
var realY
for (var i = 0; i < pixels.length; i++) {
goodX = Math.floor(pixels[i].x)
goodY = Math.floor(pixels[i].y)
for (
realX = goodX - resHalfFloor; realX <= goodX + resHalfCeil && realX >= 0 && realX < cw; realX++
) {
for (
realY = goodY - resHalfFloor; realY <= goodY + resHalfCeil && realY >= 0 && realY < ch; realY++
) {
index = (realY * imageData.width + realX) * 4
actualData[index + 3] = 255
}
}
}
imageData.data = actualData
ctx.putImageData(imageData, 0, 0)
}
function readWords() {
var randomWords = ['Text goes here', 'Text 2 goe ']
words = item = randomWords[Math.floor(Math.random() * randomWords.length)]
txt = words.split('\n')
}
function init() {
readWords()
var fontSize = 100
var wordWidth = 0
do {
wordWidth = 0
fontSize -= 5
wordCtx.font = fontSize + 'px sans-serif'
for (var i = 0; i < txt.length; i++) {
var w = wordCtx.measureText(txt[i]).width
if (w > wordWidth) wordWidth = w
}
} while (wordWidth > cw - 50 || fontSize * txt.length > ch - 50)
wordCtx.clearRect(0, 0, cw, ch)
wordCtx.textAlign = 'center'
wordCtx.textBaseline = 'middle'
for (var i = 0; i < txt.length; i++) {
wordCtx.fillText(
txt[i],
cw / 2,
ch / 2 - fontSize * (txt.length / 2 - (i + 0.5))
)
}
var index = 0
var imageData = wordCtx.getImageData(0, 0, cw, ch)
for (var x = 0; x < imageData.width; x += resolution) {
for (var y = 0; y < imageData.height; y += resolution) {
i = (y * imageData.width + x) * 4
if (imageData.data[i + 3] > 128) {
if (index >= pixels.length) {
pixels[index] = new Pixel(x, y)
} else {
pixels[index].homeX = x
pixels[index].homeY = y
}
index++
}
}
}
pixels.splice(index, pixels.length - index)
}
function body_resize() {
cw = width
ch = height
canv.width = cw
canv.height = ch
wordCanv.width = cw
wordCanv.height = ch
init()
}
resHalfFloor = Math.floor(resolution / 2)
resHalfCeil = Math.ceil(resolution / 2)
body_resize()
timer()
setInterval(init, 3000)
<canvas id="wordCanv" width="100%" height="600px" style="border:10px solid rgb(255,255,255);display:none;">
</canvas>
<canvas id="canv" onmousemove="canv_mousemove(event);" onmouseout="mx=-1;my=-1;" width="100%" height="600px">
</canvas>
It is not clear what kind of gradient effect you want to achieve...
So I guess that any will get you moving, see code below
I just added this:
actualData[index + 1] = realX % 255
in your function drawPixels
Play with those values until you get the desired combination
I'm assuming you are familiar with ImageData if not read more here:
https://developer.mozilla.org/en-US/docs/Web/API/ImageData
https://developer.mozilla.org/en-US/docs/Web/API/ImageData/data
var pixels = []
var canv = $('canv')
var ctx = canv.getContext('2d')
var wordCanv = $('wordCanv')
var wordCtx = wordCanv.getContext('2d')
var mx = -1
var my = -1
var words = ''
var txt = []
var cw = 0
var ch = 0
var resolution = 1
var n = 0
var timerRunning = false
var resHalfFloor = 0
var resHalfCeil = 0
var width = 560
var height = 200
function canv_mousemove(evt) {
mx = evt.clientX - canv.offsetLeft
my = evt.clientY - canv.offsetTop
}
function Pixel(homeX, homeY) {
this.homeX = homeX
this.homeY = homeY
this.x = Math.random() * cw
this.y = Math.random() * ch
this.xVelocity = Math.random() * 10 - 5
this.yVelocity = Math.random() * 10 - 5
}
Pixel.prototype.move = function() {
var homeDX = this.homeX - this.x
var homeDY = this.homeY - this.y
var homeDistance = Math.sqrt(Math.pow(homeDX, 2) + Math.pow(homeDY, 2))
var homeForce = homeDistance * 0.01
var homeAngle = Math.atan2(homeDY, homeDX)
var cursorForce = 0
var cursorAngle = 0
if (mx >= 0) {
var cursorDX = this.x - mx
var cursorDY = this.y - my
var cursorDistanceSquared = Math.pow(cursorDX, 2) + Math.pow(cursorDY, 2)
cursorForce = Math.min(10000 / cursorDistanceSquared, 10000)
cursorAngle = Math.atan2(cursorDY, cursorDX)
} else {
cursorForce = 0
cursorAngle = 0
}
this.xVelocity +=
homeForce * Math.cos(homeAngle) + cursorForce * Math.cos(cursorAngle)
this.yVelocity +=
homeForce * Math.sin(homeAngle) + cursorForce * Math.sin(cursorAngle)
this.xVelocity *= 0.92
this.yVelocity *= 0.92
this.x += this.xVelocity
this.y += this.yVelocity
}
function $(id) {
return document.getElementById(id)
}
function timer() {
if (!timerRunning) {
timerRunning = true
setTimeout(timer, 33)
for (var i = 0; i < pixels.length; i++) {
pixels[i].move()
}
drawPixels()
n++
if (
n % 10 == 0 &&
(cw != width || ch != height)
)
body_resize()
timerRunning = false
} else {
setTimeout(timer, 5)
}
}
function drawPixels() {
var imageData = ctx.createImageData(cw, ch)
var actualData = imageData.data
var index
var goodX
var goodY
var realX
var realY
for (var i = 0; i < pixels.length; i++) {
goodX = Math.floor(pixels[i].x)
goodY = Math.floor(pixels[i].y)
for (
realX = goodX - resHalfFloor; realX <= goodX + resHalfCeil && realX >= 0 && realX < cw; realX++
) {
for (
realY = goodY - resHalfFloor; realY <= goodY + resHalfCeil && realY >= 0 && realY < ch; realY++
) {
index = (realY * imageData.width + realX) * 4
actualData[index + 1] = realX % 255
actualData[index + 3] = 255
}
}
}
imageData.data = actualData
ctx.putImageData(imageData, 0, 0)
}
function readWords() {
var randomWords = ['Text 4 foo ', 'Text 2 goe ']
words = item = randomWords[Math.floor(Math.random() * randomWords.length)]
txt = words.split('\n')
}
function init() {
readWords()
var fontSize = 80
var wordWidth = 0
wordCtx.font = fontSize + 'px sans-serif'
do {
wordWidth = 0
fontSize -= 10
for (var i = 0; i < txt.length; i++) {
var w = wordCtx.measureText(txt[i]).width
if (w > wordWidth) wordWidth = w
}
} while (wordWidth > cw - 50 || fontSize * txt.length > ch - 50)
wordCtx.clearRect(0, 0, cw, ch)
wordCtx.textAlign = 'center'
wordCtx.textBaseline = 'middle'
for (var i = 0; i < txt.length; i++) {
wordCtx.fillText(
txt[i],
cw / 2,
ch / 2 - fontSize * (txt.length / 2 - (i + 0.5))
)
}
var index = 0
var imageData = wordCtx.getImageData(0, 0, cw, ch)
for (var x = 0; x < imageData.width; x += resolution) {
for (var y = 0; y < imageData.height; y += resolution) {
i = (y * imageData.width + x) * 4
if (imageData.data[i + 3] > 128) {
if (index >= pixels.length) {
pixels[index] = new Pixel(x, y)
} else {
pixels[index].homeX = x
pixels[index].homeY = y
}
index++
}
}
}
pixels.splice(index, pixels.length - index)
}
function body_resize() {
cw = width
ch = height
canv.width = cw
canv.height = ch
wordCanv.width = cw
wordCanv.height = ch
init()
}
resHalfFloor = Math.floor(resolution / 2)
resHalfCeil = Math.ceil(resolution / 2)
body_resize()
timer()
setInterval(init, 3000)
<canvas id="wordCanv" width="100%" height="200px" style="display:none;">
</canvas>
<canvas id="canv" width="100%" height="200px">
</canvas>
I am working on a college project that requires me to build a 2D game in javascript. A problem that I'm having at the moment is that it cannot read the 'addEventListener'. This error has caused my game to not work completely.
document.getElementById('restart').addEventListener('click', startGame);
Here is the full code that I have used. The error is down the very bottom.
(function()
{
//Define variables
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
var player, score, stop, ticker;
var ground = [], water = [], enemies = [], environment = [];
//Platform variables
var platformHeight, platformLength, gapLength;
var platformWidth = 32;
var platformBase = canvas.height - platformWidth;
var platformSpacer = 64;
//Randomly generates a number
function random(low, high)
{
return Math.floor(Math.random() * (high - low + 1) + low);
}
//Bounds a number
function bound(num, low, high)
{
return Math.max(Math.min(num, high), low);
}
//Loads all of the assets
var assetLoader = (function()
{
this.imgs = {
'bg' : 'Images/bg.png',
'sky' : 'Images/sky.png',
'backdrop' : 'Images/backdrop.png',
'backdrop2' : 'Images/backdrop_ground.png',
'grass' : 'Images/grass.png',
'avatar_normal' : 'Images/normal_walk.png',
'water' : 'imgs/water.png',
'grass1' : 'imgs/grassMid1.png',
'grass2' : 'imgs/grassMid2.png',
'bridge' : 'imgs/bridge.png',
'plant' : 'imgs/plant.png',
'bush1' : 'imgs/bush1.png',
'bush2' : 'imgs/bush2.png',
'cliff' : 'imgs/grassCliffRight.png',
'spikes' : 'imgs/spikes.png',
'box' : 'imgs/boxCoin.png',
'slime' : 'imgs/slime.png'
};
var assetsLoaded = 0; //How many assets have been loaded
var numImgs = Object.keys(this.imgs).length; //Total number of image assets
this.totalAssest = numImgs; //Total number of assets
function assetLoaded(dic, name)
{
if(this[dic][name].status !== 'loading')
{
return;
}
this[dic][name].status = 'loaded';
assetsLoaded++;
if(assetsLoaded === this.totalAssest && typeof this.finished === 'function')
{
this.finished();
}
}
this.downloadAll = function()
{
var _this = this;
var src;
for (var img in this.imgs)
{
if (this.imgs.hasOwnProperty(img))
{
src = this.imgs[img];
(function(_this, img)
{
_this.imgs[img] = new Image();
_this.imgs[img].status = 'loading';
_this.imgs[img].name = img;
_this.imgs[img].onload = function() {assetLoaded.call(_this, 'imgs', img)};
_this.imgs[img].src = src;
})(_this, img);
}
}
}
return{
imgs: this.imgs,
totalAssest: this.totalAssest,
downloadAll: this.downloadAll
};
})();
assetLoader.finished = function()
{
startGame();
}
function SpriteSheet(path, frameWidth, frameHeight)
{
this.image = new Image();
this.frameWidth = frameWidth;
this.frameHeight = frameHeight;
var self = this;
this.image.onload = function()
{
self.framesPerRow = Math.floor(self.image.width / self.frameWidth);
};
this.image.src = path;
}
function Animation(spritesheet, frameSpeed, startFrame, endFrame)
{
var animationSequence = [];
var currentFrame = 0;
var counter = 0;
for (var frameNumber = startFrame; frameNumber <= endFrame; frameNumber++)
{
animationSequence.push(frameNumber);
}
this.update = function()
{
if (counter == (frameSpeed - 1))
{
currentFrame = (currentFrame + 1) % animationSequence.length;
}
counter = (counter + 1) % frameSpeed;
};
this.draw = function(x, y)
{
var row = Math.floor(animationSequence[currentFrame] / spritesheet.framesPerRow);
var col = Math.floor(animationSequence[currentFrame] % spritesheet.framesPerRow);
ctx.drawImage
(
spritesheet.image,
col * spritesheet.frameWidth, row * spritesheet.frameHeight,
spritesheet.frameWidth, spritesheet.frameHeight,
x, y,
spritesheet.frameWidth, spritesheet.frameHeight);
};
}
var background = (function()
{
var sky = {};
var backdrop = {};
var backdrop2 = {};
this.draw = function()
{
ctx.drawImage(assetLoader.imgs.bg, 0, 0);
sky.x -= sky.speed;
backdrop.x -= backdrop.speed;
backdrop2.x -= backdrop2.speed;
ctx.drawImage(assetLoader.imgs.sky, sky.x, sky.y);
ctx.drawImage(assetLoader.imgs.sky, sky.x + canvas.width, sky.y);
ctx.drawImage(assetLoader.imgs.backdrop, backdrop.x, backdrop.y);
ctx.drawImage(assetLoader.imgs.backdrop, backdrop.x + canvas.width, backdrop.y);
ctx.drawImage(assetLoader.imgs.backdrop2, backdrop2.x, backdrop2.y);
ctx.drawImage(assetLoader.imgs.backdrop2, backdrop2.x + canvas.width, backdrop2.y);
if (sky.x + assetLoader.imgs.sky.width <= 0)
{
sky.x = 0;
}
if (backdrop.x + assetLoader.imgs.backdrop.width <= 0)
{
backdrop.x = 0;
}
if (backdrop2.x + assetLoader.imgs.backdrop2.width <= 0)
{
backdrop2.x = 0;
}
};
this.reset = function()
{
sky.x = 0;
sky.y = 0;
sky.speed = 0.2;
backdrop.x = 0;
backdrop.y = 0;
backdrop.speed = 0.4;
backdrop2.x = 0;
backdrop2.y = 0;
backdrop2.speed = 0.6;
}
return{
draw: this.draw,
reset: this.reset
};
})();
//A vector for 2D space
function Vector(x, y, dx, dy)
{
// position
this.x = x || 0;
this.y = y || 0;
// direction
this.dx = dx || 0;
this.dy = dy || 0;
}
//Advances the vector's position
Vector.prototype.advance = function()
{
this.x += this.dx;
this.y += this.dy;
};
//Gets the minimum distance between two vectors
Vector.prototype.minDist = function(vec)
{
var minDist = Infinity;
var max = Math.max(Math.abs(this.dx), Math.abs(this.dy),Math.abs(vec.dx), Math.abs(vec.dy));
var slice = 1 / max;
var x, y, distSquared;
// get the middle of each vector
var vec1 = {}, vec2 = {};
vec1.x = this.x + this.width/2;
vec1.y = this.y + this.height/2;
vec2.x = vec.x + vec.width/2;
vec2.y = vec.y + vec.height/2;
for(var percent = 0; percent < 1; percent += slice)
{
x = (vec1.x + this.dx * percent) - (vec2.x + vec.dx * percent);
y = (vec1.y + this.dy * percent) - (vec2.y + vec.dy * percent);
distSquared = x * x + y * y;
minDist = Math.min(minDist, distSquared);
}
return Math.sqrt(minDist);
};
//The player object
var player = (function(player)
{
//Player properties
player.width = 60;
player.height = 96;
player.speed = 6;
//Jumping
player.gravity = 1;
player.dy = 0;
player.jumpDy = -10;
player.isFalling = false;
player.isJumping = false;
//Spritesheets
player.sheet = new SpriteSheet('Images/normal_walk.png', player.width, player.height);
player.walkAnim = new Animation(player.sheet, 4, 0, 15);
player.jumpAnim = new Animation(player.sheet, 4, 15, 15);
player.fallAnim = new Animation(player.sheet, 4, 11, 11);
player.anim = player.walkAnim;
Vector.call(player, 0, 0, 0, player.dy);
var jumpCounter = 0;
player.update = function()
{
//Jump if not currently jumping or falling
if(KEY_STATUS.space && player.dy === 0 && !player.isJumping)
{
player.isJumping = true;
player.dy = player.jumpDy;
jumpCounter = 12;
}
//Jump higher if the spacebar is continually pressed
if(KEY_STATUS.space && jumpCounter)
{
player.dy = player.jumpDy;
}
jumpCounter = Math.max(jumpCounter - 1, 0);
this.advance();
//Gravity
if(player.isFalling || player.isJumping)
{
player.dy += player.gravity;
}
//Falling Animation
if(player.dy > 0)
{
player.anim = player.fallAnim;
}
// change animation is jumping
else if(player.dy < 0)
{
player.anim = player.jumpAnim;
}
else
{
player.anim = player.walkAnim;
}
player.anim.update();
};
//Draw the player's current position
player.draw = function()
{
player.anim.draw(player.x, player.y);
};
//Resets the player's position
player.reset = function()
{
player.x = 64;
player.y = 250;
};
return player;
})(Object.create(Vector.prototype));
//Sprites
function Sprite(x, y, type)
{
this.x = x;
this.y = y;
this.width = platformWidth;
this.height = platformWidth;
this.type = type;
Vector.call(this, x, y, 0, 0);
//Updating the sprites
this.update = function()
{
this.dx = -player.speed;
this.advancer();
}
//Drawing the sprites
this.draw = function()
{
ctx.save();
ctx.translate(0.5, 0.5);
ctx.drawImage(assetLoader.imgs[this.type], this.x, this.y);
ctx.restore();
}
}
Sprite.prototype = Object.create(Vector.prototype);
//Platforms
function getType()
{
var type;
switch(platformHeight)
{
case 0:
case 1:
type = Math.random() > 0.5 ? 'grass1' : 'grass2';
break;
case 2:
type = 'grass';
break;
case 3:
type = 'bridge';
break;
case 4:
type = 'box';
break;
}
if (platformLength === 1 && platformHeight < 3 && rand(0, 3) === 0)
{
type = 'cliff';
}
return type;
}
//Update and draw all ground positions
function updateGround()
{
//Animate ground
player.isFalling = true;
for(var i = 0; i < ground.length; i++)
{
ground[i].update();
ground[i].draw();
//Stop the player going through the platforms when landing
var angle;
if(player.minDist(ground[i]) <= player.height/2 + platformWidth/2 && (angle = Math.atan2(player.y - ground[i].y, player.x - ground[i].x) * 180/Math.PI) > -130 &&angle < -50)
{
player.isJumping = false;
player.isFalling = false;
player.y = ground[i].y - player.height + 5;
player.dy = 0;
}
}
//Remove the ground that has gone off screen
if(ground[0] && ground[0].x < -platformWidth)
{
ground.splice(0, 1);
}
}
//Update and draw all water positions
function updateWater()
{
//Animate water
for(var i = 0; i < water.length; i++)
{
water[i].update();
water[i].draw();
}
//Remove water that has gone off screen
if (water[0] && water[0].x < -platformWidth)
{
var w = water.splice(0, 1)[0];
w.x = water[water.length-1].x + platformWidth;
water.push(w);
}
}
//Update and draw all environment positions
function updateEnvironment()
{
//Animate environment
for(var i = 0; i < environment.length; i++)
{
environment[i].update();
environment[i].draw();
}
//R emove environment that have gone off screen
if(environment[0] && environment[0].x < -platformWidth)
{
environment.splice(0, 1);
}
}
//Update and draw all enemies position. Also check for collision against the player.
function updateEnemies()
{
//Animate enemies
for(var i = 0; i < enemies.length; i++)
{
enemies[i].update();
enemies[i].draw();
//Player ran into enemy
if(player.minDist(enemies[i]) <= player.width - platformWidth/2)
{
gameOver();
}
}
//Remove enemies that have gone off screen
if(enemies[0] && enemies[0].x < -platformWidth)
{
enemies.splice(0, 1);
}
}
//Update and draw the players position
function updatePlayer()
{
player.update();
player.draw();
//Game over
if(player.y + player.height >= canvas.height)
{
gameOver();
}
}
//Spawn new sprites off screen
function spawnSprites()
{
//Increase score
score++;
//First create a gap
if(gapLength > 0)
{
gapLength--;
}
//Then create the ground
else if(platformLength > 0)
{
var type = getType();
ground.push(new Sprite(
canvas.width + platformWidth % player.speed,
platformBase - platformHeight * platformSpacer,
type
));
platformLength--;
//Add random environment sprites
spawnEnvironmentSprites();
//Add random enemies
spawnEnemySprites();
}
//Start over
else
{
//Increase gap length every speed increase of 4
gapLength = rand(player.speed - 2, player.speed);
// only allow a ground to increase by 1
platformHeight = bound(rand(0, platformHeight + rand(0, 2)), 0, 4);
platformLength = rand(Math.floor(player.speed/2), player.speed * 4);
}
}
//Spawn new environment sprites off screen
function spawnEnvironmentSprites()
{
if(score > 40 && rand(0, 20) === 0 && platformHeight < 3)
{
if (Math.random() > 0.5)
{
environment.push(new Sprite(canvas.width + platformWidth % player.speed, platformBase - platformHeight * platformSpacer - platformWidth, 'plant'));
}
else if(platformLength > 2)
{
environment.push(new Sprite(canvas.width + platformWidth % player.speed, platformBase - platformHeight * platformSpacer - platformWidth, 'bush1'));
environment.push(new Sprite(canvas.width + platformWidth % player.speed + platformWidth, platformBase - platformHeight * platformSpacer - platformWidth, 'bush2'));
}
}
}
//Spawn new enemy sprites off screen
function spawnEnemySprites()
{
if(score > 100 && Math.random() > 0.96 && enemies.length < 3 && platformLength > 5 && (enemies.length ? canvas.width - enemies[enemies.length-1].x >= platformWidth * 3 || canvas.width - enemies[enemies.length-1].x < platformWidth : true))
{
enemies.push(new Sprite(canvas.width + platformWidth % player.speed, platformBase - platformHeight * platformSpacer - platformWidth, Math.random() > 0.5 ? 'spikes' : 'slime'));
}
}
//Game Loop
function animate()
{
if(!stop)
{
requestAnimFrame(animate);
ctx.clearRect(0, 0, canvas.width, canvas.height);
background.draw();
//Update entities
updateWater();
updateEnvironment();
updatePlayer();
updateGround();
updateEnemies();
//Draw the score
ctx.fillText('Score: ' + score + 'm', canvas.width - 140, 30);
//Spawn a new Sprite
if(ticker % Math.floor(platformWidth / player.speed) === 0)
{
spawnSprites();
}
//Increase player's speed only when player is jumping
if(ticker > (Math.floor(platformWidth / player.speed) * player.speed * 20) && player.dy !== 0)
{
player.speed = bound(++player.speed, 0, 15);
player.walkAnim.frameSpeed = Math.floor(platformWidth / player.speed) - 1;
//Reset ticker
ticker = 0;
//Spawn a platform to fill in gap created by increasing player speed
if(gapLength === 0)
{
var type = getType();
ground.push(new Sprite(canvas.width + platformWidth % player.speed, platformBase - platformHeight * platformSpacer, type));
platformLength--;
}
}
ticker++;
}
}
//Spacebar events
var KEY_CODES = {
32: 'space'
};
var KEY_STATUS = {};
for(var code in KEY_CODES)
{
if(KEY_CODES.hasOwnProperty(code))
{
KEY_STATUS[KEY_CODES[code]] = false;
}
}
document.onkeydown - function(e)
{
var keyCode = (e.keyCode) ? e.keyCode : e.charCode;
if(KEY_CODES[keyCode])
{
e.preventDefault();
KEY_STATUS[KEY_CODES[keyCode]] = true;
}
};
document.onkeydown - function(e)
{
var keyCode = (e.keyCode) ? e.keyCode : e.charCode;
if(KEY_CODES[keyCode])
{
e.preventDefault();
KEY_STATUS[KEY_CODES[keyCode]] = false;
}
};
//Request Animation Polyfill
var requestAnimFrame = (function()
{
return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame || function(callback, element)
{
window.setTimeout(callback, 1000 / 60);
};
})();
//Start the game and resets all variables and entities, spawn ground and water.
function startGame()
{
document.getElementById('game-over').style.display = 'none';
ground = [];
water = [];
environment = [];
enemies = [];
player.reset();
ticker = 0;
stop = false;
score = 0;
platformHeight = 2;
platformLength = 15;
gapLength = 0;
ctx.font = '16px arial, sans-serif';
for (var i = 0; i < 30; i++)
{
ground.push(new Sprite(i * (platformWidth-3), platformBase - platformHeight * platformSpacer, 'grass'));
}
for (i = 0; i < canvas.width / 32 + 2; i++)
{
water.push(new Sprite(i * platformWidth, platformBase, 'water'));
}
background.reset();
animate();
}
//End the game and restart
function gameOver()
{
stop = true;
document.getElementById('game-over').style.display = 'block';
}
document.getElementById('restart').addEventListener('click', startGame);
assetLoader.downloadAll();
})();
I have tried to put a start button to my game or a start menu , but every time I try something my game stops working , I have tried a lot of stuffs that I have found online but every time it do-sent work and my game just disappear.
My game is a Snake game in javascript ,that I am trying to insert in my web page, I have found the script online I am not very good in coding. I have just started.
I know some things and I am learning every day but I still consider my self a noob.
So this is the script
i wana put the start button in front of the game
my script begin by // body onload="init()"
the body onload , i dont have see it in the examples that i had see online
function init() {
var ctx;
var turn = [];
var xV = [-1, 0, 1, 0];
var yV = [0, -1, 0, 1];
var queue = [];
var elements = 1;
var map = [];
var X = 5 + (Math.random() * (45 - 10)) | 0;
var Y = 5 + (Math.random() * (30 - 10)) | 0;
var direction = Math.random() * 3 | 0;
var interval = 0;
var score = 0;
var inc_score = 50;
var sum = 0, easy = 0;
var i, dir;
var canvas = document.createElement('canvas');
for (i = 0; i < 45; i++) {
map[i] = [];
}
canvas.setAttribute('width', 45 * 10);
canvas.setAttribute('height', 30 * 10);
ctx = canvas.getContext('2d');
document.body.appendChild(canvas);
function placeFood() {
var x, y;
do {
x = Math.random() * 45 | 0;
y = Math.random() * 30 | 0;
} while (map[x][y]);
map[x][y] = 1;
ctx.strokeRect(x * 10 + 1, y * 10 + 1, 10 - 2, 10 - 2);
}
placeFood();
function clock() {
if (easy) {
X = (X + 45) % 45;
Y = (Y + 30) % 30;
}
--inc_score;
if (turn.length) {
dir = turn.pop();
if ((dir % 2) !== (direction % 2)) {
direction = dir;
}
}
if (
(easy || (0 <= X && 0 <= Y && X < 45 && Y < 30))
&& 2 !== map[X][Y]) {
if (1 === map[X][Y]) {
score += Math.max(5, inc_score);
inc_score = 50;
placeFood();
elements++;
}
ctx.fillRect(X * 10, Y * 10, 10 - 1, 10 - 1);
map[X][Y] = 2;
queue.unshift([X, Y]);
X += xV[direction];
Y += yV[direction];
if (elements < queue.length) {
dir = queue.pop()
map[dir[0]][dir[1]] = 0;
ctx.clearRect(dir[0] * 10, dir[1] * 10, 10, 10);
}
} else if (!turn.length) {
if (confirm("nice try,keep winning satoshis ! Play again? Your Score is " + score)) {
ctx.clearRect(0, 0, 450, 300);
queue = [];
elements = 1;
map = [];
X = 5 + (Math.random() * (45 - 10)) | 0;
Y = 5 + (Math.random() * (30 - 10)) | 0;
direction = Math.random() * 3 | 0;
score = 0;
inc_score = 50;
for (i = 0; i < 45; i++) {
map[i] = [];
}
placeFood();
} else {
window.clearInterval(interval);
window.location = "/projects/";
}
}
}
interval = window.setInterval(clock, 60);
document.onkeydown = function (e) {
var code = e.keyCode - 37;
/*
* 0: left
* 1: up
* 2: right
* 3: down
**/
if (0 <= code && code < 4 && code !== turn[0]) {
turn.unshift(code);
} else if (-5 == code) {
if (interval) {
window.clearInterval(interval);
interval = null;
} else {
interval = window.setInterval(clock, 60);
}
} else { // O.o
dir = sum + code;
if (dir == 44 || dir == 94 || dir == 126 || dir == 171) {
sum += code
} else if (dir === 218) easy = 1;
}
}
}
Is this good?
<head>
<title></title>
<script src="https://code.jquery.com/jquery-3.1.1.slim.min.js"></script>
<style>
canvas {
border: 1px solid;
}
#btn {
position: absolute;
right: 0;
}
</style>
</head>
<body>
<input type="button" value="Start" onclick="init()" id="btn" />
<script>
function init()
{
var ctx;
var turn = [];
var xV = [-1, 0, 1, 0];
var yV = [0, -1, 0, 1];
var queue = [];
var elements = 1;
var map = [];
var X = 5 + (Math.random() * (45 - 10)) | 0;
var Y = 5 + (Math.random() * (30 - 10)) | 0;
var direction = Math.random() * 3 | 0;
var interval = 0;
var score = 0;
var inc_score = 50;
var sum = 0, easy = 0;
var i, dir;
var canvas = document.createElement('canvas');
for (i = 0; i < 45; i++)
{
map[i] = [];
}
canvas.setAttribute('width', 45 * 10);
canvas.setAttribute('height', 30 * 10);
ctx = canvas.getContext('2d');
document.body.appendChild(canvas);
function placeFood()
{
var x, y;
do
{
x = Math.random() * 45 | 0;
y = Math.random() * 30 | 0;
} while (map[x][y]);
map[x][y] = 1;
ctx.strokeRect(x * 10 + 1, y * 10 + 1, 10 - 2, 10 - 2);
}
placeFood();
function clock()
{
if (easy)
{
X = (X + 45) % 45;
Y = (Y + 30) % 30;
}
--inc_score;
if (turn.length)
{
dir = turn.pop();
if ((dir % 2) !== (direction % 2))
{
direction = dir;
}
}
if (
(easy || (0 <= X && 0 <= Y && X < 45 && Y < 30))
&& 2 !== map[X][Y])
{
if (1 === map[X][Y])
{
score += Math.max(5, inc_score);
inc_score = 50;
placeFood();
elements++;
}
ctx.fillRect(X * 10, Y * 10, 10 - 1, 10 - 1);
map[X][Y] = 2;
queue.unshift([X, Y]);
X += xV[direction];
Y += yV[direction];
if (elements < queue.length)
{
dir = queue.pop()
map[dir[0]][dir[1]] = 0;
ctx.clearRect(dir[0] * 10, dir[1] * 10, 10, 10);
}
} else if (!turn.length)
{
if (confirm("nice try,keep winning satoshis ! Play again? Your Score is " + score))
{
ctx.clearRect(0, 0, 450, 300);
queue = [];
elements = 1;
map = [];
X = 5 + (Math.random() * (45 - 10)) | 0;
Y = 5 + (Math.random() * (30 - 10)) | 0;
direction = Math.random() * 3 | 0;
score = 0;
inc_score = 50;
for (i = 0; i < 45; i++)
{
map[i] = [];
}
placeFood();
} else
{
window.clearInterval(interval);
window.location = "/projects/";
}
}
}
interval = window.setInterval(clock, 60);
document.onkeydown = function (e)
{
var code = e.keyCode - 37;
if (0 <= code && code < 4 && code !== turn[0])
{
turn.unshift(code);
} else if (-5 == code)
{
if (interval)
{
window.clearInterval(interval);
interval = null;
} else
{
interval = window.setInterval(clock, 60);
}
} else
{ // O.o
dir = sum + code;
if (dir == 44 || dir == 94 || dir == 126 || dir == 171)
{
sum += code
} else if (dir === 218) easy = 1;
}
}
}
</script>
</body>
I'm trying to give each of the falling objects a gradient to make them look like shiny gold tickets.
I have a Codepen
I forked the pen from another repo and all i've changed in the background colour and the ticket colour.
This is the part of the code that control the colour. How do I add the gradient?
var colorThemes = [
function() {
//return color(200 * random()|0, 200 * random()|0, 200 * random()|0);
return color(218,165,32);
}, function() {
var black = 200 * random()|0; return color(200, black, black);
}, function() {
var black = 200 * random()|0; return color(black, 200, black);
}, function() {
var black = 200 * random()|0; return color(black, black, 200);
}, function() {
return color(200, 100, 200 * random()|0);
}, function() {
return color(200 * random()|0, 200, 200);
}, function() {
var black = 256 * random()|0; return color(black, black, black);
}, function() {
return colorThemes[random() < .5 ? 1 : 2]();
}, function() {
return colorThemes[random() < .5 ? 3 : 5]();
}, function() {
return colorThemes[random() < .5 ? 2 : 4]();
}
];
function color(r, g, b) {
return 'rgb(' + r + ',' + g + ',' + b + ')';
}
'use strict';
// If set to true, the user must press
// UP UP DOWN ODWN LEFT RIGHT LEFT RIGHT A B
// to trigger the confetti with a random color theme.
// Otherwise the confetti constantly falls.
var onlyOnKonami = false;
$(function() {
// Globals
var $window = $(window)
, random = Math.random
, cos = Math.cos
, sin = Math.sin
, PI = Math.PI
, PI2 = PI * 2
, timer = undefined
, frame = undefined
, confetti = [];
// Settings
var konami = [38, 38, 40, 40, 37, 39, 37, 39, 66, 65]
, pointer = 0;
var particles = 150
, spread = 10
, sizeMin = 3
, sizeMax = 40 - sizeMin
, eccentricity = 10
, deviation = 100
, dxThetaMin = -.1
, dxThetaMax = -dxThetaMin - dxThetaMin
, dyMin = .13
, dyMax = .18
, dThetaMin = .4
, dThetaMax = .7 - dThetaMin;
var colorThemes = [
function() {
//return color(200 * random()|0, 200 * random()|0, 200 * random()|0);
return color(218,165,32);
}, function() {
var black = 200 * random()|0; return color(200, black, black);
}, function() {
var black = 200 * random()|0; return color(black, 200, black);
}, function() {
var black = 200 * random()|0; return color(black, black, 200);
}, function() {
return color(200, 100, 200 * random()|0);
}, function() {
return color(200 * random()|0, 200, 200);
}, function() {
var black = 256 * random()|0; return color(black, black, black);
}, function() {
return colorThemes[random() < .5 ? 1 : 2]();
}, function() {
return colorThemes[random() < .5 ? 3 : 5]();
}, function() {
return colorThemes[random() < .5 ? 2 : 4]();
}
];
function color(r, g, b) {
return 'rgb(' + r + ',' + g + ',' + b + ')';
}
// Cosine interpolation
function interpolation(a, b, t) {
return (1-cos(PI*t))/2 * (b-a) + a;
}
// Create a 1D Maximal Poisson Disc over [0, 1]
var radius = 1/eccentricity, radius2 = radius+radius;
function createPoisson() {
// domain is the set of points which are still available to pick from
// D = union{ [d_i, d_i+1] | i is even }
var domain = [radius, 1-radius], measure = 1-radius2, spline = [0, 1];
while (measure) {
var dart = measure * random(), i, l, interval, a, b, c, d;
// Find where dart lies
for (i = 0, l = domain.length, measure = 0; i < l; i += 2) {
a = domain[i], b = domain[i+1], interval = b-a;
if (dart < measure+interval) {
spline.push(dart += a-measure);
break;
}
measure += interval;
}
c = dart-radius, d = dart+radius;
// Update the domain
for (i = domain.length-1; i > 0; i -= 2) {
l = i-1, a = domain[l], b = domain[i];
// c---d c---d Do nothing
// c-----d c-----d Move interior
// c--------------d Delete interval
// c--d Split interval
// a------b
if (a >= c && a < d)
if (b > d) domain[l] = d; // Move interior (Left case)
else domain.splice(l, 2); // Delete interval
else if (a < c && b > c)
if (b <= d) domain[i] = c; // Move interior (Right case)
else domain.splice(i, 0, c, d); // Split interval
}
// Re-measure the domain
for (i = 0, l = domain.length, measure = 0; i < l; i += 2)
measure += domain[i+1]-domain[i];
}
return spline.sort();
}
// Create the overarching container
var container = document.createElement('div');
container.style.position = 'fixed';
container.style.top = '0';
container.style.left = '0';
container.style.width = '100%';
container.style.height = '0';
container.style.overflow = 'visible';
container.style.zIndex = '9999';
// Confetto constructor
function Confetto(theme) {
this.frame = 0;
this.outer = document.createElement('div');
this.inner = document.createElement('div');
this.outer.appendChild(this.inner);
var outerStyle = this.outer.style, innerStyle = this.inner.style;
outerStyle.position = 'absolute';
outerStyle.width = (sizeMin + sizeMax * random()) + 'px';
outerStyle.height = (sizeMin + sizeMax * random()) + 'px';
innerStyle.width = '100%';
innerStyle.height = '100%';
innerStyle.backgroundColor = theme();
outerStyle.perspective = '100px';
outerStyle.transform = 'rotate(' + (360 * random()) + 'deg)';
this.axis = 'rotate3D(' +
cos(360 * random()) + ',' +
cos(360 * random()) + ',0,';
this.theta = 360 * random();
this.dTheta = dThetaMin + dThetaMax * random();
innerStyle.transform = this.axis + this.theta + 'deg)';
this.x = $window.width() * random();
this.y = -deviation;
this.dx = sin(dxThetaMin + dxThetaMax * random());
this.dy = dyMin + dyMax * random();
outerStyle.left = this.x + 'px';
outerStyle.top = this.y + 'px';
// Create the periodic spline
this.splineX = createPoisson();
this.splineY = [];
for (var i = 1, l = this.splineX.length-1; i < l; ++i)
this.splineY[i] = deviation * random();
this.splineY[0] = this.splineY[l] = deviation * random();
this.update = function(height, delta) {
this.frame += delta;
this.x += this.dx * delta;
this.y += this.dy * delta;
this.theta += this.dTheta * delta;
// Compute spline and convert to polar
var phi = this.frame % 7777 / 7777, i = 0, j = 1;
while (phi >= this.splineX[j]) i = j++;
var rho = interpolation(
this.splineY[i],
this.splineY[j],
(phi-this.splineX[i]) / (this.splineX[j]-this.splineX[i])
);
phi *= PI2;
outerStyle.left = this.x + rho * cos(phi) + 'px';
outerStyle.top = this.y + rho * sin(phi) + 'px';
innerStyle.transform = this.axis + this.theta + 'deg)';
return this.y > height+deviation;
};
}
function poof() {
if (!frame) {
// Append the container
document.body.appendChild(container);
// Add confetti
var theme = colorThemes[onlyOnKonami ? colorThemes.length * random()|0 : 0]
, count = 0;
(function addConfetto() {
if (onlyOnKonami && ++count > particles)
return timer = undefined;
var confetto = new Confetto(theme);
confetti.push(confetto);
container.appendChild(confetto.outer);
timer = setTimeout(addConfetto, spread * random());
})(0);
// Start the loop
var prev = undefined;
requestAnimationFrame(function loop(timestamp) {
var delta = prev ? timestamp - prev : 0;
prev = timestamp;
var height = $window.height();
for (var i = confetti.length-1; i >= 0; --i) {
if (confetti[i].update(height, delta)) {
container.removeChild(confetti[i].outer);
confetti.splice(i, 1);
}
}
if (timer || confetti.length)
return frame = requestAnimationFrame(loop);
// Cleanup
document.body.removeChild(container);
frame = undefined;
});
}
}
$window.keydown(function(event) {
pointer = konami[pointer] === event.which
? pointer+1
: +(event.which === konami[0]);
if (pointer === konami.length) {
pointer = 0;
poof();
}
});
if (!onlyOnKonami) poof();
});
html {
height: 100%;
}
body {
background: #d09d42;
background: linear-gradient(to bottom, #efc466, #d09d42);
height: 100%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
You need to modify method Confetto() to change the color of the divI've added the following javascript after innerStyle.backgroundColor = theme():
function Confetto(){
//Code
innerStyle.backgroundColor = theme()
innerStyle.background = "linear-gradient(to right, " + theme() + " , yellow)";
innerStyle.border = "thick solid #FFFB00";
innerStyle.borderWidth = "thin";
//Rest of the code
}
Check out this :
// JavaScript source code
'use strict';
// If set to true, the user must press
// UP UP DOWN ODWN LEFT RIGHT LEFT RIGHT A B
// to trigger the confetti with a random color theme.
// Otherwise the confetti constantly falls.
var onlyOnKonami = false;
$(function () {
// Globals
var $window = $(window),
random = Math.random,
cos = Math.cos,
sin = Math.sin,
PI = Math.PI,
PI2 = PI * 2,
timer = undefined,
frame = undefined,
confetti = [];
// Settings
var konami = [38, 38, 40, 40, 37, 39, 37, 39, 66, 65],
//var konami = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
pointer = 0;
var particles = 10,
spread = 10,
sizeMin = 3,
sizeMax = 40 - sizeMin,
eccentricity = 10,
deviation = 100,
dxThetaMin = -.1,
dxThetaMax = -dxThetaMin - dxThetaMin,
dyMin = .13,
dyMax = .18,
dThetaMin = .4,
dThetaMax = .7 - dThetaMin;
var colorThemes = [
function () {
//return color(200 * random()|0, 200 * random()|0, 200 * random()|0);
return color(218, 165, 32);
},
function () {
var black = 200 * random() | 0;
return color(200, black, black);
},
function () {
var black = 200 * random() | 0;
return color(black, 200, black);
},
function () {
var black = 200 * random() | 0;
return color(black, black, 200);
},
function () {
return color(200, 100, 200 * random() | 0);
},
function () {
return color(200 * random() | 0, 200, 200);
},
function () {
var black = 256 * random() | 0;
return color(black, black, black);
},
function () {
return colorThemes[random() < .5 ? 1 : 2]();
},
function () {
return colorThemes[random() < .5 ? 3 : 5]();
},
function () {
return colorThemes[random() < .5 ? 2 : 4]();
}
];
function color(r, g, b) {
return 'rgb(' + r + ',' + g + ',' + b + ')';
}
// Cosine interpolation
function interpolation(a, b, t) {
return (1 - cos(PI * t)) / 2 * (b - a) + a;
}
// Create a 1D Maximal Poisson Disc over [0, 1]
var radius = 1 / eccentricity,
radius2 = radius + radius;
function createPoisson() {
// domain is the set of points which are still available to pick from
// D = union{ [d_i, d_i+1] | i is even }
var domain = [radius, 1 - radius],
measure = 1 - radius2,
spline = [0, 1];
while (measure) {
var dart = measure * random(),
i, l, interval, a, b, c, d;
// Find where dart lies
for (i = 0, l = domain.length, measure = 0; i < l; i += 2) {
a = domain[i], b = domain[i + 1], interval = b - a;
if (dart < measure + interval) {
spline.push(dart += a - measure);
break;
}
measure += interval;
}
c = dart - radius, d = dart + radius;
// Update the domain
for (i = domain.length - 1; i > 0; i -= 2) {
l = i - 1, a = domain[l], b = domain[i];
// c---d c---d Do nothing
// c-----d c-----d Move interior
// c--------------d Delete interval
// c--d Split interval
// a------b
if (a >= c && a < d)
if (b > d) domain[l] = d; // Move interior (Left case)
else domain.splice(l, 2); // Delete interval
else if (a < c && b > c)
if (b <= d) domain[i] = c; // Move interior (Right case)
else domain.splice(i, 0, c, d); // Split interval
}
// Re-measure the domain
for (i = 0, l = domain.length, measure = 0; i < l; i += 2)
measure += domain[i + 1] - domain[i];
}
return spline.sort();
}
// Create the overarching container
var container = document.createElement('div');
container.style.position = 'fixed';
container.style.top = '0';
container.style.left = '0';
container.style.width = '100%';
container.style.height = '0';
container.style.overflow = 'visible';
container.style.zIndex = '9999';
// Confetto constructor
function Confetto(theme) {
this.frame = 0;
this.outer = document.createElement('div');
this.inner = document.createElement('div');
this.outer.appendChild(this.inner);
var outerStyle = this.outer.style,
innerStyle = this.inner.style;
outerStyle.position = 'absolute';
outerStyle.width = (sizeMin + sizeMax * random()) + 'px';
outerStyle.height = (sizeMin + sizeMax * random()) + 'px';
innerStyle.width = '100%';
innerStyle.height = '100%';
var f = theme();
innerStyle.backgroundColor = theme();
innerStyle.background = "linear-gradient(to right, " + theme() + " , yellow)";
innerStyle.border = "thick solid #FFFB00";
innerStyle.borderWidth = "thin";
outerStyle.perspective = '100px';
outerStyle.transform = 'rotate(' + (360 * random()) + 'deg)';
this.axis = 'rotate3D(' +
cos(360 * random()) + ',' +
cos(360 * random()) + ',0,';
this.theta = 360 * random();
this.dTheta = dThetaMin + dThetaMax * random();
innerStyle.transform = this.axis + this.theta + 'deg)';
this.x = $window.width() * random();
this.y = -deviation;
this.dx = sin(dxThetaMin + dxThetaMax * random());
this.dy = dyMin + dyMax * random();
outerStyle.left = this.x + 'px';
outerStyle.top = this.y + 'px';
// Create the periodic spline
this.splineX = createPoisson();
this.splineY = [];
for (var i = 1, l = this.splineX.length - 1; i < l; ++i)
this.splineY[i] = deviation * random();
this.splineY[0] = this.splineY[l] = deviation * random();
this.update = function (height, delta) {
this.frame += delta;
this.x += this.dx * delta;
this.y += this.dy * delta;
this.theta += this.dTheta * delta;
// Compute spline and convert to polar
var phi = this.frame % 7777 / 7777,
i = 0,
j = 1;
while (phi >= this.splineX[j]) i = j++;
var rho = interpolation(
this.splineY[i],
this.splineY[j],
(phi - this.splineX[i]) / (this.splineX[j] - this.splineX[i])
);
phi *= PI2;
outerStyle.left = this.x + rho * cos(phi) + 'px';
outerStyle.top = this.y + rho * sin(phi) + 'px';
innerStyle.transform = this.axis + this.theta + 'deg)';
return this.y > height + deviation;
};
}
function poof() {
if (!frame) {
// Append the container
document.body.appendChild(container);
// Add confetti
var theme = colorThemes[onlyOnKonami ? colorThemes.length * random() | 0 : 0],
count = 0;
(function addConfetto() {
if (onlyOnKonami && ++count > particles)
return timer = undefined;
var confetto = new Confetto(theme);
confetti.push(confetto);
container.appendChild(confetto.outer);
timer = setTimeout(addConfetto, spread * random());
})(0);
// Start the loop
var prev = undefined;
requestAnimationFrame(function loop(timestamp) {
var delta = prev ? timestamp - prev : 0;
prev = timestamp;
var height = $window.height();
for (var i = confetti.length - 1; i >= 0; --i) {
if (confetti[i].update(height, delta)) {
container.removeChild(confetti[i].outer);
confetti.splice(i, 1);
}
}
if (timer || confetti.length)
return frame = requestAnimationFrame(loop);
// Cleanup
document.body.removeChild(container);
frame = undefined;
});
}
}
$window.keydown(function (event) {
pointer = konami[pointer] === event.which ?
pointer + 1 :
+(event.which === konami[0]);
if (pointer === konami.length) {
pointer = 0;
poof();
}
});
if (!onlyOnKonami) poof();
});
html {
height: 100%;
}
body {
background: #d09d42;
background: linear-gradient(to bottom, #efc466, #d09d42);
height: 100%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
I need some expert help. When I make canvas background transparent the line colors the whole canvas (shown in code below).
How do I stop/fix this? I want the line stay as a single line that doesn't color the canvas.
Math.clamp = function(x, min, max) {
return x < min ? min : (x > max ? max : x);
};
// canvas settings
var viewWidth = window.innerWidth,
viewHeight = window.innerHeight,
drawingCanvas = document.getElementById("drawing_canvas"),
ctx,
timeStep = (10 / 100),
time = 0;
var lineTension = 0.067,
lineDamping = 0.068,
waveSpreadFactor = 0.1;
var previousMousePosition = {
x: 0,
y: 0
},
currentMousePosition = {
x: 0,
y: 0
},
actualMousePosition = {
x: 0,
y: 0
};
var line,
lineSegmentCount = 64,
lineMaxForce = 32,
lineStrokeGradient;
var audioCtx,
nodeCount = 64,
oscillatorNodes = [],
gainNodes = [];
var segmentsPerNode = lineSegmentCount / nodeCount;
function initGui() {
}
function goBananas() {
lineTension = 0.2;
line.anchors[Math.floor(Math.random() * line.anchors.length)].
vel = lineMaxForce;
}
function resetLine() {
line.reset();
for (var i = 0; i < nodeCount; i++) {
oscillatorNodes[i].detune.value = 100;
gainNodes[i].gain.value = 0;
}
lineTension = 0.0025;
lineDamping = 0.05;
waveSpreadFactor = 0.1;
}
function initDrawingCanvas() {
drawingCanvas.width = viewWidth;
drawingCanvas.height = viewHeight;
window.addEventListener('resize', resizeHandler);
window.addEventListener('mousemove', mouseMoveHandler);
setInterval(updateMousePosition, (1000 / 30));
ctx = drawingCanvas.getContext('2d');
ctx.lineWidth = 5;
line = new Line(0, viewHeight * 0.5, viewWidth, lineSegmentCount);
// line.anchors[0].vel = viewHeight * 0.25;
lineStrokeGradient = ctx.createLinearGradient(0, 0, 0, viewHeight);
lineStrokeGradient.addColorStop(0, '#0ff');
}
function initWebAudio() {
audioCtx = new(window.AudioContext || window.webkitAudioContext)();
for (var i = 0; i < nodeCount; i++) {
var oscillatorNode = audioCtx.createOscillator();
var gainNode = audioCtx.createGain();
oscillatorNode.connect(gainNode);
gainNode.connect(audioCtx.destination);
gainNode.gain.value = 0;
oscillatorNode.type = 'saw';
oscillatorNode.detune.value = 200;
oscillatorNode.frequency.value = 1200 * (i / 60);
oscillatorNode.start();
oscillatorNodes[i] = oscillatorNode;
gainNodes[i] = gainNode;
}
}
function resizeHandler() {
drawingCanvas.width = viewWidth = window.innerWidth;
drawingCanvas.height = viewHeight = window.innerHeight;
if (ctx) {
ctx.lineWidth = 4;
line.resize(viewWidth, viewHeight * 0.5);
}
}
function mouseMoveHandler(event) {
actualMousePosition.x = Math.floor(event.clientX);
actualMousePosition.y = Math.floor(event.clientY);
}
function updateMousePosition() {
previousMousePosition.x = currentMousePosition.x;
previousMousePosition.y = currentMousePosition.y;
currentMousePosition.x = actualMousePosition.x;
currentMousePosition.y = actualMousePosition.y;
}
function update() {
var px = Math.min(previousMousePosition.x, currentMousePosition.x),
py = Math.min(previousMousePosition.y, currentMousePosition.y),
pw = Math.max(1, Math.abs(previousMousePosition.x - currentMousePosition.x)),
ph = Math.max(1, Math.abs(previousMousePosition.y - currentMousePosition.y)),
force = Math.clamp(currentMousePosition.y -
previousMousePosition.y, -lineMaxForce, lineMaxForce);
var pixels = ctx.getImageData(px, py, pw, ph),
data = pixels.data;
for (var i = 0; i < data.length; i += 3) {
var r = data[i + 0],
g = data[i + 1],
b = data[i + 2],
x = (i % ph) + px;
if (r + g + b > 0) {
line.ripple(x, force);
}
}
line.update();
for (var j = 0; j < gainNodes.length; j++) {
var anchor = line.anchors[j * segmentsPerNode],
gain = Math.clamp(Math.abs(anchor.vel) / viewHeight * 0.5, 0, 3),
detune = Math.clamp(anchor.pos / viewHeight * 100, 0, 300);
gainNodes[j].gain.value = gain;
oscillatorNodes[j].detune.value = detune;
}
}
function draw() {
ctx.strokeStyle = lineStrokeGradient;
line.draw();
}
window.onload = function() {
initDrawingCanvas();
initWebAudio();
initGui();
requestAnimationFrame(loop);
};
function loop() {
update();
draw();
time += timeStep;
requestAnimationFrame(loop);
}
Line = function(x, y, length, segments) {
this.x = x;
this.y = y;
this.length = length;
this.segments = segments;
this.segmentLength = this.length / this.segments;
this.anchors = [];
for (var i = 0; i <= this.segments; i++) {
this.anchors[i] = {
target: this.y,
pos: this.y,
vel: 0,
update: function() {
var dy = this.pos - this.target,
acc = -lineTension * dy - lineDamping * this.vel;
this.pos += this.vel;
this.vel += acc;
},
reset: function() {
this.pos = this.target;
this.vel = 0;
}
};
}
};
Line.prototype = {
resize: function(length, targetY) {
this.length = length;
this.segmentLength = this.length / this.segments;
for (var i = 0; i <= this.segments; i++) {
this.anchors[i].target = targetY;
}
},
reset: function() {
for (var i = 0; i <= this.segments; i++) {
this.anchors[i].reset();
}
},
ripple: function(origin, amplitude) {
var i = Math.floor((origin - this.x) / this.segmentLength);
if (i >= 0 && i <= this.segments) {
this.anchors[i].vel = amplitude;
}
},
update: function() {
var lDeltas = [],
rDeltas = [],
i;
for (i = 0; i <= this.segments; i++) {
this.anchors[i].update();
}
for (i = 0; i <= this.segments; i++) {
if (i > 0) {
lDeltas[i] = waveSpreadFactor * (this.anchors[i].pos - this.anchors[i - 1].pos);
this.anchors[i - 1].vel += lDeltas[i];
}
if (i < this.segments) {
rDeltas[i] = waveSpreadFactor * (this.anchors[i].pos - this.anchors[i + 1].pos);
this.anchors[i + 1].vel += rDeltas[i];
}
}
for (i = 0; i <= this.segments; i++) {
if (i > 0) {
this.anchors[i - 1].pos += lDeltas[i];
}
if (i < this.segments) {
this.anchors[i + 1].pos += rDeltas[i];
}
}
},
draw: function() {
ctx.beginPath();
for (var i = 0; i <= this.segments; i++) {
ctx.lineTo(
this.x + this.segmentLength * i,
this.anchors[i].pos
);
}
ctx.stroke();
}
};
From the code you posted, the problem seems to be a missing
ctx.clearRect(0, 0, viewWidth, viewHeight)
at the beginning of your "draw" function.
See a working example here