Changing input from text to radio stops existing code working - javascript

I have some code which works perfect from a tutorial site. It shows RSVP and updates the text when you type in the input box. This is the code working:
https://jsfiddle.net/spadez/7gyrd08w/6/
Current it works with an input box as such:
<input id="input" type="text" value="EDIT ME">
And then the following JS:
function initInput() {
input = document.getElementById('input');
input.addEventListener('keyup', updateText);
input.value = 'RSVP';
}
I wanted to change it to pull the value from the radio box when one was selected. So I changed the html to this:
<input id="input" type="radio" name="rsvp" value="Yay!">
<input id="input" type="radio" name="rsvp" value="Oh no!">
And the JavaScript to this (line 167):
function initInput() {
input = document.getElementById('input');
input.addEventListener('change', updateText);
input.value = 'RSVP';
}
However, this doesn't work, and when I select a radio box the text doesn't update. Is there any obvious reason why? This code can be seen here (not working with the radio field):
https://jsfiddle.net/spadez/7gyrd08w/7/

Use the following code. This should help you solve the problem.
var height,
width,
container,
scene,
camera,
renderer,
particles = [],
mouseVector = new THREE.Vector3(0, 0, 0),
mousePos = new THREE.Vector3(0, 0, 0),
cameraLookAt = new THREE.Vector3(0, 0, 0),
cameraTarget = new THREE.Vector3(0, 0, 800),
textCanvas,
textCtx,
textPixels = [],
input;
var colors = ['#F7A541', '#F45D4C', '#FA2E59', '#4783c3', '#9c6cb7'];
function initStage() {
width = window.innerWidth;
height = window.innerHeight;
container = document.getElementById('stage');
window.addEventListener('resize', resize);
container.addEventListener('mousemove', mousemove);
}
function initScene() {
scene = new THREE.Scene();
renderer = new THREE.WebGLRenderer({
alpha: true,
antialias: true
});
renderer.setPixelRatio(window.devicePixelRatio);
renderer.setSize(width, height);
container.appendChild(renderer.domElement);
}
function randomPos(vector) {
var radius = width * 3;
var centerX = 0;
var centerY = 0;
// ensure that p(r) ~ r instead of p(r) ~ constant
var r = width + radius * Math.random();
var angle = Math.random() * Math.PI * 2;
// compute desired coordinates
vector.x = centerX + r * Math.cos(angle);
vector.y = centerY + r * Math.sin(angle);
}
function initCamera() {
fieldOfView = 75;
aspectRatio = width / height;
nearPlane = 1;
farPlane = 3000;
camera = new THREE.PerspectiveCamera(
fieldOfView,
aspectRatio,
nearPlane,
farPlane);
camera.position.z = 800;
console.log(camera.position);
console.log(cameraTarget);
}
function createLights() {
shadowLight = new THREE.DirectionalLight(0xffffff, 2);
shadowLight.position.set(20, 0, 10);
shadowLight.castShadow = true;
shadowLight.shadowDarkness = 0.01;
scene.add(shadowLight);
light = new THREE.DirectionalLight(0xffffff, .5);
light.position.set(-20, 0, 20);
scene.add(light);
backLight = new THREE.DirectionalLight(0xffffff, 0.8);
backLight.position.set(0, 0, -20);
scene.add(backLight);
}
function Particle() {
this.vx = Math.random() * 0.05;
this.vy = Math.random() * 0.05;
}
Particle.prototype.init = function(i) {
var particle = new THREE.Object3D();
var geometryCore = new THREE.BoxGeometry(20, 20, 20);
var materialCore = new THREE.MeshLambertMaterial({
color: colors[i % colors.length],
shading: THREE.FlatShading
});
var box = new THREE.Mesh(geometryCore, materialCore);
box.geometry.__dirtyVertices = true;
box.geometry.dynamic = true;
particle.targetPosition = new THREE.Vector3((textPixels[i].x - (width / 2)) * 4, (textPixels[i].y) * 5, -10 * Math.random() + 20);
particle.position.set(width * 0.5, height * 0.5, -10 * Math.random() + 20);
randomPos(particle.position);
for (var i = 0; i < box.geometry.vertices.length; i++) {
box.geometry.vertices[i].x += -10 + Math.random() * 20;
box.geometry.vertices[i].y += -10 + Math.random() * 20;
box.geometry.vertices[i].z += -10 + Math.random() * 20;
}
particle.add(box);
this.particle = particle;
}
Particle.prototype.updateRotation = function() {
this.particle.rotation.x += this.vx;
this.particle.rotation.y += this.vy;
}
Particle.prototype.updatePosition = function() {
this.particle.position.lerp(this.particle.targetPosition, 0.02);
}
function render() {
renderer.render(scene, camera);
}
function updateParticles() {
for (var i = 0, l = particles.length; i < l; i++) {
particles[i].updateRotation();
particles[i].updatePosition();
}
}
function setParticles() {
for (var i = 0; i < textPixels.length; i++) {
if (particles[i]) {
particles[i].particle.targetPosition.x = (textPixels[i].x - (width / 2)) * 4;
particles[i].particle.targetPosition.y = (textPixels[i].y) * 5;
particles[i].particle.targetPosition.z = -10 * Math.random() + 20;
} else {
var p = new Particle();
p.init(i);
scene.add(p.particle);
particles[i] = p;
}
}
for (var i = textPixels.length; i < particles.length; i++) {
randomPos(particles[i].particle.targetPosition);
}
}
function initCanvas() {
textCanvas = document.getElementById('text');
textCanvas.style.width = width + 'px';
textCanvas.style.height = 200 + 'px';
textCanvas.width = width;
textCanvas.height = 200;
textCtx = textCanvas.getContext('2d');
textCtx.font = '700 100px Arial';
textCtx.fillStyle = '#555';
}
//function initInput() {
// input = document.getElementById('input');
// input.addEventListener('keyup', updateText);
// input.value = 'RSVP';
//}
function initInput() {
radios = document.getElementsByName('rsvp');
for (radio in radios) {
(radios[radio]).onclick = updateText;
}
//input.value = 'RSVP';
}
function updateText() {
var value = (this.value != undefined) ? this.value : '';
var fontSize = (width / (value * 1.3));
if (fontSize > 120) fontSize = 120;
textCtx.font = '700 ' + fontSize + 'px Arial';
textCtx.clearRect(0, 0, width, 200);
textCtx.textAlign = 'center';
textCtx.textBaseline = "middle";
textCtx.fillText(value.toUpperCase(), width / 2, 50);
var pix = textCtx.getImageData(0, 0, width, 200).data;
textPixels = [];
for (var i = pix.length; i >= 0; i -= 4) {
if (pix[i] != 0) {
var x = (i / 4) % width;
var y = Math.floor(Math.floor(i / width) / 4);
if ((x && x % 6 == 0) && (y && y % 6 == 0)) textPixels.push({
x: x,
y: 200 - y + -120
});
}
}
setParticles();
}
function animate() {
requestAnimationFrame(animate);
updateParticles();
camera.position.lerp(cameraTarget, 0.2);
camera.lookAt(cameraLookAt);
render();
}
function resize() {
width = window.innerWidth;
height = window.innerHeight;
camera.aspect = width / height;
camera.updateProjectionMatrix();
renderer.setSize(width, height);
textCanvas.style.width = width + 'px';
textCanvas.style.height = 200 + 'px';
textCanvas.width = width;
textCanvas.height = 200;
updateText();
}
function mousemove(e) {
//var x = e.pageX - width/2;
//var y = e.pageY - height/2;
//cameraTarget.x = x*-1;
//cameraTarget.y = y;
}
initStage();
initScene();
initCanvas();
initCamera();
createLights();
initInput();
animate();
setTimeout(function() {
updateText();
}, 40);
body {
overflow: hidden;
}
div,
canvas {
position: absolute;
}
#text {
z-index: 200;
display: none;
}
form {
z-index: 400;
position: absolute;
text-transform: uppercase;
font-size: 30px;
color: #222;
font-weight: bold;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r71/three.min.js"></script>
<div id="stage"></div>
<canvas id="text" width="700" height="150"></canvas>
<form>
<!--<input id="input" type="text" value="EDIT ME">-->
<input id="input" type="radio" name="rsvp" value="Yay!">
<input id="input" type="radio" name="rsvp" value="Oh no!">
</form>

Related

Canvas: Movement only allowed on X axis?

The Problem
I am creating a game where you have to move away from or dodge projectiles coming towards you, I have enabled the user to move the image they are controlling but at the moment the user can place the image anywhere on the canvas.
The Question
How can I only allow the user to move along designated part of the canvas and only along the X axis? for example:
Here is my game, "working progress":
The user is in control of the ship, they should only be able to move left or right like this for example:
The Code
<script>
var game = create_game();
game.init();
//music
var snd = new Audio("menu.mp3");
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 = "apple.png";
player_img.src = "basket.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;
player.y = (e.clientY - bounding_box.top) * (c.height / bounding_box.height) - player_img.height / 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
};
}
</script>
JSFiddle (Broken)
https://jsfiddle.net/3oc4jsf6/10/
If your ship is tied to mouse movement, and you want to only allow movement across the X-axis you can simply avoid changing its .y property in your mousemove listener.
Remove this line:
player.y = (e.clientY - bounding_box.top) * (c.height / bounding_box.height) - player_img.height / 2;

how can i make two objects belonging to the same array move independently of each other using javascript and the canvas tag?

I am trying to create a blackhole simulation, where all the balls that are outside of it go away from it at a given speed and those that fall on it are dragged towards the circle until they reach the center of it, where they would stop and disappear, here is my code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>blackhole simulation escape velocity</title>
<script>
var canvas, ctx;
var blackhole;
var circle;
var circles = new Array();
var G = 6.67e-11, //gravitational constant
pixel_G = G / 1e-11,
c = 3e8, //speed of light (m/s)
M = 12e31, // masseof the blackhole in kg (60 solar masses)
pixel_M = M / 1e32
Rs = (2 * G * M) / 9e16, //Schwarzchild radius
pixel_Rs = Rs / 1e3, // scaled radius
ccolor = 128;
function update() {
var pos, i, distance, somethingMoved = false;
for (i = 0; i < circles.length; i++) {
pos = circles[i].position;
distance = Math.sqrt(((pos.x - 700) * (pos.x - 700)) + ((pos.y - 400) * (pos.y - 400)));
if (distance > pixel_Rs-5 ) {
var delta = new Vector2D(0, 0);
var forceDirection = Math.atan2(pos.y - 400, pos.x - 700);
var evelocity = Math.sqrt((2 * pixel_G * pixel_M) / (distance * 1e-2));
delta.x += Math.cos(forceDirection) * evelocity;
delta.y += Math.sin(forceDirection) * evelocity;
pos.x += delta.x;
pos.y += delta.y;
somethingMoved = true;
} else {
var delta2 = new Vector2D (0,0);
var forceDirection2 = Math.atan2(pos.y - 400, pos.x - 700);
var g = (pixel_G*pixel_M)/(distance*distance*1e2);
delta2.x += Math.cos(forceDirection2)*g;
delta2.y += Math.sin(forceDirection2)*g;
pos.x -= delta2.x;
pos.y -= delta2.y;
somethingMoved = true;
circles[i].color -= 1;
if (pos.x == 700 && pos.y == 400){
somethingMoved = false;
};
}
}
if (somethingMoved) {
drawEverything();
requestAnimationFrame(update);
};
}
function drawEverything() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
blackhole.draw(ctx);
for (var i = 0; i < circles.length; i++) {
circles[i].draw(ctx);
}
}
function init(event) {
canvas = document.getElementById("space");
ctx = canvas.getContext('2d');
blackhole = new Ball(pixel_Rs, { x: 700,
y: 400 }, 0);
for (var i = 0; i < 200; i++) {
var vec2D = new Vector2D(Math.floor(Math.random() * 1400), Math.floor(Math.random() * 800));
circle = new Ball(5, vec2D, ccolor);
circles.push(circle);
}
drawEverything();
requestAnimationFrame(update);
}
function Ball(radius, position, color) {
this.radius = radius;
this.position = position;
this.color = color;
}
Ball.prototype.draw = function(ctx) {
var c=parseInt(this.color);
ctx.fillStyle = 'rgba(' + c + ',' + c + ',' + c + ',1)';
ctx.beginPath();
ctx.arc(this.position.x, this.position.y, this.radius, 0, 2 * Math.PI);
ctx.closePath();
ctx.fill();
};
function Vector2D(x, y) {
this.x = x;
this.y = y;
}
function onClick (){
canvas = document.getElementById ('space');
ctx = canvas.getContext ('2d')
canvas.addEventListener ("mousedown", init, false)
blackhole = new Ball (5, {x: 700,
y: 400 }, 0);
blackhole.draw (ctx) ;
}
window.onload = onClick;
</script>
<style>
body {
background-color:#021c36 ;
margin: 0px;
}
</style>
</head>
<body>
<canvas id = "space", width = "1400", height = "800">
</canvas>
</body>
</html>
Now as you can see, I created a second variable called delta2, but the problem is that it can't update the position of the circles, which in term makes it impossible to move the circle, can someone tell me what is wrong. Also, how can I make the big black circle after a certain amount of time, i know i probably should create a timer, but i don't know how they work
The gravity is too weak. I put a pseudo gravity to demonstrate.
var canvas, ctx;
var blackhole;
var circle;
var circles = new Array();
var bh = {
w:500,
h:300
};
bh.cx = Math.floor(bh.w/2);
bh.cy = Math.floor(bh.h/2)
var G = 6.67e-11, //gravitational constant
pixel_G = G / 1e-11,
c = 3e8, //speed of light (m/s)
M = 12e31, // masseof the blackhole in kg (60 solar masses)
pixel_M = M / 1e32
Rs = (2 * G * M) / 9e16, //Schwarzchild radius
pixel_Rs = Rs / 1e3, // scaled radius
ccolor = 128;
function update() {
var pos, i, distance, somethingMoved = false;
for (i = 0; i < circles.length; i++) {
pos = circles[i].position;
distance = Math.sqrt(((pos.x - bh.cx) * (pos.x - bh.cx)) + ((pos.y - bh.cy) * (pos.y - bh.cy)));
if (distance > pixel_Rs - 5) {
var delta = new Vector2D(0, 0);
var forceDirection = Math.atan2(pos.y - bh.cy, pos.x - bh.cx);
var evelocity = Math.sqrt((2 * pixel_G * pixel_M) / (distance * 1e-2));
delta.x += Math.cos(forceDirection) * evelocity;
delta.y += Math.sin(forceDirection) * evelocity;
pos.x += delta.x;
pos.y += delta.y;
somethingMoved = true;
} else {
var delta2 = new Vector2D(0, 0);
var forceDirection2 = Math.atan2(pos.y - bh.cy, pos.x - bh.cx);
// FIX THIS!!!
var g = 1;//(pixel_G * pixel_M) / (distance * distance * 1e2);
delta2.x += Math.cos(forceDirection2) * g;
delta2.y += Math.sin(forceDirection2) * g;
pos.x -= delta2.x;
pos.y -= delta2.y;
somethingMoved = true;
circles[i].color -= 1;
if (pos.x == bh.cx && pos.y == bh.cy) {
somethingMoved = false;
};
}
}
if (somethingMoved) {
drawEverything();
requestAnimationFrame(update);
};
}
function drawEverything() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
blackhole.draw(ctx);
for (var i = 0; i < circles.length; i++) {
circles[i].draw(ctx);
}
}
function init(event) {
canvas = document.getElementById("space");
canvas.width = bh.w;
canvas.height = bh.h;
ctx = canvas.getContext('2d');
blackhole = new Ball(5, { //pixel_Rs, {
x: bh.cx,
y: bh.cy
}, 0);
for (var i = 0; i < 200; i++) {
var vec2D = new Vector2D(Math.floor(Math.random() * bh.w), Math.floor(Math.random() * bh.h));
circle = new Ball(5, vec2D, ccolor);
circles.push(circle);
}
drawEverything();
requestAnimationFrame(update);
}
function Ball(radius, position, color) {
this.radius = radius;
this.position = position;
this.color = color;
}
Ball.prototype.draw = function(ctx) {
var c = parseInt(this.color);
ctx.fillStyle = 'rgba(' + c + ',' + c + ',' + c + ',1)';
ctx.beginPath();
ctx.arc(this.position.x, this.position.y, this.radius, 0, 2 * Math.PI);
ctx.closePath();
ctx.fill();
};
function Vector2D(x, y) {
this.x = x;
this.y = y;
}
function onClick() {
canvas = document.getElementById('space');
ctx = canvas.getContext('2d')
canvas.addEventListener("mousedown", init, false)
blackhole = new Ball(5, {
x: bh.cx,
y: bh.cy
}, 0);
blackhole.draw(ctx);
}
window.onload = onClick;
body {
background-color: #021c36;
margin: 0px;
}
<canvas id="space" , width="700" , height="400"></canvas>

Why does my Javascript animation slowdown after a while

So I am in the process of making this rhythm game with canvas, all that it does up to this point is render the receivers (the point the blocks are going to collide with so the user can press the corresponding buttons and get points) and it renders the dancer animation. For some reason though after the page is open for a while the dancer slows down significantly and continues to gradually slow.
I can't figure out why or how to fix it. Anyone have any ideas?
var canvas = document.createElement("canvas");
var ctx = canvas.getContext("2d");
canvas.width = 500;
canvas.height = 600;
document.body.appendChild(canvas);
var spritesheet = null;
var dancer = {
time:0,
speed:0,
image:null,
x:0,
y:0,
currentFrame:0,
width:50,
height:100,
ready:false
}
function onload() {
spritesheet = new Image();
spritesheet.src = "danceSheet.png";
spritesheet.onload = initiate;
}
function initiate() {
game.startTime = new Date().getTime() / 1000;
dancer.x = (canvas.width / 2) - dancer.width;
dancer.y = 120;
game.initiateReceivers();
main();
}
var game = {
startTime:0,
currentTime:0,
receivers:[],
senders:[],
lanes:[],
drawDancer: function() {
ctx.drawImage(spritesheet, dancer.width * dancer.currentFrame, 0, dancer.width, dancer.height, dancer.x, dancer.y, dancer.width, dancer.height );
},
clearWindow: function() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
},
initiateReceivers: function() {
var distanceRate = canvas.width / 4;
var position = 30;
for(initiates = 0; initiates < 4; initiates++) {
this.receivers[initiates] = new receivers;
this.receivers[initiates].x = position;
this.receivers[initiates].y = 300;
position += distanceRate;
}
}
}
var gameUpdates = {
updateMovement: function() {
game.currentTime = new Date().getTime() / 1000;
dancer.time = game.currentTime - game.startTime;
if(dancer.time >= 0.1) {
game.startTime = new Date().getTime() / 1000;
dancer.currentFrame += 1;
if(dancer.currentFrame == 12) dancer.currentFrame = 0;
}
},
collision: function(shapeA, shapeB) {
// get the vectors to check against
var vX = (shapeA.x + (shapeA.width / 2)) - (shapeB.x + (shapeB.width / 2)),
vY = (shapeA.y + (shapeA.height / 2)) - (shapeB.y + (shapeB.height / 2)),
// add the half widths and half heights of the objects
hWidths = (shapeA.width / 2) + (shapeB.width / 2),
hHeights = (shapeA.height / 2) + (shapeB.height / 2);
// if the x and y vector are less than the half width or half height, they we must be inside the object, causing a collision
if (Math.abs(vX) < hWidths && Math.abs(vY) < hHeights) {
return true;
}
return false;
}
}
function receivers() {
this.x = 0;
this.y = 0;
this.width = 60;
this.height = 10;
}
function senders() {
this.x = 0;
this.y = 0;
this.width = 60;
this.height = 10;
this.lane = 0;
this.status = true;
}
function update() {
gameUpdates.updateMovement();
}
function render() {
game.clearWindow();
game.drawDancer();
game.receivers.forEach( function(receiver) {
ctx.rect(receiver.x,receiver.y,receiver.width,receiver.height);
ctx.fillStyle = "red";
ctx.fill();
}
)
}
function main() {
update();
render();
requestAnimationFrame(main);
}
I'm trying to get an idea of the slowness you're seeing so I adjusted your code to get a frames-per-second. Haven't found the cause yet for the drop.
Update
I found that the frames were dropping from drawing the rectangles. I've altered the code to use fillRect put the fill style outside of the loop. This seems to have fixed the frame drop.
var canvas = document.createElement("canvas");
var ctx = canvas.getContext("2d");
canvas.width = 500;
canvas.height = 600;
document.body.appendChild(canvas);
var spritesheet = null;
var dancer = {
time: 0,
speed: 0,
image: null,
x: 0,
y: 0,
currentFrame: 0,
width: 50,
height: 100,
ready: false
}
function onload() {
spritesheet = document.createElement('canvas');
spritesheet.width = (dancer.width * 12);
spritesheet.height = dancer.height;
var ctx = spritesheet.getContext('2d');
ctx.font = "30px Arial";
ctx.fillStyle = "black";
ctx.strokeStyle = "red";
for (var i = 0; i < 12; i++) {
var x = (i * dancer.width) + 10;
ctx.fillText(i,x,60);
ctx.beginPath();
ctx.rect(i*dancer.width,0,dancer.width,dancer.height);
ctx.stroke();
}
initiate();
}
function initiate() {
game.startTime = new Date().getTime() / 1000;
dancer.x = (canvas.width / 2) - dancer.width;
dancer.y = 120;
game.initiateReceivers();
main();
}
var game = {
startTime: 0,
currentTime: 0,
receivers: [],
senders: [],
lanes: [],
drawDancer: function() {
ctx.drawImage(spritesheet, dancer.width * dancer.currentFrame, 0, dancer.width, dancer.height, dancer.x, dancer.y, dancer.width, dancer.height);
//ctx.strokeStyle="red";
//ctx.beginPath();
//ctx.lineWidth = 3;
//ctx.rect(dancer.x,dancer.y,dancer.width,dancer.height);
//ctx.stroke();
},
clearWindow: function() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
},
initiateReceivers: function() {
var distanceRate = canvas.width / 4;
var position = 30;
for (initiates = 0; initiates < 4; initiates++) {
this.receivers[initiates] = new receivers;
this.receivers[initiates].x = position;
this.receivers[initiates].y = 300;
position += distanceRate;
}
}
};
var gameUpdates = {
updateMovement: function() {
game.currentTime = new Date().getTime() / 1000;
dancer.time = game.currentTime - game.startTime;
if (dancer.time >= 0.1) {
game.startTime = new Date().getTime() / 1000;
dancer.currentFrame += 1;
if (dancer.currentFrame == 12) dancer.currentFrame = 0;
}
},
collision: function(shapeA, shapeB) {
// get the vectors to check against
var vX = (shapeA.x + (shapeA.width / 2)) - (shapeB.x + (shapeB.width / 2)),
vY = (shapeA.y + (shapeA.height / 2)) - (shapeB.y + (shapeB.height / 2)),
// add the half widths and half heights of the objects
hWidths = (shapeA.width / 2) + (shapeB.width / 2),
hHeights = (shapeA.height / 2) + (shapeB.height / 2);
// if the x and y vector are less than the half width or half height, they we must be inside the object, causing a collision
if (Math.abs(vX) < hWidths && Math.abs(vY) < hHeights) {
return true;
}
return false;
}
}
function receivers() {
this.x = 0;
this.y = 0;
this.width = 60;
this.height = 10;
}
function senders() {
this.x = 0;
this.y = 0;
this.width = 60;
this.height = 10;
this.lane = 0;
this.status = true;
}
function update() {
gameUpdates.updateMovement();
}
function render() {
game.clearWindow();
game.drawDancer();
ctx.fillStyle = "red";
game.receivers.forEach(function(receiver) {
ctx.fillRect(receiver.x, receiver.y, receiver.width, receiver.height);
});
ctx.fillText(fps,10,10);
}
var fps = 0;
var frames = 0;
function getFps() {
fps = frames;
frames = 0;
setTimeout(getFps,1000);
}
getFps();
function main() {
update();
render();
frames++;
requestAnimationFrame(main);
}
onload();
canvas {
border:1px solid blue;
}

changing image color while animating it in javascript

I have an image drawn on a canvas. The image for now is doing a simple circular rotation on each frame.
The image scaling is based on the value entered in the text box.
I put the jsfiddle as suggested below
var canvas = null;
var ctx = null;
var image = null;
var slider = null;
var vBox = null;
var x = 50;
var y = 50;
var scaleX;
var scaleY;
var center = {
x: 0,
y: 0
};
var radius = 50.0;
var angle = 0;
var result = false;
var textActive = false;
var imgArr = null;
var imageData;
var data;
function start() {
ctx = getCtxReference();
image = getImageReference();
result = setOtherReferences();
imgArr = getStarImages();
imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
data = imageData.data;
for (var i = 0; i < imgArr.length; i++) {
imgArr[i].addEventListener('load', drawBackgroundStar)
}
if (image != null && result && imgArr != null) {
Loop();
}
}
function checkKeyPressed(e) {
if (e.keyCode == "65") {
changeImgColorToBlue();
}
}
function getCtxReference() {
canvas = document.getElementById("canvas");
ctx = canvas.getContext('2d');
return ctx;
}
function getImageReference() {
image = new Image();
image.src = "star.png";
image.addEventListener('load', drawImg);
return image;
}
function setOtherReferences() {
slider = document.getElementById("rangeInput");
vBox = document.getElementById("textbox");
scaleX = 100;
scaleY = 100;
center.x = canvas.width / 3;
center.y = canvas.height / 3;
return true;
}
function getStarImages() {
var arr = new Array();
for (var i = 0; i < 500; i++) {
var img = new Image();
img.src = "star.png";
arr.push(img);
}
return arr;
}
function drawImg() {
ctx.drawImage(image, x, y, scaleX, scaleY);
return true;
}
function drawBackgroundStar() {
for (var i = 0; i < imgArr.length; i++) {
ctx.drawImage(imgArr[i], getRandomArbitrary(0, canvas.width), getRandomArbitrary(0, canvas.height), getRandomArbitrary(5, 15), getRandomArbitrary(5, 15));
}
}
function Loop() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
window.setTimeout(Loop, 100);
angle += Math.PI * 0.05;
x = center.x + radius * Math.cos(angle);
y = center.y + radius * Math.sin(angle);
vBox.value = slider.value;
updateStarScale();
drawImg();
//drawBackgroundStar();
}
function updateStarScale() {
if (vBox.value > 0) {
scaleX += vBox.value / 10;
scaleY += vBox.value / 10;
changeImgColorToBlue();
} else if (vBox.value < 0) {
scaleX -= Math.abs(vBox.value / 10);
scaleY -= Math.abs(vBox.value / 10);
changeImgColorToRed();
}
if (scaleX > 600 || scaleY > 600) {
scaleX = 600;
scaleY = 600;
} else if (scaleX < 50 || scaleY < 50) {
scaleX = 50;
scaleY = 50;
}
}
function changeImgColorToBlue() {
for (var i = 0; i < data.length; i += 4) {
data[i] = 0; // red
data[i + 1] = 0; // green
data[i + 2] = 255; // blue
}
ctx.putImageData(imageData, 0, 0);
}
function changeImgColorToRed() {
}
function getRandomArbitrary(min, max) {
return Math.random() * (max - min) + min;
}
<html>
<style type="text/css">
body {
text-align: center;
background-image: url("stars.png");
}
#container {
position: fixed;
color: red;
top: 0px;
left: 0px;
}
#textBox {
position: absolute;
top: 25px;
left: 5px;
}
#slider {
position: absolute;
top: 25px;
left: 200px;
}
</style>
<body onload="start()">
<canvas id="canvas" width="1024" height="768"></canvas>
<div id="container">
<div id="textBox">
Velocity:
<input type="text" id="textbox" value="0">
</div>
<div id="slider">
Slider:
<form oninput="amount.value=rangeInput.value">
<input type="range" id="rangeInput" name="rangeInput" min="-100" max="100" step="3" value="">
<output name="amount" for="rangeInput">0</output>
</form>
</div>
</div>
<script type="text/javascript" src="main.js">
</script>
</body>
</html>
So in my Loop(), I am updating the position of my image. In the updateStarScale() I am scaling the image size based on the value given in the text box by the user. All of this works fine. My only concern is the changeImgColorToBlue() which does nothing to the image color. I want the image color to be changed to blue but this doesn't work. What am I doing wrong?
**
UPDATE 1.0:
**
After suggestions from the last post, I changed the code to below. There are two yellow stars on the screen now and they scale up based on the sliders but alongside scaling I want their colors to change ie when they are scaled up they turn blue and when they are scaled down they turn red but the colors don't change.
//Create the images(Using a canvas for CORS issues)
function createStars() {
var imgCanvas = document.createElement('canvas');
imgCanvas.height = "500";
imgCanvas.width = "500";
var imgCtx = imgCanvas.getContext('2d');
imgCtx.fillStyle = 'black';
imgCtx.fillRect(0, 0, 500, 500)
imgCtx.fillStyle = '#FF0';
for (i = 0; i < Math.floor(Math.random() * 500) + 250; i++) {
imgCtx.fillRect(Math.random() * 500, Math.random() * 500, 1, 1)
}
document.body.style.backgroundImage = 'url(' + imgCanvas.toDataURL() + ')';
}
createStars();
var canvas = null;
var ctx = null;
var image = null;
var slider = null;
var vBox = null;
var x = 50;
var y = 50;
var scaleX;
var scaleY;
var center = {
x: 0,
y: 0
};
var radius = 50.0;
var angle = 0;
var result = false;
var imageData;
var data;
var backgroundImg = null;
function start() {
ctx = getCtxReference();
result = setOtherReferences();
image = getStarImages();
if (image != null)
image.addEventListener('load', Loop);
}
function getCtxReference() {
canvas = document.getElementById("canvas");
ctx = canvas.getContext('2d');
return ctx;
}
function setOtherReferences() {
slider = document.getElementById("rangeInput");
vBox = document.getElementById("textbox");
scaleX = 150;
scaleY = 150;
center.x = canvas.width / 3;
center.y = canvas.height / 3;
return true;
}
function getStarImages() {
var img = new Image();
img.src = createStar();
return img;
}
function createStar() {
ctx.fillStyle = '#FF0';
ctx.fillRect(Math.random() * 45, Math.random() * 45, scaleX, scaleY);
return canvas.toDataURL();
}
function drawImg() {
ctx.drawImage(image, x, y, scaleX, scaleY);
}
function Loop() {
window.setTimeout(Loop, 100);
ctx.clearRect(0, 0, canvas.width, canvas.height);
angle += Math.PI * 0.05;
x = center.x + radius * Math.cos(angle);
y = center.y + radius * Math.sin(angle);
vBox.value = slider.value;
updateStarScale();
drawImg();
}
function updateStarScale() {
if (vBox.value > 0) {
scaleX += vBox.value / 10;
scaleY += vBox.value / 10;
changeImgColorToBlue();
} else if (vBox.value < 0) {
scaleX -= Math.abs(vBox.value / 10);
scaleY -= Math.abs(vBox.value / 10);
changeImgColorToRed();
}
if (scaleX > 600 || scaleY > 600) {
scaleX = 600;
scaleY = 600;
} else if (scaleX < 50 || scaleY < 50) {
scaleX = 50;
scaleY = 50;
}
}
function changeImgColorToBlue() {
imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
data = imageData.data;
for (var i = 0; i < data.length; i += 4) {
//is our data black?
if (data[i] > 0 || data[i + 1] > 0 || data[i + 2] > 0) {
data[i] = 0; // red
data[i + 1] = 0; // green
data[i + 2] = 255; // blue
}
}
ctx.putImageData(imageData, 0, 0);
}
function changeImgColorToRed() {
imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
data = imageData.data;
for (var i = 0; i < data.length; i += 4) {
if (data[i] > 0 || data[i + 1] > 0 || data[i + 2] > 0) {
data[i] = 255; // red
data[i + 1] = 0; // green
data[i + 2] = 0; // blue
}
}
ctx.putImageData(imageData, 0, 0);
}
function getRandomArbitrary(min, max) {
return Math.random() * (max - min) + min;
}
start();
Edit
Ok, so if you only need to draw those moving stars, you can simplify a lot your code, especially about the changing color :
As each star is only a colored rectangle, you only have to store a color value (i.e hex) and update it when you want to the desired color. No bitmap calculation needed.
However, as your code is right now, if you try to create new stars, they will all follow the same path and scale update.
I think that you will have to rethink the way you update the position.
Here is an update, with simplification of the code and example showing the issue
function createStars() {
var imgCanvas = document.createElement('canvas');
imgCanvas.height = "500";
imgCanvas.width = "500";
var imgCtx = imgCanvas.getContext('2d');
imgCtx.fillStyle = 'black';
imgCtx.fillRect(0, 0, 500, 500)
imgCtx.fillStyle = '#FF0';
for (i = 0; i < Math.floor(Math.random() * 500) + 250; i++) {
imgCtx.fillRect(Math.random() * 500, Math.random() * 500, 1, 1)
}
document.body.style.backgroundImage = 'url(' + imgCanvas.toDataURL() + ')';
}
createStars();
var canvas = null;
var ctx = null;
var slider = null;
var vBox = null;
var x = 50;
var y = 50;
var center = {
x: 0,
y: 0
};
var radius = 50.0;
var angle = 0;
var result = false;
var color = "FF0"; // set the color as a global variable, avoiding a function to set it
var stars = []; // set an array that will contain all our moving stars
function start() {
canvas = document.getElementById("canvas");
ctx = canvas.getContext('2d');
result = setOtherReferences();
// append new stars to our array
stars.push(createStar());
stars.push(createStar());
stars.push(createStar());
// start the Loop()
Loop();
}
function setOtherReferences() {
slider = document.getElementById("rangeInput");
vBox = document.getElementById("textbox");
center.x = canvas.width / 3;
center.y = canvas.height / 3;
return true;
}
function createStar() {
// set moving stars as object, with their own x,y,width and height properties.
var star = {
xStart: Math.random() * 150, // used in order to avoid the exact
yStart: Math.random() * 150, // same position of your stars
x: this.xStart,
y: this.yStart,
w: 50,
h: 50
}
return star;
}
function drawImg() {
// set the moving stars color to the actual growing/shrinking state
ctx.fillStyle = color;
// for each of our moving stars, draw a rect
for (i = 0; i < stars.length; i++) {
ctx.fillRect(stars[i].x, stars[i].y, stars[i].w, stars[i].h);
}
}
function Loop() {
window.setTimeout(Loop, 100);
ctx.clearRect(0, 0, canvas.width, canvas.height);
angle += Math.PI * 0.05;
/*
Here is the main issue
as each of our stars x/y pos are updated with the same function,
they will follow each others.
I added the xStart property so they're not
exactly at the same position for you beeing able to see it.
*/
for (i = 0; i < stars.length; i++) {
stars[i].x = center.x + radius * Math.cos(angle) + stars[i].xStart;
stars[i].y = center.y + radius * Math.sin(angle) + stars[i].yStart;
}
vBox.value = slider.value;
updateStarScale();
drawImg();
}
function updateStarScale() {
//same as above, each of our stars will have the same scale update
for (i = 0; i < stars.length; i++) {
if (vBox.value > 0) {
stars[i].w += vBox.value / 10;
stars[i].h += vBox.value / 10;
color = "#00F";
} else if (vBox.value < 0) {
stars[i].w -= Math.abs(vBox.value / 10);
stars[i].h -= Math.abs(vBox.value / 10);
color = "#F00";
}
if (stars[i].w > 600 || stars[i].h > 600) {
stars[i].w = 600;
stars[i].h = 600;
} else if (stars[i].w < 5 || stars[i].h < 5) {
stars[i].w = 5;
stars[i].h = 5;
}
}
}
// Only call it if you haven't already done (i.e in a load event)
start();
body {
text-align: center;
background-image: url("stars.png");
}
#container {
position: fixed;
color: red;
top: 0px;
left: 0px;
}
#textBox {
position: absolute;
top: 25px;
left: 5px;
}
#slider {
position: absolute;
top: 25px;
left: 200px;
}
<canvas id="canvas" width="1024" height="768"></canvas>
<div id="container">
<div id="textBox">
Velocity:
<input type="text" id="textbox" value="0">
</div>
<div id="slider">
Slider:
<form oninput="amount.value=rangeInput.value">
<input type="range" id="rangeInput" name="rangeInput" min="-100" max="100" step="3" value="0">
<output name="amount" for="rangeInput">0</output>
</form>
</div>
</div>
Original answer
First, You will need to update your imageData each time you call changeImgColorToBlue.
Secondly, in order to not change all your pixels into blue, you will have to check if each pixel is in some range of color.
Assuming your star.png does look like a black background with colored dots over it, you can do:
for (var i = 0; i < data.length; i += 4) {
if( data[i]>0 || data[i+1]>0 || data[i+2]>0 ){
//is our pixel black?
data[i] = 0;// red
data[i + 1] = 0; // green
data[i + 2] = 255; // blue
}
}
Of course, you can change those conditions to match for the actual color of your dots with more precision by using e.g if your dots are yellow
if( data[i]>=200 && data[i+1]>=200 && data[i+2]<100 )
Also, I did some changes in your code as you had redundant calls to some functions.
//Create the images(Using a canvas for CORS issues)
function createStars(){
var imgCanvas = document.createElement('canvas');
imgCanvas.height="500";
imgCanvas.width="500";
var imgCtx = imgCanvas.getContext('2d');
imgCtx.fillStyle= 'black';
imgCtx.fillRect(0,0,500,500)
imgCtx.fillStyle= '#FF0';
for(i=0; i<Math.floor(Math.random()*500)+250; i++){
imgCtx.fillRect(Math.random()*500, Math.random()*500, 1,1)
}
document.body.style.backgroundImage='url('+imgCanvas.toDataURL()+')';
}
createStars();
function createStar(){
var imgCanvas = document.createElement('canvas');
imgCanvas.height="50";
imgCanvas.width="50";
var imgCtx = imgCanvas.getContext('2d');
imgCtx.fillStyle= '#FF0';
imgCtx.fillRect(Math.random()*45,Math.random()*45, 5,5);
return imgCanvas.toDataURL();
}
var canvas = null;
var ctx = null;
var image = null;
var slider = null;
var vBox = null;
var x = 50;
var y = 50;
var scaleX;
var scaleY;
var center = {
x: 0,
y: 0
};
var radius = 50.0;
var angle = 0;
var result = false;
var textActive = false;
var imgArr = null;
var imageData;
var data;
var backgroundImg = null;
function start() {
ctx = getCtxReference();
result = setOtherReferences();
image = getStarImages();
if (image != null && result && imgArr != null) {
Loop();
}
}
function getCtxReference() {
canvas = document.getElementById("canvas");
ctx = canvas.getContext('2d');
return ctx;
}
function setOtherReferences() {
slider = document.getElementById("rangeInput");
vBox = document.getElementById("textbox");
scaleX = 100;
scaleY = 100;
center.x = canvas.width / 3;
center.y = canvas.height / 3;
return true;
}
function drawImg() {
ctx.drawImage(image, x, y, scaleX, scaleY);
return true;
}
function Loop() {
window.setTimeout(Loop, 100);
ctx.clearRect(0,0,canvas.width,canvas.height);
ctx.drawImage(backgroundImg, 0,0);
angle += Math.PI * 0.05;
x = center.x + radius * Math.cos(angle);
y = center.y + radius * Math.sin(angle);
vBox.value = slider.value;
updateStarScale();
drawImg();
}
function getStarImages() {
//as they're all the same image, you don't need to make an array of them, simply make a loop below
var img = new Image();
img.addEventListener('load', drawBackgroundStar)
img.src = createStar();
return img;
}
function drawBackgroundStar() {
for (var i=0; i<500; i++) {
ctx.drawImage(image, getRandomArbitrary(0, canvas.width), getRandomArbitrary(0, canvas.height), getRandomArbitrary(5, 15), getRandomArbitrary(5, 15));
}
backgroundImg = new Image();
backgroundImg.addEventListener('load', Loop);
backgroundImg.src = canvas.toDataURL();
}
function updateStarScale() {
if (vBox.value > 0) {
scaleX += vBox.value / 10;
scaleY += vBox.value / 10;
changeImgColorToBlue();
} else if (vBox.value < 0) {
scaleX -= Math.abs(vBox.value / 10);
scaleY -= Math.abs(vBox.value / 10);
changeImgColorToRed();
}
if (scaleX > 600 || scaleY > 600) {
scaleX = 600;
scaleY = 600;
} else if (scaleX < 50 || scaleY < 50) {
scaleX = 50;
scaleY = 50;
}
}
function changeImgColorToBlue() {
imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
data = imageData.data;
for (var i = 0; i < data.length; i += 4) {
//is our data black?
if(data[i]>0||data[i+1]>0||data[i+2]>0){
data[i] = 0;// red
data[i + 1] = 0; // green
data[i + 2] = 255; // blue
}
}
ctx.putImageData(imageData, 0, 0);
}
function changeImgColorToRed() {
imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
data = imageData.data;
for (var i = 0; i < data.length; i += 4) {
if(data[i]>0||data[i+1]>0||data[i+2]>0){
data[i] = 255;// red
data[i + 1] = 0; // green
data[i + 2] = 0; // blue
}
}
ctx.putImageData(imageData, 0, 0);
}
function getRandomArbitrary(min, max) {
return Math.random() * (max - min) + min;
}
start();
body {
text-align: center;
}
#container {
position: fixed;
color: red;
top: 0px;
left: 0px;
}
#textBox {
position: absolute;
top: 25px;
left: 5px;
}
#slider {
position: absolute;
top: 25px;
left: 200px;
}
<canvas id="canvas" width="1024" height="768"></canvas>
<div id="container">
<div id="textBox">
Velocity:
<input type="text" id="textbox" value="0">
</div>
<div id="slider">
Slider:
<form oninput="amount.value=rangeInput.value">
<input type="range" id="rangeInput" name="rangeInput" min="-100" max="100" step="3" value="">
<output name="amount" for="rangeInput">0</output>
</form>
</div>
</div>
As you wrote it, the changeImgColorToBlue functions are only changing the background stars of your canvas. I'm not sure it is what you want to achieve so here is a way to only change this one dot :
function createStars(){
var imgCanvas = document.createElement('canvas');
imgCanvas.height="500";
imgCanvas.width="500";
var imgCtx = imgCanvas.getContext('2d');
imgCtx.fillStyle= 'black';
imgCtx.fillRect(0,0,500,500)
imgCtx.fillStyle= '#FF0';
for(i=0; i<Math.floor(Math.random()*500)+250; i++){
imgCtx.fillRect(Math.random()*500, Math.random()*500, 1,1)
}
document.body.style.backgroundImage='url('+imgCanvas.toDataURL()+')';
}
createStars();
function createStar(){
var imgCanvas = document.createElement('canvas');
imgCanvas.height="50";
imgCanvas.width="50";
var imgCtx = imgCanvas.getContext('2d');
imgCtx.fillStyle= '#FF0';
imgCtx.fillRect(Math.random()*45,Math.random()*45, 5,5);
return imgCanvas.toDataURL();
}
var canvas = null;
var ctx = null;
var starCanvas = null;
var starCtx = null;
var image = null;
var slider = null;
var vBox = null;
var x = 50;
var y = 50;
var scaleX;
var scaleY;
var center = {
x: 0,
y: 0
};
var radius = 50.0;
var angle = 0;
var result = false;
var textActive = false;
var imgArr = null;
var imageData;
var data;
var backgroundImg = null;
function start() {
ctx = getCtxReference();
starCtx = getStarReference();
result = setOtherReferences();
image = getStarImages();
if (image != null && result && imgArr != null && backgroundImg != null) {
Loop();
}
}
function getCtxReference() {
canvas = document.getElementById("canvas");
return canvas.getContext('2d');
}
function getStarReference() {
starCanvas = document.createElement("canvas");
starCanvas.height = 50;
starCanvas.width = 50;
starCanvas.id=('star');
document.body.appendChild(starCanvas);
return starCanvas.getContext('2d');
}
function setOtherReferences() {
slider = document.getElementById("rangeInput");
vBox = document.getElementById("textbox");
scaleX = 100;
scaleY = 100;
center.x = canvas.width / 3;
center.y = canvas.height / 3;
return true;
}
function drawImg() {
ctx.drawImage(starCanvas, x, y, scaleX, scaleY);
return true;
}
function Loop() {
window.setTimeout(Loop, 100);
ctx.clearRect(0,0,canvas.width,canvas.height);
ctx.drawImage(backgroundImg, 0,0);
angle += Math.PI * 0.05;
x = center.x + radius * Math.cos(angle);
y = center.y + radius * Math.sin(angle);
vBox.value = slider.value;
updateStarScale();
drawImg();
}
function getStarImages() {
//as they're all the same image, you don't need to make an array of them, simply make a loop below
var img = new Image();
img.addEventListener('load', drawBackgroundStar)
img.src = createStar();
return img;
}
function drawBackgroundStar() {
for (var i=0; i<500; i++) {
ctx.drawImage(image, getRandomArbitrary(0, canvas.width), getRandomArbitrary(0, canvas.height), getRandomArbitrary(5, 15), getRandomArbitrary(5, 15));
}
backgroundImg = new Image();
backgroundImg.addEventListener('load', Loop);
backgroundImg.src = canvas.toDataURL();
starCtx.drawImage(image, 0,0,50,50)
}
function updateStarScale() {
if (vBox.value > 0) {
scaleX += vBox.value / 10;
scaleY += vBox.value / 10;
changeImgColorToBlue();
} else if (vBox.value < 0) {
scaleX -= Math.abs(vBox.value / 10);
scaleY -= Math.abs(vBox.value / 10);
changeImgColorToRed();
}
if (scaleX > 600 || scaleY > 600) {
scaleX = 600;
scaleY = 600;
} else if (scaleX < 50 || scaleY < 50) {
scaleX = 50;
scaleY = 50;
}
}
function changeImgColorToBlue() {
imageData = starCtx.getImageData(0, 0, 50, 50);
data = imageData.data;
for (var i = 0; i < data.length; i += 4) {
//is our data black?
if(data[i]>0||data[i+1]>0||data[i+2]>0){
data[i] = 0;// red
data[i + 1] = 0; // green
data[i + 2] = 255; // blue
}
}
starCtx.putImageData(imageData, 0, 0);
}
function changeImgColorToRed() {
imageData = starCtx.getImageData(0, 0, 50, 50);
data = imageData.data;
for (var i = 0; i < data.length; i += 4) {
if(data[i]>0||data[i+1]>0||data[i+2]>0){
data[i] = 255;// red
data[i + 1] = 0; // green
data[i + 2] = 0; // blue
}
}
starCtx.putImageData(imageData, 0, 0);
}
function getRandomArbitrary(min, max) {
return Math.random() * (max - min) + min;
}
start();
body {
text-align: center;
}
#container {
position: fixed;
color: red;
top: 0px;
left: 0px;
}
#textBox {
position: absolute;
top: 25px;
left: 5px;
}
#slider {
position: absolute;
top: 25px;
left: 200px;
}
<canvas id="canvas" width="1024" height="768"></canvas>
<div id="container">
<div id="textBox">
Velocity:
<input type="text" id="textbox" value="0">
</div>
<div id="slider">
Slider:
<form oninput="amount.value=rangeInput.value">
<input type="range" id="rangeInput" name="rangeInput" min="-100" max="100" step="3" value="">
<output name="amount" for="rangeInput">0</output>
</form>
</div>
</div>

How to remove canvas background and display full background image

I am following this tutorial and trying to implement it on my website. I am struggling to remove the 'Black' background to show the full background image with the stars.
Here's jsFiddle: jFiddle
Here's the screen shot below.
Here's the jQuery for your inspection:
width = window.innerWidth,
height = 300;
// Add 2 shooting stars that just cycle.
entities.push(new ShootingStar());
entities.push(new ShootingStar());
//animate background
function animate() {
bgCtx.fillStyle = "black";
bgCtx.fillRect(0, 0, width, height);
bgCtx.fillStyle = '#fff';
bgCtx.strokeStyle = "#fff";
var entLen = entities.length;
while (entLen--) {
entities[entLen].update();
}
requestAnimationFrame(animate);
}
animate();
Any help would be great! thanks :)
In the animate()function, replace
bgCtx.fillStyle = "black";
bgCtx.fillRect(0, 0, width, height);
with
bgCtx.fillStyle = "rgba(0,0,0,0)";
bgCtx.clearRect(0, 0, width, height);
and remove this line bgCtx.fillRect(0, 0, width, height);(l80)
http://jsfiddle.net/aernk8kk/13/
(function () {
var requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame || window.msRequestAnimationFrame || function (callback) {
window.setTimeout(callback, 1000 / 60);
};
window.requestAnimationFrame = requestAnimationFrame;
})();
// Terrain stuff.
var background = document.getElementById("bgCanvas"),
bgCtx = background.getContext("2d"),
width = window.innerWidth,
height = 300;
(height < 400) ? height = 400 : height;
background.width = width;
background.height = height;
function Terrain(options) {
options = options || {};
this.terrain = document.createElement("canvas");
this.terCtx = this.terrain.getContext("2d");
this.scrollDelay = options.scrollDelay || 90;
this.lastScroll = new Date().getTime();
this.terrain.width = width;
this.terrain.height = height;
this.fillStyle = options.fillStyle || "#f30";
this.mHeight = options.mHeight || height;
// generate
this.points = [];
var displacement = options.displacement || 140,
power = Math.pow(2, Math.ceil(Math.log(width) / (Math.log(2))));
// set the start height and end height for the terrain
this.points[0] = this.mHeight;//(this.mHeight - (Math.random() * this.mHeight / 2)) - displacement;
this.points[power] = this.points[0];
// create the rest of the points
for (var i = 1; i < power; i *= 2) {
for (var j = (power / i) / 2; j < power; j += power / i) {
this.points[j] = ((this.points[j - (power / i) / 2] + this.points[j + (power / i) / 2]) / 2) + Math.floor(Math.random() * -displacement + displacement);
}
displacement *= 0.6;
}
document.body.appendChild(this.terrain);
}
Terrain.prototype.update = function () {
// draw the terrain
this.terCtx.clearRect(0, 0, width, height);
this.terCtx.fillStyle = this.fillStyle;
if (new Date().getTime() > this.lastScroll + this.scrollDelay) {
this.lastScroll = new Date().getTime();
this.points.push(this.points.shift());
}
this.terCtx.beginPath();
for (var i = 0; i <= width; i++) {
if (i === 0) {
this.terCtx.moveTo(0, this.points[0]);
} else if (this.points[i] !== undefined) {
this.terCtx.lineTo(i, this.points[i]);
}
}
this.terCtx.lineTo(width, this.terrain.height);
this.terCtx.lineTo(0, this.terrain.height);
this.terCtx.lineTo(0, this.points[0]);
this.terCtx.fill();
}
// Second canvas used for the stars
bgCtx.fillStyle = "rgb(255,255,255)";
// stars
function Star(options) {
this.size = Math.random() * 2;
this.speed = Math.random() * .05;
this.x = options.x;
this.y = options.y;
}
Star.prototype.reset = function () {
this.size = Math.random() * 2;
this.speed = Math.random() * .05;
this.x = width;
this.y = Math.random() * height;
}
Star.prototype.update = function () {
this.x -= this.speed;
if (this.x < 0) {
this.reset();
} else {
bgCtx.fillRect(this.x, this.y, this.size, this.size);
}
}
function ShootingStar() {
this.reset();
}
ShootingStar.prototype.reset = function () {
this.x = Math.random() * width;
this.y = 0;
this.len = (Math.random() * 80) + 10;
this.speed = (Math.random() * 10) + 6;
this.size = (Math.random() * 1) + 0.1;
// this is used so the shooting stars arent constant
this.waitTime = new Date().getTime() + (Math.random() * 3000) + 500;
this.active = false;
}
ShootingStar.prototype.update = function () {
if (this.active) {
this.x -= this.speed;
this.y += this.speed;
if (this.x < 0 || this.y >= height) {
this.reset();
} else {
bgCtx.lineWidth = this.size;
bgCtx.beginPath();
bgCtx.moveTo(this.x, this.y);
bgCtx.lineTo(this.x + this.len, this.y - this.len);
bgCtx.stroke();
}
} else {
if (this.waitTime < new Date().getTime()) {
this.active = true;
}
}
}
var entities = [];
// init the stars
for (var i = 0; i < height; i++) {
entities.push(new Star({
x: Math.random() * width,
y: Math.random() * height
}));
}
// Add 2 shooting stars that just cycle.
entities.push(new ShootingStar());
entities.push(new ShootingStar());
//animate background
function animate() {
bgCtx.fillStyle = "rgba(0,0,0,0)";
bgCtx.clearRect(0, 0, width, height);
bgCtx.fillStyle = '#fff';
bgCtx.strokeStyle = "#fff";
var entLen = entities.length;
while (entLen--) {
entities[entLen].update();
}
requestAnimationFrame(animate);
}
animate();
body, html {
color: #fff;
width: 100%;
height: 100%;
margin: 0;
padding: 0;
background: url(
http://cdn1.dottech.org/wp-content/uploads/2013/08/moon_clear_sky_wallpaper_2560x1440.jpg
) no-repeat center center fixed;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
}
canvas {
position:absolute;
top:0;
left:0
}
<canvas id="bgCanvas"></canvas>
check clearRect

Categories