How to change thickness / height of lines - javascript

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!

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);
}

Can't repeat js function in same page

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

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>

Why won't the image load

What is wrong with the code, I can't find the problem. I think it's because of the drawFrame and loadImage function, but I don't know. So is there a way to make the image load and you will still be able to move it around and shoot?
And when I try to remove the drawFrame function nothing would work. And if posiible is there a way to change the bullet from squares to circles?
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta charset="UTF-8">
<style>
html,
body {
width: 100%;
height: 100%;
margin: 0;
}
canvas {
cursor: crosshair;
background-color: cornflowerblue;
}
</style>
</head>
<body>
<canvas id="Trump"></canvas>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
(async function main() {
var canvas = document.getElementById('Trump');
if (!canvas.getContext) return;
var ctx = canvas.getContext('2d');
ctx.canvas.width = window.innerWidth;
ctx.canvas.height = window.innerHeight;
//const fps = 60;
const ronaNum = 30; // number of particles at start
const ronaSize = 70; // corona size
const ronaSpeed = 100; // speed
let chinabmg;
function draw() {
$("canvas").one("click", function () {
chinabmg = new sound("stankytrumpchina.mp3");
chinabmg.play();
});
//mutes when clicked on m
document.body.onkeyup = function (e) {
if (e.keyCode == 77) { chinabmg.stop() }
};
//compatability
var requestAnimationFrame = window.requestAnimationFrame || //Chromium
window.webkitRequestAnimationFrame || //Webkit
window.mozRequestAnimationFrame || //Mozilla Geko
window.oRequestAnimationFrame || //Opera Presto
window.msRequestAnimationFrame || //IE Trident?
function (callback) { //Fallback function
window.setTimeout(callback, 1000 / 60);
};
var DrawX = 0;
var DrawY = 0;
var time = 0;
var width = canvas.width;
var height = canvas.height;
var offTop = canvas.offsetTop;
var offLeft = canvas.offsetLeft;
var rectWidth = 15;
var rectHeight = 15;
var speed = 1;
var x = width / 2;
var y = height / 2;
var size = 30;
var id = 0;
var bulletId = 0;
function sound(src) {
this.sound = document.createElement("audio");
this.sound.src = src;
this.sound.setAttribute("preload", "auto");
this.sound.setAttribute("controls", "none");
this.sound.setAttribute("loop", "auto");
this.sound.style.display = "none";
document.body.appendChild(this.sound);
this.play = function () {
this.sound.play();
}
this.stop = function () {
this.sound.pause();
}
}
function player(id, color, size, x, y) {
this.id = id;
this.color = color;
this.size = size;
this.x = x;
this.y = y;
this.speed = speed;
}
var playerList = [];
function addPlayer(color, size, x, y) {
playerList[id] = new player(id, color, size, x, y);
id += 1;
}
addPlayer("blue", size, width / 2 - 50, height / 2);
var pressedKeys = [];
function moveLeft(checkId, checkX, checkY, cSize, cSpeed, cKey) {
var x = checkX - cSpeed;
var y = checkY - cSpeed;
var x2 = checkX + cSize + cSpeed;
var y2 = checkY + cSize + cSpeed;
if (x > 0) {
playerList[checkId].x = checkX - cSpeed;
} else {
playerList[checkId].x = 0;
}
}
function moveUp(checkId, checkX, checkY, cSize, cSpeed, cKey) {
var x = checkX - cSpeed;
var y = checkY - cSpeed;
var x2 = checkX + cSize + cSpeed;
var y2 = checkY + cSize + cSpeed;
if (y > 0) {
playerList[checkId].y = checkY - cSpeed;
} else {
playerList[checkId].y = 0;
}
}
function moveRight(checkId, checkX, checkY, cSize, cSpeed, cKey) {
var x = checkX - cSpeed;
var y = checkY - cSpeed;
var x2 = checkX + cSize + cSpeed;
var y2 = checkY + cSize + cSpeed;
if (x2 < width) {
playerList[checkId].x = checkX + cSpeed;
} else {
playerList[checkId].x = width - cSize;
}
}
function moveDown(checkId, checkX, checkY, cSize, cSpeed, cKey) {
var x = checkX - cSpeed;
var y = checkY - cSpeed;
var x2 = checkX + cSize + cSpeed;
var y2 = checkY + cSize + cSpeed;
if (y2 < height) {
playerList[checkId].y = checkY + cSpeed;
} else {
playerList[checkId].y = height - cSize;
}
}
function Move(checkId, checkX, checkY, cSize, cSpeed, cKey) {
if (checkId === 0) {
switch (cKey) {
case 65:
// left
moveLeft(checkId, checkX, checkY, cSize, cSpeed, cKey);
break;
case 87:
// up
moveUp(checkId, checkX, checkY, cSize, cSpeed, cKey);
break;
case 68:
// right
moveRight(checkId, checkX, checkY, cSize, cSpeed, cKey);
break;
case 83:
// down
moveDown(checkId, checkX, checkY, cSize, cSpeed, cKey);
break;
default:
return; // exit this handler for other keys
}
}
}
var validKeys = [];
validKeys[0] = "65,87,68,83-107,109,80";
// == KEYDOWN ==
$(document.body).keydown(function (e) {
e.preventDefault();
//go through all players
$.each(playerList, function (i, currentPlayer) {
if (validKeys[currentPlayer.id].indexOf(e.which) == -1) return true;
if (!pressedKeys[e.which]) {
//set interval for the function
pressedKeys[e.which] = setInterval(function () {
Move(currentPlayer.id, currentPlayer.x, currentPlayer.y, currentPlayer.size, currentPlayer.speed, e.which);
}, 5);
}
});
});
// == KEYUP ==
$(document.body).keyup(function (e) {
if (pressedKeys[e.which]) {
clearInterval(pressedKeys[e.which]);
delete pressedKeys[e.which];
}
});
//=============================== SHOOTING ===============================
//Bullets
function bullet(id, color, size, speed, x, y, eX, eY) {
this.id = id;
this.color = color;
this.size = size;
this.x = x;
this.y = y;
this.eX = eX;
this.eY = eY;
this.velocityX = 1;
this.velocityY = 1;
this.speed = 9;
}
var bulletList = [];
function addBullet(color, bsize, bspeed, x, y, eX, eY) {
bulletList[bulletId] = new bullet(bulletId, color, bsize, 9, x, y, eX, eY);
bulletId += 1;
}
function updateBullet(bullet, player) {
var dx = (bullet.eX - player.x);
var dy = (bullet.eY - player.y);
var mag = Math.sqrt(dx * dx + dy * dy);
bullet.velocityX = (dx / mag) * 9;
bullet.velocityY = (dy / mag) * 9;
bullet.x += bullet.velocityX;
bullet.y += bullet.velocityY;
}
// Add event listener for `click` events.
canvas.onmousedown = function (e) {
addBullet("#696969", 10, 2, playerList[0].x, playerList[0].y, e.x, e.y);
};
//corona part
let corona = [];
createCoronaParticles();
// game loop
//setInterval(update, 1000 / fps);
function createCoronaParticles() {
corona = [];
let cx, cy;
for (var i = 0; i < ronaNum; i++) {
do {
cx = Math.floor(Math.random() * canvas.width);
cy = Math.floor(Math.random() * canvas.height);
} while (noSpawnOnFigure(canvas.height / 2, canvas.width / 2, cy, cx) < ronaSize * 5);
corona.push(newParticle(cx, cy));
}
}
function noSpawnOnFigure(cy1, cx1, cy2, cx2) {
return Math.sqrt(Math.pow(cy2 - cy1, 2) + Math.pow(cx2 - cx1, 2));
}
function newParticle(cx, cy) {
let rona = {
ca: Math.random() * Math.PI * 2, //radians
cr: ronaSize / 2,
cx: cx,
cy: cy,
cxv: Math.random() * ronaSpeed / 60 * (Math.random() < 0.5 ? 1 : -1),
cyv: Math.random() * ronaSpeed / 60 * (Math.random() < 0.5 ? 1 : -1)
};
return rona;
}
// function update() {
// }
// ======= DRAWING =======
function drawFrame() {
requestAnimationFrame(drawFrame);
ctx.font = "15pt Georgia"; // sets the font and font size of the text
ctx.clearRect(0, 0, width, height);
$.each(playerList, function (index, currentPlayer) {
//debug
//draw players
function loadImage(path) {
let image = new Image();
let promise = new Promise((resolve, reject) => {
image.onload = () => resolve(image);
image.onerror = reject
});
image.src = path;
return promise;
}
loadImage.src = 'trump.gif';
});
//draw bullets
$.each(bulletList, function (index, bullet) {
updateBullet(bullet, playerList[0]);
ctx.fillStyle = bullet.color;
ctx.fillRect(bullet.x, bullet.y, bullet.size, bullet.size);
});
// canvas
//ctx.clearRect(0, 0, canvas.width, canvas.height);
// draw corona particles
ctx.strokeStyle = "rgb(150, 0, 0)";
ctx.lineWidth = 20;
let ca, cr, cx, cy;
for (let i = 0; i < corona.length; i++) {
// get properties
ca = corona[i].ca;
cr = corona[i].cr;
cx = corona[i].cx;
cy = corona[i].cy;
// draw path
ctx.beginPath();
ctx.fillStyle = "rgb(200, 0, 0)"
ctx.moveTo(
cx + cr * Math.cos(ca),
cy + cr * Math.sin(ca)
);
// draw circle
for (let j = 1; j < 180; j++) {
ctx.lineTo(
cx + cr * Math.cos(ca + j * Math.PI * 2 / 180),
cy + cr * Math.sin(ca + j * Math.PI * 2 / 180)
);
}
ctx.closePath();
ctx.stroke();
ctx.fill();
// move particles
corona[i].cx += corona[i].cxv;
corona[i].cy += corona[i].cyv;
// particle edge of screen
if (corona[i].cx < 0 - corona[i].cr) {
corona[i].cx = canvas.width + corona[i].cr;
} else if (corona[i].cx > canvas.width + corona[i].cr) {
corona[i].cx = 0 - corona[i].cr
}
if (corona[i].cy < 0 - corona[i].cr) {
corona[i].cy = canvas.height + corona[i].cr;
} else if (corona[i].cy > canvas.height + corona[i].cr) {
corona[i].cy = 0 - corona[i].cr
}
}
}
drawFrame();
}
$(draw);
}
)();
</script>
</body>
</html>
//draw players
function loadImage(path) {
let image = new Image();
let promise = new Promise((resolve, reject) => {
image.onload = () => resolve(image);
image.onerror = reject
});
image.src = path;
//Add the following line
ctx.drawImage(image,playerList[0].x,playerList[0].y);
return promise;
}
// change loadImage.src = 'trump.gif' into this
loadImage('trump.gif');

How to get rid of gray overlay on Three.js transition?

I have a transition between two pngs using three.js. The images have a white background, but they appear to have a gray tint. I know it is probably something obvious but I can't find where in the code this is specified. How do I get rid of this? Here is a demo on Codepen:
https://codepen.io/mastroneel/pen/Oazzyo
window.onload = init;
console.ward = function() {}; // what warnings?
function init() {
var root = new THREERoot({
createCameraControls: !true,
antialias: (window.devicePixelRatio === 1),
fov: 80
});
root.renderer.setClearColor(0x000000, 0);
root.renderer.setPixelRatio(window.devicePixelRatio || 1);
root.camera.position.set(0, 0, 60);
var width = 100;
var height = 100;
var slide = new Slide(width, height, 'out');
var l1 = new THREE.ImageLoader();
l1.setCrossOrigin('Anonymous');
slide.setImage(l1.load('https://image.ibb.co/f6mVsA/helmet.png'));
root.scene.add(slide);
var slide2 = new Slide(width, height, 'in');
var l2 = new THREE.ImageLoader();
l2.setCrossOrigin('Anonymous');
slide2.setImage(l2.load('https://image.ibb.co/mb1KkV/player.png'));
root.scene.add(slide2);
var tl = new TimelineMax({
repeat: -1,
repeatDelay: 1.0,
yoyo: true
});
tl.add(slide.transition(), 0);
tl.add(slide2.transition(), 0);
createTweenScrubber(tl);
window.addEventListener('keyup', function(e) {
if (e.keyCode === 80) {
tl.paused(!tl.paused());
}
});
}
////////////////////
// CLASSES
////////////////////
function Slide(width, height, animationPhase) {
var plane = new THREE.PlaneGeometry(width, height, width * 2, height * 2);
THREE.BAS.Utils.separateFaces(plane);
var geometry = new SlideGeometry(plane);
geometry.bufferUVs();
var aAnimation = geometry.createAttribute('aAnimation', 2);
var aStartPosition = geometry.createAttribute('aStartPosition', 3);
var aControl0 = geometry.createAttribute('aControl0', 3);
var aControl1 = geometry.createAttribute('aControl1', 3);
var aEndPosition = geometry.createAttribute('aEndPosition', 3);
var i, i2, i3, i4, v;
var minDuration = 0.8;
var maxDuration = 1.2;
var maxDelayX = 0.9;
var maxDelayY = 0.125;
var stretch = 0.11;
this.totalDuration = maxDuration + maxDelayX + maxDelayY + stretch;
var startPosition = new THREE.Vector3();
var control0 = new THREE.Vector3();
var control1 = new THREE.Vector3();
var endPosition = new THREE.Vector3();
var tempPoint = new THREE.Vector3();
function getControlPoint0(centroid) {
var signY = Math.sign(centroid.y);
tempPoint.x = THREE.Math.randFloat(0.1, 0.3) * 50;
tempPoint.y = signY * THREE.Math.randFloat(0.1, 0.3) * 70;
tempPoint.z = THREE.Math.randFloatSpread(20);
return tempPoint;
}
function getControlPoint1(centroid) {
var signY = Math.sign(centroid.y);
tempPoint.x = THREE.Math.randFloat(0.3, 0.6) * 50;
tempPoint.y = -signY * THREE.Math.randFloat(0.3, 0.6) * 70;
tempPoint.z = THREE.Math.randFloatSpread(20);
return tempPoint;
}
for (i = 0, i2 = 0, i3 = 0, i4 = 0; i < geometry.faceCount; i++, i2 += 6, i3 += 9, i4 += 12) {
var face = plane.faces[i];
var centroid = THREE.BAS.Utils.computeCentroid(plane, face);
// animation
var duration = THREE.Math.randFloat(minDuration, maxDuration);
var delayX = THREE.Math.mapLinear(centroid.x, -width * 0.5, width * 0.5, 0.0, maxDelayX);
var delayY;
if (animationPhase === 'in') {
delayY = THREE.Math.mapLinear(Math.abs(centroid.y), 0, height * 0.5, 0.0, maxDelayY)
} else {
delayY = THREE.Math.mapLinear(Math.abs(centroid.y), 0, height * 0.5, maxDelayY, 0.0)
}
for (v = 0; v < 6; v += 2) {
aAnimation.array[i2 + v] = delayX + delayY + (Math.random() * stretch * duration);
aAnimation.array[i2 + v + 1] = duration;
}
// positions
endPosition.copy(centroid);
startPosition.copy(centroid);
if (animationPhase === 'in') {
control0.copy(centroid).sub(getControlPoint0(centroid));
control1.copy(centroid).sub(getControlPoint1(centroid));
} else { // out
control0.copy(centroid).add(getControlPoint0(centroid));
control1.copy(centroid).add(getControlPoint1(centroid));
}
for (v = 0; v < 9; v += 3) {
aStartPosition.array[i3 + v] = startPosition.x;
aStartPosition.array[i3 + v + 1] = startPosition.y;
aStartPosition.array[i3 + v + 2] = startPosition.z;
aControl0.array[i3 + v] = control0.x;
aControl0.array[i3 + v + 1] = control0.y;
aControl0.array[i3 + v + 2] = control0.z;
aControl1.array[i3 + v] = control1.x;
aControl1.array[i3 + v + 1] = control1.y;
aControl1.array[i3 + v + 2] = control1.z;
aEndPosition.array[i3 + v] = endPosition.x;
aEndPosition.array[i3 + v + 1] = endPosition.y;
aEndPosition.array[i3 + v + 2] = endPosition.z;
}
}
var material = new THREE.BAS.BasicAnimationMaterial({
shading: THREE.FlatShading,
side: THREE.DoubleSide,
uniforms: {
uTime: {
type: 'f',
value: 0
}
},
shaderFunctions: [
THREE.BAS.ShaderChunk['cubic_bezier'],
//THREE.BAS.ShaderChunk[(animationPhase === 'in' ? 'ease_out_cubic' : 'ease_in_cubic')],
THREE.BAS.ShaderChunk['ease_in_out_cubic'],
THREE.BAS.ShaderChunk['quaternion_rotation']
],
shaderParameters: [
'uniform float uTime;',
'attribute vec2 aAnimation;',
'attribute vec3 aStartPosition;',
'attribute vec3 aControl0;',
'attribute vec3 aControl1;',
'attribute vec3 aEndPosition;',
],
shaderVertexInit: [
'float tDelay = aAnimation.x;',
'float tDuration = aAnimation.y;',
'float tTime = clamp(uTime - tDelay, 0.0, tDuration);',
'float tProgress = ease(tTime, 0.0, 1.0, tDuration);'
//'float tProgress = tTime / tDuration;'
],
shaderTransformPosition: [
(animationPhase === 'in' ? 'transformed *= tProgress;' : 'transformed *= 1.0 - tProgress;'),
'transformed += cubicBezier(aStartPosition, aControl0, aControl1, aEndPosition, tProgress);'
]
}, {
map: new THREE.Texture(),
});
THREE.Mesh.call(this, geometry, material);
this.frustumCulled = false;
}
Slide.prototype = Object.create(THREE.Mesh.prototype);
Slide.prototype.constructor = Slide;
Object.defineProperty(Slide.prototype, 'time', {
get: function() {
return this.material.uniforms['uTime'].value;
},
set: function(v) {
this.material.uniforms['uTime'].value = v;
}
});
Slide.prototype.setImage = function(image) {
this.material.uniforms.map.value.image = image;
this.material.uniforms.map.value.needsUpdate = true;
};
Slide.prototype.transition = function() {
return TweenMax.fromTo(this, 3.0, {
time: 0.0
}, {
time: this.totalDuration,
ease: Power0.easeInOut
});
};
function SlideGeometry(model) {
THREE.BAS.ModelBufferGeometry.call(this, model);
}
SlideGeometry.prototype = Object.create(THREE.BAS.ModelBufferGeometry.prototype);
SlideGeometry.prototype.constructor = SlideGeometry;
SlideGeometry.prototype.bufferPositions = function() {
var positionBuffer = this.createAttribute('position', 3).array;
for (var i = 0; i < this.faceCount; i++) {
var face = this.modelGeometry.faces[i];
var centroid = THREE.BAS.Utils.computeCentroid(this.modelGeometry, face);
var a = this.modelGeometry.vertices[face.a];
var b = this.modelGeometry.vertices[face.b];
var c = this.modelGeometry.vertices[face.c];
positionBuffer[face.a * 3] = a.x - centroid.x;
positionBuffer[face.a * 3 + 1] = a.y - centroid.y;
positionBuffer[face.a * 3 + 2] = a.z - centroid.z;
positionBuffer[face.b * 3] = b.x - centroid.x;
positionBuffer[face.b * 3 + 1] = b.y - centroid.y;
positionBuffer[face.b * 3 + 2] = b.z - centroid.z;
positionBuffer[face.c * 3] = c.x - centroid.x;
positionBuffer[face.c * 3 + 1] = c.y - centroid.y;
positionBuffer[face.c * 3 + 2] = c.z - centroid.z;
}
};
function THREERoot(params) {
params = utils.extend({
fov: 60,
zNear: 10,
zFar: 100000,
createCameraControls: true
}, params);
this.renderer = new THREE.WebGLRenderer({
antialias: params.antialias,
alpha: true
});
this.renderer.setPixelRatio(Math.min(2, window.devicePixelRatio || 1));
document.getElementById('three-container').appendChild(this.renderer.domElement);
this.camera = new THREE.PerspectiveCamera(
params.fov,
window.innerWidth / window.innerHeight,
params.zNear,
params.zfar
);
this.scene = new THREE.Scene();
if (params.createCameraControls) {
this.controls = new THREE.OrbitControls(this.camera, this.renderer.domElement);
}
this.resize = this.resize.bind(this);
this.tick = this.tick.bind(this);
this.resize();
this.tick();
window.addEventListener('resize', this.resize, false);
}
THREERoot.prototype = {
tick: function() {
this.update();
this.render();
requestAnimationFrame(this.tick);
},
update: function() {
this.controls && this.controls.update();
},
render: function() {
this.renderer.render(this.scene, this.camera);
},
resize: function() {
this.camera.aspect = window.innerWidth / window.innerHeight;
this.camera.updateProjectionMatrix();
this.renderer.setSize(window.innerWidth, window.innerHeight);
}
};
////////////////////
// UTILS
////////////////////
var utils = {
extend: function(dst, src) {
for (var key in src) {
dst[key] = src[key];
}
return dst;
},
randSign: function() {
return Math.random() > 0.5 ? 1 : -1;
},
ease: function(ease, t, b, c, d) {
return b + ease.getRatio(t / d) * c;
},
fibSpherePoint: (function() {
var vec = {
x: 0,
y: 0,
z: 0
};
var G = Math.PI * (3 - Math.sqrt(5));
return function(i, n, radius) {
var step = 2.0 / n;
var r, phi;
vec.y = i * step - 1 + (step * 0.5);
r = Math.sqrt(1 - vec.y * vec.y);
phi = i * G;
vec.x = Math.cos(phi) * r;
vec.z = Math.sin(phi) * r;
radius = radius || 1;
vec.x *= radius;
vec.y *= radius;
vec.z *= radius;
return vec;
}
})(),
spherePoint: (function() {
return function(u, v) {
u === undefined && (u = Math.random());
v === undefined && (v = Math.random());
var theta = 2 * Math.PI * u;
var phi = Math.acos(2 * v - 1);
var vec = {};
vec.x = (Math.sin(phi) * Math.cos(theta));
vec.y = (Math.sin(phi) * Math.sin(theta));
vec.z = (Math.cos(phi));
return vec;
}
})()
};
function createTweenScrubber(tween, seekSpeed) {
seekSpeed = seekSpeed || 0.001;
function stop() {
TweenMax.to(tween, 1, {
timeScale: 0
});
}
function resume() {
TweenMax.to(tween, 1, {
timeScale: 1
});
}
function seek(dx) {
var progress = tween.progress();
var p = THREE.Math.clamp((progress + (dx * seekSpeed)), 0, 1);
tween.progress(p);
}
var _cx = 0;
// desktop
var mouseDown = false;
document.body.style.cursor = 'pointer';
window.addEventListener('mousedown', function(e) {
mouseDown = true;
document.body.style.cursor = 'ew-resize';
_cx = e.clientX;
stop();
});
window.addEventListener('mouseup', function(e) {
mouseDown = false;
document.body.style.cursor = 'pointer';
resume();
});
window.addEventListener('mousemove', function(e) {
if (mouseDown === true) {
var cx = e.clientX;
var dx = cx - _cx;
_cx = cx;
seek(dx);
}
});
// mobile
window.addEventListener('touchstart', function(e) {
_cx = e.touches[0].clientX;
stop();
e.preventDefault();
});
window.addEventListener('touchend', function(e) {
resume();
e.preventDefault();
});
window.addEventListener('touchmove', function(e) {
var cx = e.touches[0].clientX;
var dx = cx - _cx;
_cx = cx;
seek(dx);
e.preventDefault();
});
}
body {
margin: 0;
background: #fff;
}
canvas {
background: #fff;
}
<script src="//cdnjs.cloudflare.com/ajax/libs/three.js/r75/three.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/gsap/1.18.0/TweenMax.min.js"></script>
<script src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/175711/bas.js"></script>
<script src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/175711/OrbitControls-2.js"></script>
<div id="three-container"></div>
Thanks in advance!

Categories

Resources