I Want to create an radial timer.
The Problem is, the arc are not painting correctly, when i try to set the start and end angle.
Thats, what i want:
Here is my code:
var Timer = function Timer(selector) {
var _width = 134;
var _height = 134;
var _x = _width / 2;
var _y = _height / 2;
var _canvas = null;
var _context = null;
var _percentage = 0;
var _background = '#000000';
var _foreground = '#FF0000';
this.init = function init(selector) {
var element = document.querySelector(selector);
_canvas = document.createElement('canvas');
_canvas.setAttribute('width', _width);
_canvas.setAttribute('height', _height);
element.parentNode.replaceChild(_canvas, element);
_context = _canvas.getContext('2d');
this.paint();
};
this.clear = function clear() {
_context.clearRect(0, 0, _width, _height);
};
this.start = function start(seconds) {
var current = seconds;
var _watcher = setInterval(function AnimationInterval() {
_percentage = 100 * current / seconds;
if(_percentage < 0) {
_percentage = 0;
clearInterval(_watcher);
} else if(_percentage > 100) {
_percentage = 100;
clearInterval(_watcher);
}
this.paint();
console.log(_percentage + '%');
--current;
}.bind(this), 1000);
};
this.paint = function paint() {
this.clear();
this.paintBackground();
this.paintForeground();
};
this.paintForeground = function paintForeground() {
_context.beginPath();
_context.arc(_x, _y, 134 / 2 - 5, -(Math.PI / 2), ((Math.PI * 2) * _percentage) - (Math.PI / 2), false);
_context.lineWidth = 8;
_context.strokeStyle = _foreground;
_context.stroke();
};
this.paintBackground = function paintBackground() {
_context.beginPath();
_context.arc(_x, _y, 134 / 2 - 5, 0, Math.PI * 2, false);
_context.lineWidth = 10;
_context.strokeStyle = _background;
_context.stroke();
};
this.init(selector);
};
var timer = new Timer('timer');
timer.start(10);
<timer></timer>
Can you tell me, what i make wrong?
Related
Please be kind I'm a real beginner.
I'm trying to use this function twice on the same page (in different sections) but am unable to do this. I assume I somehow need to label it differently each time I use it, but can't figure out where.
Maybe the functions are not labeled correctly but I have tried trying this.
Here is the JS
(function () {
var lastTime = 0;
var vendors = ["ms", "moz", "webkit", "o"];
for (var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) {
window.requestAnimationFrame = window[vendors[x] + "RequestAnimationFrame"];
window.cancelAnimationFrame =
window[vendors[x] + "CancelAnimationFrame"] ||
window[vendors[x] + "CancelRequestAnimationFrame"];
}
if (!window.requestAnimationFrame)
window.requestAnimationFrame = function (callback, element) {
var currTime = new Date().getTime();
var timeToCall = Math.max(0, 16 - (currTime - lastTime));
var id = window.setTimeout(function () {
callback(currTime + timeToCall);
}, timeToCall);
lastTime = currTime + timeToCall;
return id;
};
if (!window.cancelAnimationFrame)
window.cancelAnimationFrame = function (id) {
clearTimeout(id);
};
})();
var Nodes = {
// Settings
density: 20,
reactionSensitivity: 10,
points: [],
lines: [[], [], [], []],
mouse: { x: 10, y: 10, down: false },
animation: null,
canvas: null,
context: null,
init: function () {
// Set up the visual canvas
this.canvas = document.getElementById("stripes2");
this.context = this.canvas.getContext("2d");
this.context.lineJoin = "bevel";
this.canvas.width = window.innerHeight*2;
this.canvas.height = window.innerHeight;
this.canvas.style.display = "block";
this.canvas.addEventListener("mousemove", this.mouseMove, false);
this.canvas.addEventListener("mousedown", this.mouseDown, false);
this.canvas.addEventListener("mouseup", this.mouseUp, false);
this.canvas.addEventListener("mouseout", this.mouseOut, false);
window.onresize = function (event) {
Nodes.canvas.width = (window.innerHeight*2);
Nodes.canvas.height = Math.max(window.innerHeight, 1000);
Nodes.onWindowResize();
};
this.preparePoints();
this.draw();
},
preparePoints: function () {
// Clear the current points
this.points = [];
this.lines = [[], [], [], [], []];
var width, height, i;
var center = window.innerHeight / 2;
for (i = -1000; i < this.canvas.width + 1000; i += this.density) {
var line1 = { y: center - 17, originalY: center - -100, color: "#249FA4" };
var line2 = { y: center - 17, originalY: center - -50, color: "#3DB8B5" };
var line3 = { y: center - 17, originalY: center - 0, color: "#F8DCAA" };
var line4 = { y: center - 17, originalY: center - 50, color: "#F1B30A" };
var line5 = { y: center - 17, originalY: center - 100, color: "#E77419" };
line1["x"] = i;
line1["originalX"] = i;
line2["x"] = i;
line2["originalX"] = i;
line3["x"] = i;
line3["originalX"] = i;
line4["x"] = i;
line4["originalX"] = i;
line5["x"] = i;
line5["originalX"] = i;
this.points.push(line1);
this.points.push(line2);
this.points.push(line3);
this.points.push(line4);
this.points.push(line5);
this.lines[0].push(line1);
this.lines[1].push(line2);
this.lines[2].push(line3);
this.lines[3].push(line4);
this.lines[4].push(line5);
}
},
updatePoints: function () {
var i, currentPoint, theta, distance;
for (i = 0; i < this.points.length; i++) {
currentPoint = this.points[i];
theta = Math.atan2(
currentPoint.y - this.mouse.y,
currentPoint.x - this.mouse.x
);
if (this.mouse.down) {
distance =
(this.reactionSensitivity * 300) /
Math.sqrt(
(this.mouse.x - currentPoint.x) * (this.mouse.x - currentPoint.x) +
(this.mouse.y - currentPoint.y) * (this.mouse.y - currentPoint.y)
);
} else {
distance =
(this.reactionSensitivity * 150) /
Math.sqrt(
(this.mouse.x - currentPoint.x) * (this.mouse.x - currentPoint.x) +
(this.mouse.y - currentPoint.y) * (this.mouse.y - currentPoint.y)
);
}
currentPoint.x +=
Math.cos(theta) * distance +
(currentPoint.originalX - currentPoint.x) * 0.07;
currentPoint.y +=
Math.sin(theta) * distance +
(currentPoint.originalY - currentPoint.y) * 0.07;
}
},
drawPoints: function () {
var i, currentPoint;
for (i = 0; i < 5; i++) {
var line = this.lines[i];
this.context.beginPath();
this.context.lineJoin = "round";
this.context.moveTo(line[0].x, line[0].y);
this.context.strokeStyle = line[0].color;
this.context.lineWidth = 50;
for (var j = 1; j < line.length - 2; j++) {
var point = line[j];
var xc = (point.x + line[j + 1].x) / 2;
var yc = (point.y + line[j + 1].y) / 2;
this.context.quadraticCurveTo(point.x, point.y, xc, yc);
}
this.context.stroke();
this.context.closePath();
}
},
draw: function () {
this.animation = requestAnimationFrame(function () {
Nodes.draw();
});
this.clear();
this.updatePoints();
this.drawPoints();
},
clear: function () {
this.canvas.width = this.canvas.width;
},
mouseDown: function (event) {
Nodes.mouse.down = true;
},
mouseUp: function (event) {
Nodes.mouse.down = false;
},
mouseMove: function (event) {
Nodes.mouse.x = event.pageY;
Nodes.mouse.y = event.pageY;
},
mouseOut: function (event) {
Nodes.mouse.x = -1000;
Nodes.mouse.y = -1000;
Nodes.mouse.down = false;
},
// Resize and redraw the canvas.
onWindowResize: function () {
cancelAnimationFrame(this.animation);
this.preparePoints();
this.draw();
}
};
// Start the app.
setTimeout(function () {
Nodes.init();
}, 10);
<canvas id="stripes2" class="container">
Many thanks
I just made this animation using canvas. Shows a number of bubbles scrolling from top to bottom. Clicking on any bubble starts it moving top to bottom again.
I plan to add a counter of the number of bubbles clicked/picked with a localStorage but I have difficulties implementing it.
Here is how I implemented it.
Each bubble now has id property.
Every time you run the script, it puts empty array to localStorage.clickedBubbles.
When a bubble is clicked, the array is checked if it contains the id. If not, the id is pushed to local storage.
Also, each click the count is logged to console.
const INITIALIZATION = 100;
const STEP1 = 200;
const BUBBLES = 10;
const SPEED = 10;
let counter = 0;
localStorage.setItem("clickedBubbles", "[]");
function Bubble(x, y, radio) {
this.id = counter++;
this.x = x;
this.y = y;
this.radio = radio;
this.color = "blue";
this.speed = 5;
this.getId = function () {
return this.id;
};
this.getX = function () {
return this.x;
};
this.getY = function () {
return this.y;
};
this.getRadio = function () {
return this.radio;
};
this.getColor = function () {
return this.color;
};
this.getspeed = function () {
return this.speed;
};
this.setX = function (x) {
this.x = x;
};
this.setY = function (y) {
this.y = y;
};
this.setRadio = function (radio) {
this.radio = radio;
};
this.setColor = function (color) {
this.color = color;
};
this.setSpeed = function (speed) {
this.speed = speed;
};
this.draw = function (ctx) {
ctx.save();
ctx.fillStyle = this.color;
ctx.beginPath();
ctx.arc(this.x, this.y, this.radio, 0, Math.PI * 2, true);
ctx.fill();
ctx.fillStyle = "white";
ctx.beginPath();
ctx.arc(
this.x + this.radio / 3,
this.y - this.radio / 3,
this.radio / 4,
0,
Math.PI * 2,
true
);
ctx.fill();
ctx.restore();
};
this.coordinates = function (x, y) {
var ax = this.getX() - this.getRadio();
var ay = this.getY() - this.getRadio();
return (
x >= ax &&
x <= ax + 2 * this.getRadio() &&
y >= ay &&
y <= ay + 2 * this.getRadio()
);
};
}
function animationBubbles() {
var bubbles = [];
var arrayColors;
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var status = INITIALIZATION;
var app = this;
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
this.click = function (e) {
var x = e.x || e.pageX || e.clientX;
var y = e.y || e.clientY || e.pageY;
const clickedArr = JSON.parse(localStorage.getItem("clickedBubbles"));
for (var i = 0; i < bubbles.length; i++) {
var aux = bubbles[i];
if (aux.coordinates(x, y)) {
if (!clickedArr.includes(aux.getId())) {
clickedArr.push(aux.getId());
localStorage.setItem("clickedBubbles", JSON.stringify(clickedArr));
}
aux.setY(0);
break;
}
}
console.log("Clicked count: " + clickedArr.length);
};
canvas.addEventListener("mousedown", this.click, false);
this.realizeAnimation = function () {
ctx.clearRect(0, 0, canvas.width, canvas.height);
for (var i = 0; i < bubbles.length; i++) {
var aux = bubbles[i];
if (aux.getY() < canvas.height) {
aux.setY(aux.getY() + aux.getspeed());
} else {
aux.setY(0);
aux.setColor(arrayColors[Math.floor(Math.random() * 4)]);
}
aux.draw(ctx);
}
setTimeout(app.realizeAnimation, 100);
};
this.createBubbles = function () {
for (var i = 1; i <= BUBBLES; i++) {
var burbuja = new Bubble(
canvas.width * (i / BUBBLES),
0,
this.generateRandom(Math.floor(canvas.width / 20))
);
burbuja.setSpeed(SPEED);
burbuja.setColor(arrayColors[this.generateRandom(4)]);
bubbles.push(burbuja);
}
};
this.generateRandom = function (num) {
return Math.floor(Math.random() * num);
};
this.initColor = function () {
arrayColors[0] = "#C923C9";
arrayColors[1] = "#FAEF20";
arrayColors[2] = "#20ECFA";
arrayColors[3] = "#FA209C";
};
this.machineStates = function () {
if (status === INITIALIZATION) {
arrayColors = [];
this.initColor();
this.createBubbles();
status = STEP1;
setTimeout(app.machineStates, 100);
} else {
app.realizeAnimation();
}
};
this.machineStates();
}
new animationBubbles();
I'm currently working on a particle system where the particles move around and create pictures with some seconds in between (almost like a slide). I know where to put the color code to change the color on the particles forming the pictures bur for some reason it doesn't work. I therefore suspect that the problem is somewhere else in the script but the question is where...
You can see the code below (tried to make a codepen but it didn't work):
var dispersed = false;
var firstDone = false;
var secondDone = false;
var thirdDone = false;
var fRgba = []; // first img rgba data
var sRgba = []; // second img rgba data
var tRgba = []; // third img rgba data
var WIDTH = window.innerWidth,
HEIGHT = window.innerHeight;
var VIEW_ANGLE = 45,
ASPECT = WIDTH / HEIGHT,
NEAR = 0.01,
FAR = 10000;
var $container = $("#container");
var renderer = new THREE.WebGLRenderer();
var camera = new THREE.PerspectiveCamera(
VIEW_ANGLE,
ASPECT,
NEAR,
FAR);
var scene = new THREE.Scene();
scene.add(camera);
camera.position.z = 900;
renderer.setSize(WIDTH, HEIGHT);
$container.append(renderer.domElement);
var particleCount = 5200,
particles = new THREE.Geometry();
var pMaterial = new THREE.PointsMaterial({
size: 6,
map: createCircleTexture('#CACACA', 256),
transparent: true,
depthWrite: false
});
function createCircleTexture(color, size) {
var matCanvas = document.createElement('canvas');
matCanvas.width = matCanvas.height = size;
var matContext = matCanvas.getContext('2d');
var texture = new THREE.Texture(matCanvas);
var center = size / 2;
matContext.beginPath();
matContext.arc(center, center, size/2, 0, 2 * Math.PI, false);
matContext.closePath();
matContext.fillStyle = color;
matContext.fill();
texture.needsUpdate = true;
return texture;
}
for (var i = 0; i < particleCount; i++) {
var x = Math.random() * 1600 - 800;
var y = getRandomInt(600, 1500)
var z = Math.random() * 30 - 15;
var particle = new THREE.Vector3(x, y, z);
particle.updated = 0;
particles.vertices.push(particle);
};
var particleSystem = new THREE.Points(particles, pMaterial);
particleSystem.sortParticles = true;
scene.add(particleSystem);
function drawImage(imageObj, array) {
var canvas = $("#canvas")[0];
var context = canvas.getContext("2d");
var imageX = 0;
var imageY = 0;
var imageWidth = imageObj.width;
var imageHeight = imageObj.height;
context.drawImage(imageObj, imageX, imageY);
var imageData = context.getImageData(imageX, imageY, imageWidth,
imageHeight);
var data = imageData.data;
for(var y = 0; y < imageHeight; y+= 4) {
for(var x = 0; x < imageWidth; x+= 4) {
var red = data[((imageWidth * y) + x) * 4];
var green = data[((imageWidth * y) + x) * 4 + 1];
var blue = data[((imageWidth * y) + x) * 4 + 2];
var alpha = data[((imageWidth * y) + x) * 4 + 3];
if (red < 100) {
var pX = (x % 500) - 249;
var pY = 249 - y;
array.push([pX, pY, red, green, blue, alpha]);
}
}
}
};
var addDestination = function(particle, x, y, z) {
var dest = new THREE.Vector3(x, y, z);
particle.destination = dest;
};
var addVelocity = function(particle) {
var xDiff = (particle.destination.x - particle.x) / 180;
var yDiff = (particle.destination.y - particle.y) / 180;
var zDiff = (particle.destination.z - particle.z) / 180;
var vel = new THREE.Vector3(xDiff, yDiff, zDiff);
particle.velocity = vel;
};
var move = function(particle) {
particle.x += particle.velocity.x;
particle.y += particle.velocity.y;
particle.z += particle.velocity.z;
particle.updated += 1;
};
var slowDown = function(particle) {
particle.velocity.x -= (particle.velocity.x / 300)
particle.velocity.y -= (particle.velocity.y / 300)
particle.velocity.z -= (particle.velocity.z / 160)
};
var resetProperties = function() {
var pCount = particleCount;
while (pCount--) {
var particle = particles.vertices[pCount];
particle.destination = null
particle.updated = 0;
};
};
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min)) + min;
};
var distributedZ = function(level) {
var z;
if (level === 1) {
z = getRandomInt(50, 100);
} else if (level === 2) {
z = getRandomInt(350, 400);
} else {
z = getRandomInt(650, 700);
}
return z;
};
function shuffle(array) {
var currentIndex = array.length, temporaryValue, randomIndex;
while (0 !== currentIndex) {
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex -= 1;
temporaryValue = array[currentIndex];
array[currentIndex] = array[randomIndex];
array[randomIndex] = temporaryValue;
}
return array;
};
var disperse = function() {
pCount = particleCount;
for (var i = 0; i < pCount; i++) {
var particle = particles.vertices[i];
if (typeof(particle.destination) === "undefined") {
var nums = [-1, 1];
var x = particle.x + nums[Math.round(Math.random())];
var y = particle.y - 1000;
var z = Math.random() * 30 - 15;
addDestination(particle, x, y, z);
particle.velocity = new THREE.Vector3(x - particle.x, -3, z -
particle.z);
}
if (particle.updated <= 300) {
move(particle);
} else {
particles.vertices = shuffle(particles.vertices);
resetProperties();
dispersed = true;
return;
}
}
}
var morphImageParticles = function(imageParticles, rgba) {
for (var i = 0; i < imageParticles.length; i++) {
var particle = imageParticles[i]
if (particle.destination === null) {
var pixelData = rgba[i];
var x = pixelData[0];
var y = pixelData[1];
var z = Math.random() * 15 - 7;
addDestination(particle, x, y, z);
addVelocity(particle);
}
if (particle.updated <= 180) {
move(particle);
}
}
};
var morphOuterParticles = function(outerParticles, ord) {
for (var i = 0; i < outerParticles.length; i++) {
var nums = [-1, 1];
var particle = outerParticles[i];
if (particle.destination === null) {
var x = Math.random() * 1000 - 500;
var y = Math.random() * 1000 - 500;
var z;
if (i <= Math.round(outerParticles.length * 0.6)) {
z = distributedZ(1)
} else if (i > Math.round(outerParticles.length * 0.6) && i <
Math.round(outerParticles.length * 0.9)) {
z = distributedZ(2)
} else {
z = distributedZ(3);
}
addDestination(particle, x, y, z);
addVelocity(particle);
}
if (particle.updated <= 600) {
move(particle);
slowDown(particle);
} else {
particles.vertices = shuffle(particles.vertices);
resetProperties();
if (ord === 1) {
firstDone = true;
} else if (ord === 2) {
secondDone = true;
} else {
thirdDone = true;
}
return;
}
}
};
var makeImg = function(rgba, ord) {
var pCount = particleCount;
var imagePs = particles.vertices.slice(0, rgba.length);
var outerPs = particles.vertices.slice(rgba.length, pCount);
morphImageParticles(imagePs, rgba);
morphOuterParticles(outerPs, ord);
};
var update = function() {
if (thirdDone) {
} else if (secondDone) {
makeImg(tRgba, 3);
} else if (firstDone) {
makeImg(sRgba, 2);
} else if (dispersed) {
makeImg(fRgba, 1);
} else {
disperse();
}
particleSystem.geometry.verticesNeedUpdate = true;
renderer.render(scene, camera);
requestAnimationFrame(update);
TWEEN.update();
};
var rotXScale = d3.scale.linear().domain([0, window.innerHeight]).range([15,
-15]);
var rotYScale = d3.scale.linear().domain([0, window.innerWidth]).range([25,
-25]);
d3.select("body").on("mousemove", function() {
var scaledX = rotXScale(d3.mouse(this)[1]) * Math.PI / 180;
var scaledY = rotYScale(d3.mouse(this)[0]) * Math.PI / 180;
var tween = new TWEEN.Tween(particleSystem.rotation).to({ x: scaledX, y:
scaledY, z: 0 });
tween.easing( TWEEN.Easing.Quartic.Out);
tween.start();
transparency: true
});
var img1 = new Image();
var img2 = new Image();
var img3 = new Image();
img1.onload = function() {
drawImage(this, fRgba);
img2.onload = function() {
drawImage(this, sRgba);
img3.onload = function() {
drawImage(this, tRgba);
}
img3.src = "images/p1.png";
}
img2.src = "images/p2.png";
update();
}
img1.src = "images/p3.png";
update();
I thought I only need to add the code below, for example ['0xffffff'], that's how it should work at least but it didn't. Therefore I guess the problem is somewhere else in the script.
var fRgba = []; // first img rgba data
var sRgba = []; // second img rgba data
var tRgba = []; // third img rgba data
The Problem
I am creating a game that involves dodging projectiles. The player is in control of an image of a ship and I dont want the ship to move exactly together as this looks very unrealistic.
The Question
Is there a way to control how fast the image moves, how can i slow the movemnt of the image down?
The Code
var game = create_game();
game.init();
//music
var snd = new Audio("Menu.mp3");
snd.loop = true;
snd.play();
document.getElementById('mute').addEventListener('click', function (evt) {
if ( snd.muted ) {
snd.muted = false
evt.target.innerHTML = 'mute'
}
else {
snd.muted = true
evt.target.innerHTML = 'unmute'
}
})
function create_game() {
debugger;
var level = 1;
var projectiles_per_level = 1;
var min_speed_per_level = 1;
var max_speed_per_level = 2;
var last_projectile_time = 0;
var next_projectile_time = 0;
var width = 600;
var height = 500;
var delay = 1000;
var item_width = 30;
var item_height = 30;
var total_projectiles = 0;
var projectile_img = new Image();
var projectile_w = 30;
var projectile_h = 30;
var player_img = new Image();
var c, ctx;
var projectiles = [];
var player = {
x: 200,
y: 400,
score: 0
};
function init() {
projectile_img.src = "projectile.png";
player_img.src = "player.png";
level = 1;
total_projectiles = 0;
projectiles = [];
c = document.getElementById("c");
ctx = c.getContext("2d");
ctx.fillStyle = "#ff6600";
ctx.fillRect(0, 0, 500, 600);
c.addEventListener("mousemove", function (e) {
//moving over the canvas.
var bounding_box = c.getBoundingClientRect();
player.x = (e.clientX - bounding_box.left) * (c.width / bounding_box.width) - player_img.width / 2;
}, false);
setupProjectiles();
requestAnimationFrame(tick);
}
function setupProjectiles() {
var max_projectiles = level * projectiles_per_level;
while (projectiles.length < max_projectiles) {
initProjectile(projectiles.length);
}
}
function initProjectile(index) {
var max_speed = max_speed_per_level * level;
var min_speed = min_speed_per_level * level;
projectiles[index] = {
x: Math.round(Math.random() * (width - 2 * projectile_w)) + projectile_w,
y: -projectile_h,
v: Math.round(Math.random() * (max_speed - min_speed)) + min_speed,
delay: Date.now() + Math.random() * delay
}
total_projectiles++;
}
function collision(projectile) {
if (projectile.y + projectile_img.height < player.y + 74) {
return false;
}
if (projectile.y > player.y + 74) {
return false;
}
if (projectile.x + projectile_img.width < player.x + 177) {
return false;
}
if (projectile.x > player.x + 177) {
return false;
}
return true;
}
function maybeIncreaseDifficulty() {
level = Math.max(1, Math.ceil(player.score / 10));
setupProjectiles();
}
function tick() {
var i;
var projectile;
var dateNow = Date.now();
c.width = c.width;
for (i = 0; i < projectiles.length; i++) {
projectile = projectiles[i];
if (dateNow > projectile.delay) {
projectile.y += projectile.v;
if (collision(projectile)) {
initProjectile(i);
player.score++;
} else if (projectile.y > height) {
initProjectile(i);
} else {
ctx.drawImage(projectile_img, projectile.x, projectile.y);
}
}
}
ctx.font = "bold 24px sans-serif";
ctx.fillStyle = "#ff6600";
ctx.fillText(player.score, c.width - 50, 50);
ctx.fillText("Level: " + level, 20, 50);
ctx.drawImage(player_img, player.x, player.y);
maybeIncreaseDifficulty();
requestAnimationFrame(tick);
}
return {
init: init
};
}
https://jsfiddle.net/a6nmy804/4/ (Broken)
Throttle the player's movement using a "timeout" countdown
Create a global var playerFreezeCountdown=0.
In mousemove change player.x only if playerFreezeCountdown<=0.
If playerFreezeCountdown>0 you don't change player.x.
If playerFreezeCountdown<=0 you both change player.x and also set playerFreezeCountdown to a desired "tick timeout" value: playerFreezeCountdown=5. This timeout will cause prevent the player from moving their ship until 5 ticks have passed.
In tick, always decrement playerFreezeCountdown--. This will indirectly allow a change to player.x after when playerFreezeCountdown is decremented to zero or below zero.
I am trying to convert my canvas code into backbone app...
can you guys tell me how to fix it...
providing my code below...
i referred a sample code but could not figure it out...
proving my fiddle and code below...
http://jsfiddle.net/JB9yg/191/
this is my working code without backbone http://jsfiddle.net/QhfVg/7/
var Box = Backbone.Model.extend({
defaults: {
var SIZE = 200;
var SPINNER_WIDTH = 20;
var STEP_PERCENT = 1;
var STEP_DELAY = 20;
var radius, centerX, centerY;
radius = centerX = centerY = SIZE / 2;
var deg360 = Math.PI * 2;
var deg60 = deg360 / 6;
var deg30 = deg360 / 12;
var deg1 = Math.PI / 360;
var deg2 = deg1 * 2;
var degStart = -Math.PI / 2;
var canvas = document.getElementById(id);
canvas.width = canvas.height = SIZE;
var ctx = canvas.getContext('2d');
var percent = 0;
}
});
Your sample code makes me confused :-D,the code below shows the canvas,I hope it works for you:
$(function () {
var SIZE = 200;
var SPINNER_WIDTH = 20;
var STEP_PERCENT = 1;
var STEP_DELAY = 20;
var radius, centerX, centerY;
radius = centerX = centerY = SIZE / 2;
var deg360 = Math.PI * 2;
var deg60 = deg360 / 6;
var deg30 = deg360 / 12;
var deg1 = Math.PI / 360;
var deg2 = deg1 * 2;
var degStart = -Math.PI / 2;
var Box = Backbone.Model.extend({
defaults: {
x: 0,
y: 0,
w: 1,
h: 1,
color: "#FF9000",
linewidth: 3
}});
var BoxSet = Backbone.Collection.extend({
model: Box
});
var BoxView = Backbone.View.extend({
tagName: "canvas",
attributes: {
id: _.uniqueId("canvas")
},
percent: 0,
render: function () {
console.log("Rendering ==> " + this.model.get("name"));
this.start(this.el);
return this;
},
start: function (canvas) {
canvas.width = canvas.height = SIZE;
this.ctx = canvas.getContext('2d');
this.animate();
},
animate: function () {
var self = this, deg, i, n, from, to;
this.ctx.width = this.ctx.height = SIZE;
this.percent += STEP_PERCENT;
deg = this.percent / 100 * deg360;
this.drawArc('#aaa', radius, deg360);
this.drawArc('#0e728e', radius, deg);
for (i = 0, n = Math.floor(deg / deg60); i < n; i++) {
from = i * deg30 + deg2;
to = from + deg30 - deg2 * 2
this.drawArc('#250696', radius, to, from);
}
this.drawArc('#fff', radius - SPINNER_WIDTH, deg360);
if (this.percent >= 100) {
document.getElementById('text').innerText = 'FINISHED';
} else {
setTimeout(function () {
self.animate();
}, STEP_DELAY);
}
},
drawArc: function (color, arcRadius, degTo, degFrom) {
if (!degFrom) {
degFrom = 0;
}
this.ctx.fillStyle = color;
this.ctx.beginPath();
this.ctx.moveTo(centerX, centerY);
this.ctx.arc(centerX, centerY, arcRadius, degStart + degFrom, degStart + degTo, false);
this.ctx.lineTo(centerX, centerY);
this.ctx.fill();
}
});
var BoxSetView = Backbone.View.extend({
className: "container",
render: function () {
this.collection.each(function (model) {
var boxView = new BoxView({model: model});
this.$el.append(boxView.render().$el)
}, this);
return this;
}
});
var c = new BoxSet([
{
name: "canvas1"
},
{
name: "canvas2"
},
{
name: "canvas3"
},
{
name: "canvas4"
}
]);
var v = new BoxSetView({
collection: c
});
$("body").append(v.render().$el);
});