Can't repeat js function in same page - javascript

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

Related

want to style the all dots of pre built html canvas background

The code is different, I apologize may I didn't ask the question the right way, you can understand well in principle, When I'm hovering the dots get colours and connect to each other, other dots are invisible, I want that all dots should be visible all time. live example available on codepen, https://codepen.io/tati420/pen/RwBamQo?editors=1111
(function () {
var width,
height,
largeHeader,
canvas,
ctx,
points,
target,
animateHeader = true;
// Main
initHeader();
initAnimation();
addListeners();
function initHeader() {
width = window.innerWidth;
height = window.innerHeight;
target = { x: width / 2, y: height / 2 };
largeHeader = document.getElementById("large-header");
largeHeader.style.height = height + "px";
canvas = document.getElementById("demo-canvas");
canvas.width = width;
canvas.height = height;
ctx = canvas.getContext("2d");
// create points
points = [];
for (var x = 0; x < width; x = x + width / 20) {
for (var y = 0; y < height; y = y + height / 20) {
var px = x + (Math.random() * width) / 20;
var py = y + (Math.random() * height) / 20;
var p = { x: px, originX: px, y: py, originY: py };
points.push(p);
}
}
// for each point find the 5 closest points
for (var i = 0; i < points.length; i++) {
var closest = [];
var p1 = points[i];
for (var j = 0; j < points.length; j++) {
var p2 = points[j];
if (!(p1 == p2)) {
var placed = false;
for (var k = 0; k < 5; k++) {
if (!placed) {
if (closest[k] == undefined) {
closest[k] = p2;
placed = true;
}
}
}
for (var k = 0; k < 5; k++) {
if (!placed) {
if (getDistance(p1, p2) < getDistance(p1, closest[k])) {
closest[k] = p2;
placed = true;
}
}
}
}
}
p1.closest = closest;
}
// assign a circle to each point
for (var i in points) {
var c = new Circle(
points[i],
2 + Math.random() * 2,
"rgba(0,255,255,0.3)"
);
points[i].circle = c;
}
}
// Event handling
function addListeners() {
if (!("ontouchstart" in window)) {
window.addEventListener("mousemove", mouseMove);
}
window.addEventListener("scroll", scrollCheck);
window.addEventListener("resize", resize);
}
function mouseMove(e) {
var posx = (posy = 0);
if (e.pageX || e.pageY) {
posx = e.pageX;
posy = e.pageY;
} else if (e.clientX || e.clientY) {
posx =
e.clientX +
document.body.scrollLeft +
document.documentElement.scrollLeft;
posy =
e.clientY +
document.body.scrollTop +
document.documentElement.scrollTop;
}
target.x = posx;
target.y = posy;
}
function scrollCheck() {
if (document.body.scrollTop > height) animateHeader = false;
else animateHeader = true;
}
function resize() {
width = window.innerWidth;
height = window.innerHeight;
largeHeader.style.height = height + "px";
canvas.width = width;
canvas.height = height;
}
// animation
function initAnimation() {
animate();
for (var i in points) {
shiftPoint(points[i]);
}
}
function animate() {
if (animateHeader) {
ctx.clearRect(0, 0, width, height);
for (var i in points) {
// detect points in range
if (Math.abs(getDistance(target, points[i])) < 4000) {
points[i].active = 0.3;
points[i].circle.active = 0.6;
} else if (Math.abs(getDistance(target, points[i])) < 20000) {
points[i].active = 0.1;
points[i].circle.active = 0.3;
} else if (Math.abs(getDistance(target, points[i])) < 40000) {
points[i].active = 0.02;
points[i].circle.active = 0.1;
} else {
points[i].active = 0;
points[i].circle.active = 0;
}
drawLines(points[i]);
points[i].circle.draw();
}
}
requestAnimationFrame(animate);
}
function shiftPoint(p) {
TweenLite.to(p, 1 + 1 * Math.random(), {
x: p.originX - 50 + Math.random() * 100,
y: p.originY - 50 + Math.random() * 100,
ease: Circ.easeInOut,
onComplete: function () {
shiftPoint(p);
},
});
}
ctx.strokeStyle = "rgba(255,0,0," + p.active + ")";
// Canvas manipulation
function drawLines(p) {
if (!p.active) return;
for (var i in p.closest) {
ctx.beginPath();
ctx.moveTo(p.x, p.y);
ctx.lineTo(p.closest[i].x, p.closest[i].y);
ctx.strokeStyle = "rgba(0,255,255," + p.active + ")";
ctx.stroke();
}
}
function Circle(pos, rad, color) {
var _this = this;
// constructor
(function () {
_this.pos = pos || null;
_this.radius = rad || null;
_this.color = color || null;
})();
this.draw = function () {
if (!_this.active) return;
ctx.beginPath();
ctx.arc(_this.pos.x, _this.pos.y, _this.radius, 0, 2 * Math.PI, false);
ctx.fillStyle = "rgba(0,255,0," + _this.active + ")";
ctx.fill();
};
}
// Util
function getDistance(p1, p2) {
return Math.pow(p1.x - p2.x, 2) + Math.pow(p1.y - p2.y, 2);
}
})();
If I understand your question correctly, you just want to make sure that every point.active = 1 and point.circle.active = 1:
function animate() {
if (animateHeader) {
ctx.clearRect(0, 0, width, height);
for (var i in points) {
points[i].active = 1;
points[i].circle.active = 1;
drawLines(points[i]);
points[i].circle.draw();
}
}
requestAnimationFrame(animate);
}

Canvas particle animation mobile touch event with elements positioned on top

I have this canvas particle animation that follows the mouse event correctly but it does not follow a touch event on mobile. I realized that it's because I have this animation beneath the rest of the content which is positioned on top. When there is something on top of the canvas that it's hitting, it does not trigger the touch event. I'm hoping someone can help me figure out how to avoid this issue so that the animation will still follow the user underneath the page content.
JS
var PI2 = Math.PI * 2;
var HALF_PI = Math.PI / 2;
var isTouch = 'ontouchstart' in window;
var isSafari = !!navigator.userAgent.match(/Version\/[\d\.]+.*Safari/);
function Canvas(options) {
options = _.clone(options || {});
this.options = _.defaults(options, this.options);
this.el = this.options.el;
this.ctx = this.el.getContext('2d');
this.dpr = window.devicePixelRatio || 1;
this.updateDimensions();
window.addEventListener('resize', this.updateDimensions.bind(this), false);
this.resetTarget();
if(isTouch){
// touch
this.el.addEventListener('touchstart', this.touchMove.bind(this), false);
this.el.addEventListener('touchmove', this.touchMove.bind(this), false);
// this.el.addEventListener('touchend', this.resetTarget.bind(this), false);
} else {
// Mouse
window.addEventListener('mousemove', this.mouseMove.bind(this), false);
window.addEventListener('mouseout', this.resetTarget.bind(this), false);
}
this.setupParticles();
this.loop();
}
Canvas.prototype.updateDimensions = function() {
this.width = this.el.width = _.result(this.options, 'width') * this.dpr;
this.height = this.el.height = _.result(this.options, 'height') * this.dpr;
this.el.style.width = _.result(this.options, 'width') + 'px';
this.el.style.height = _.result(this.options, 'height') + 'px';
}
// Update the orb target
Canvas.prototype.mouseMove = function(event) {
this.target = new Vector(event.clientX * this.dpr, event.clientY* this.dpr);
}
// Reset to center when we mouse out
Canvas.prototype.resetTarget = function() {
this.target = new Vector(this.width / 2, this.height /2);
}
// Touch Eent
Canvas.prototype.touchMove = function(event) {
if(event.touches.length === 1) { event.preventDefault(); }
this.target = new Vector(event.touches[0].pageX * this.dpr, event.touches[0].pageY * this.dpr);
}
// Defaults
Canvas.prototype.options = {
count: 11,
speed: 0.001,
width: 400,
height: 400,
size: 5,
radius: 1,
background: '240, 240, 240, 0.6',
maxDistance: 100
}
Canvas.prototype.setupParticles = function() {
this.particles = [];
var index = -1;
var between = PI2 / this.options.count;
while(++index < this.options.count) {
var x;
var y;
var angle;
var max = Math.max(this.width, this.height);
angle = (index + 1) * between;
x = Math.cos(angle) * max;
x += this.width / 2;
y = Math.sin(angle) * max;
y += this.height / 2;
var particle = new Particle({
x: x,
y: y,
radius: this.options.radius,
size: this.options.size,
angle: angle,
color: this.options.color
});
this.particles.push(particle);
}
}
Canvas.prototype.findClosest = function() {
var index = -1;
var pointsLength = this.particles.length;
while(++index < pointsLength) {
var closestIndex = -1;
this.particles[index].closest = [];
while(++closestIndex < pointsLength) {
var closest = this.particles[closestIndex];
var distance = this.particles[index].position.distanceTo(closest.position);
if(distance < this.options.maxDistance) {
var vector = new Vector(closest.position.x, closest.position.y);
vector.opacity = 1 - (distance / this.options.maxDistance);
vector.distance = distance;
this.particles[index].closest.push(vector);
}
}
}
}
Canvas.prototype.loop = function() {
// this.clear();
if(isTouch || isSafari) {
this.ghost();
} else {
this.ghostGradient();
}
if(this.options.maxDistance > 0) {
this.findClosest();
}
this.draw();
window.requestAnimationFrame(_.bind(this.loop, this));
}
Canvas.prototype.clear = function() {
this.ctx.clearRect(0, 0 , this.width, this.height);
}
Canvas.prototype.ghost = function() {
this.ctx.globalCompositeOperation = "source-over";
this.ctx.rect(0, 0 , this.width, this.height);
if(typeof this.options.background === 'string') {
this.ctx.fillStyle = "rgba(" + this.options.background + ")";
} else {
this.ctx.fillStyle = "rgba(" + this.options.background[0] + ")";
}
this.ctx.fill();
}
Canvas.prototype.ghostGradient = function() {
var gradient;
if(typeof this.options.background === 'string') {
this.ctx.fillStyle = 'rgba(' + this.options.background + ')';
} else {
var gradient = this.ctx.createLinearGradient(0, 0, 0, this.height);
var length = this.options.background.length;
for(var i = 0; i < length; i++){
gradient.addColorStop((i+1) / length, 'rgba(' + this.options.background[i] + ')');
}
this.ctx.fillStyle = gradient;
}
this.ctx.globalOpacity = 0.1;
this.ctx.globalCompositeOperation = "darken";
this.ctx.fillRect(0, 0 , this.width, this.height);
}
// Draw
Canvas.prototype.draw = function() {
var index = -1;
var length = this.particles.length;
while(++index < length) {
var point = this.particles[index];
var color = point.color || this.options.color;
point.update(this.target, index);
this.ctx.globalAlpha = 0.3;
this.ctx.globalCompositeOperation = "lighten";
this.ctx.fillStyle = 'rgb(' + color + ')';
this.ctx.beginPath();
this.ctx.arc(point.position.x, point.position.y, point.size, 0, PI2, false);
this.ctx.closePath();
this.ctx.fill();
if(this.options.maxDistance > 0) {
this.drawLines(point, color);
}
}
}
// Draw connecting lines
Canvas.prototype.drawLines = function (point, color) {
color = color || this.options.color;
var index = -1;
var length = point.closest.length;
this.ctx.globalAlpha = 0.2;
this.ctx.globalCompositeOperation = "screen";
this.ctx.lineCap = 'round';
while(++index < length) {
this.ctx.lineWidth = (point.size * 2) * point.closest[index].opacity;
this.ctx.strokeStyle = 'rgba(250,250,250, ' + point.closest[index].opacity + ')';
this.ctx.beginPath();
this.ctx.moveTo(point.position.x, point.position.y);
this.ctx.lineTo(point.closest[index].x, point.closest[index].y);
this.ctx.stroke();
}
}
function Particle(options) {
options = _.clone(options || {});
this.options = _.defaults(options, this.options);
this.position = this.shift = new Vector(this.options.x, this.options.y);
this.speed = this.options.speed || 0.01 + Math.random() * 0.04;
this.angle = this.options.angle || 0;
if(this.options.color) {
var color = this.options.color.split(',');
var colorIndex = -1;
while(++colorIndex < 3) {
color[colorIndex] = Math.round(parseInt(color[colorIndex], 10) + (Math.random()*100)-50);
// Clamp
color[colorIndex] = Math.min(color[colorIndex], 255);
color[colorIndex] = Math.max(color[colorIndex], 0);
}
this.color = color.join(', ');
}
// Size
this.options.size = this.options.size || 7;
this.size = 1 + Math.random() * this.options.size;
this.targetSize = this.options.targetSize || this.options.size;
this.orbit = this.options.radius * 0.5 + (this.options.radius * 0.5 * Math.random());
}
Particle.prototype.update = function(target, index) {
this.angle += this.speed;
this.shift.x += (target.x - this.shift.x) * this.speed;
this.shift.y += (target.y - this.shift.y) * this.speed;
this.position.x = this.shift.x + Math.cos(index + this.angle) * this.orbit;
this.position.y = this.shift.y + Math.sin(index + this.angle) * this.orbit;
if(!isSafari) {
this.size += (this.targetSize - this.size) * 0.03;
if(Math.round(this.size) === Math.round(this.targetSize)) {
this.targetSize = 1 + Math.random() * this.options.size;
}
}
}
function Vector(x, y) {
this.x = x || 0;
this.y = y || 0;
}
Vector.prototype.distanceTo = function(vector, abs) {
var distance = Math.sqrt(Math.pow(this.x - vector.x, 2) + Math.pow(this.y - vector.y, 2));
return abs || false ? Math.abs(distance) : distance;
};
new Canvas({
el: document.getElementById('canvas'),
count: 25,
speed: 0.3,
radius: 6,
width: function() { return window.innerWidth; },
height: function() { return window.innerHeight; },
size: 15,
color: '30, 180, 1',
maxDistance: 100,
background: ['250,250,250,1', '215,216,215,0.8']
})
CSS
html, body {
min-height: 100%;
height: 100%;
}
#canvas {
width: 100%;
height: 100%;
position: fixed;
z-index: 100;
}
.page-content {
position: relative;
z-index: 900;
display: flex;
flex-direction: column;
}
HTML
<body>
<div id="container">
<canvas id="canvas"></canvas>
<div class="page-content">
</div>
</div>
</body>

How to change thickness / height of lines

I found this codepen that I'd like to use but want the lines to appear 'thinner'. Which variable do I change?
Here is the link to the code and here is the code:
<canvas id="stripes">
(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: 6,
reactionSensitivity: 3,
points: [],
lines: [[], []],
mouse: { x: -1000, y: -1000, down: false },
animation: null,
canvas: null,
context: null,
init: function() {
// Set up the visual canvas
this.canvas = document.getElementById( 'stripes' );
this.context = this.canvas.getContext( '2d' );
this.context.lineJoin = 'bevel';
this.canvas.width = window.innerWidth;
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.innerWidth;
Nodes.canvas.height = Math.max(window.innerHeight, 670);
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 = -10; i < this.canvas.width + 10; i += this.density ) {
var line1 = {y: center - 17, originalY: center - 10, color: '#B1FB17'};
var line2 = {y: center - 17, originalY: center - 25, color: '#F52887'};
line1["x"] = i;
line1["originalX"] = i;
line2["x"] = i;
line2["originalX"] = i;
this.points.push(line1);
this.points.push(line2);
this.lines[0].push(line1);
this.lines[1].push(line2);
}
},
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 < 2; 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 = 10;
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.pageX;
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);
Look for linewidth - actually with a bit of reading you cold solve this yourself!

Create radial Timer

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?

Slowing movement of image on canvas

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.

Categories

Resources