Im new to this area and hope some off you can help me.
I am super inspired be this site and the particle animation / function they have http://www.giantstepsmedias.com/
I found this one that are close to the inspiration. But i can't figure out how to change it to an images instead of the value in the input field.
var canvas = document.querySelector("#scene"),
ctx = canvas.getContext("2d"),
particles = [],
amount = 0,
mouse = {x:0,y:0},
radius = 1;
var colors = ["rgba(255,255,255,1)","rgba(255,255,255,.5)", "rgba(255,255,255,.25)","rgba(255,255,255,.1)"];
var copy = document.querySelector("#copy");
var ww = canvas.width = window.innerWidth;
var wh = canvas.height = window.innerHeight;
function Particle(x,y){
this.x = Math.random()*ww;
this.y = Math.random()*wh;
this.dest = {
x : x,
y: y
};
this.r = Math.random()*5 + 2;
this.vx = (Math.random()-0.5)*20;
this.vy = (Math.random()-0.5)*20;
this.accX = 0;
this.accY = 0;
this.friction = Math.random()*0.05 + 0.94;
this.color = colors[Math.floor(Math.random()*6)];
}
Particle.prototype.render = function() {
this.accX = (this.dest.x - this.x)/1000;
this.accY = (this.dest.y - this.y)/1000;
this.vx += this.accX;
this.vy += this.accY;
this.vx *= this.friction;
this.vy *= this.friction;
this.x += this.vx;
this.y += this.vy;
ctx.fillStyle = this.color;
ctx.beginPath();
ctx.arc(this.x, this.y, this.r, Math.PI * 2, false);
ctx.fill();
var a = this.x - mouse.x;
var b = this.y - mouse.y;
var distance = Math.sqrt( a*a + b*b );
if(distance<(radius*70)){
this.accX = (this.x - mouse.x)/100;
this.accY = (this.y - mouse.y)/100;
this.vx += this.accX;
this.vy += this.accY;
}
}
function onMouseMove(e){
mouse.x = e.clientX;
mouse.y = e.clientY;
}
function onTouchMove(e){
if(e.touches.length > 0 ){
mouse.x = e.touches[0].clientX;
mouse.y = e.touches[0].clientY;
}
}
function onTouchEnd(e){
mouse.x = -9999;
mouse.y = -9999;
}
function initScene(){
ww = canvas.width = window.innerWidth;
wh = canvas.height = window.innerHeight;
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.font = "bold "+(ww/10)+"px sans-serif";
ctx.textAlign = "center";
ctx.fillText(copy.value, ww/2, wh/2);
var data = ctx.getImageData(0, 0, ww, wh).data;
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.globalCompositeOperation = "screen";
particles = [];
for(var i=0;i<ww;i+=Math.round(ww/150)){
for(var j=0;j<wh;j+=Math.round(ww/150)){
if(data[ ((i + j*ww)*4) + 3] > 150){
particles.push(new Particle(i,j));
}
}
}
amount = particles.length;
}
function onMouseClick(){
radius++;
if(radius ===5){
radius = 0;
}
}
function render(a) {
requestAnimationFrame(render);
ctx.clearRect(0, 0, canvas.width, canvas.height);
for (var i = 0; i < amount; i++) {
particles[i].render();
}
};
copy.addEventListener("keyup", initScene);
window.addEventListener("resize", initScene);
window.addEventListener("mousemove", onMouseMove);
window.addEventListener("touchmove", onTouchMove);
window.addEventListener("click", onMouseClick);
window.addEventListener("touchend", onTouchEnd);
initScene();
requestAnimationFrame(render);
canvas{
background: black;
width: 100vw;
height: 100vh;
}
<canvas id="scene"></canvas>
<input id="copy" type="text" value="Hello Codepen ♥" />
The animation is based on whatever has been rendered to the canvas.
In your code that is
ctx.font = "bold "+(ww/10)+"px sans-serif";
ctx.textAlign = "center";
ctx.fillText(copy.value, ww/2, wh/2);
instead, change this to render an image:
const img = document.getElementById('img');
ctx.drawImage(img, ww/2, wh/2);
you might like to adjust the positions for .drawImage: https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/drawImage
Using HTML:
<canvas id="scene"></canvas>
<div style="display:none;">
<img id="img"
src="http://www.giantstepsmedias.com/img/logos/giant_steps_small.png">
</div>
However, rendering an image from a different server to your ctx gives The canvas has been tainted by cross-origin data so I can't give you a working snippet.
Use an image that is on the same server as the page or, as suggested, use a data: url:
var canvas = document.querySelector("#scene"),
ctx = canvas.getContext("2d"),
particles = [],
amount = 0,
mouse = {
x: 0,
y: 0
},
radius = 1;
var colors = ["rgba(255,255,255,1)", "rgba(255,255,255,.5)", "rgba(255,255,255,.25)", "rgba(255,255,255,.1)"];
var ww = canvas.width = window.innerWidth;
var wh = canvas.height = window.innerHeight;
function Particle(x, y) {
this.x = Math.random() * ww;
this.y = Math.random() * wh;
this.dest = {
x: x,
y: y
};
this.r = Math.random() * 5 + 2;
this.vx = (Math.random() - 0.5) * 20;
this.vy = (Math.random() - 0.5) * 20;
this.accX = 0;
this.accY = 0;
this.friction = Math.random() * 0.05 + 0.94;
this.color = colors[Math.floor(Math.random() * 6)];
}
Particle.prototype.render = function() {
this.accX = (this.dest.x - this.x) / 1000;
this.accY = (this.dest.y - this.y) / 1000;
this.vx += this.accX;
this.vy += this.accY;
this.vx *= this.friction;
this.vy *= this.friction;
this.x += this.vx;
this.y += this.vy;
ctx.fillStyle = this.color;
ctx.beginPath();
ctx.arc(this.x, this.y, this.r, Math.PI * 2, false);
ctx.fill();
var a = this.x - mouse.x;
var b = this.y - mouse.y;
var distance = Math.sqrt(a * a + b * b);
if (distance < (radius * 70)) {
this.accX = (this.x - mouse.x) / 100;
this.accY = (this.y - mouse.y) / 100;
this.vx += this.accX;
this.vy += this.accY;
}
}
function onMouseMove(e) {
mouse.x = e.clientX;
mouse.y = e.clientY;
}
function onTouchMove(e) {
if (e.touches.length > 0) {
mouse.x = e.touches[0].clientX;
mouse.y = e.touches[0].clientY;
}
}
function onTouchEnd(e) {
mouse.x = -9999;
mouse.y = -9999;
}
function initScene() {
ww = canvas.width = window.innerWidth;
wh = canvas.height = window.innerHeight;
ctx.clearRect(0, 0, canvas.width, canvas.height);
//ctx.font = "bold "+(ww/10)+"px sans-serif";
//ctx.textAlign = "center";
//ctx.fillText(copy.value, ww/2, wh/2);
const img = document.getElementById('img');
ctx.drawImage(img, ww / 2 - 75, (wh / 2) - 75, 150, 150);
var data = ctx.getImageData(0, 0, ww, wh).data;
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.globalCompositeOperation = "screen";
particles = [];
for (var i = 0; i < ww; i += Math.round(ww / 150)) {
for (var j = 0; j < wh; j += Math.round(ww / 150)) {
if (data[((i + j * ww) * 4) + 3] > 150) {
particles.push(new Particle(i, j));
}
}
}
amount = particles.length;
}
function onMouseClick() {
radius++;
if (radius === 5) {
radius = 0;
}
}
function render(a) {
requestAnimationFrame(render);
ctx.clearRect(0, 0, canvas.width, canvas.height);
for (var i = 0; i < amount; i++) {
particles[i].render();
}
};
window.addEventListener("resize", initScene);
window.addEventListener("mousemove", onMouseMove);
window.addEventListener("touchmove", onTouchMove);
window.addEventListener("click", onMouseClick);
window.addEventListener("touchend", onTouchEnd);
initScene();
requestAnimationFrame(render);
canvas {
background: black;
width: 100vw;
height: 100vh;
}
<canvas id="scene"></canvas>
<div style="display:none;">
<img id="img" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACYAAAAsCAYAAAAJpsrIAAAC9UlEQVR42syZSWgUQRSGezJJ0IhLwIDLRQkumEMOihdFPOghcd9QEEREiIokHkQRISAKRsUdEUxAL2pGxV08iQt40QgexAUNiBgFSQY0EjEzk/J/8kqHobvrRat76sE3E7prar55vdTrl4RS6oXneaNBzvsbSdAPjoATYMCzFw3gAMj6zEvf2w2mlOJlPBgVMAmJTQY7Qa8lsQowMmR/iX7JhAxKgM0gBSZaEjNlP/PHThB14BaY48UUJYMYW8NyG1wToxgB2sA+MNQlMX3e7QZnwTiXxHSsBjfBTNfEKKaDa2BF3GIK/DSMocN5ke91ZXGKHQPthnEk1ALO8CoSuRjtfwvWg1bBfDTuMpgaxzk2nA8nrXHbQZ9h/FxwG8yPWkzlvR/mrHwyfKaaM7clzquSvnAZeG4YRwv1KXAcDItCrN9n2xOwiA+ZKRr5qtVFQLktsTVgks/2j7zvqKBioB9xndfbPlHKUCh+UeZ4DWYDL4BG0CuYpxPcAwMhY8hHLEbRAzaGyNWBD+r/Y9Biin/pQVARIFcLOoohpuMSGBsgNwakiiWmODMzAuTKwH6QKYYYRRdYFXLeNYCvxRCjyIJmzpKf3Dy+Gq2K0cmeFk7YBqoC5GrAA9sZo2zsEU76kCX85CrBOc6wFbFtPHET+C6QewfqA+SSoFUiJlmS9NMQLcZrhZVFe0BlQW2IDltrZTbv7xtgMXgqqOGosjjp0w4YYkussOZ/BpaAq4LPbgXnwYQoyp6Ez7bPXFkcKsioXywAd/LaCyrqxzdqfuzgeuubYew0cAXUgx+SyUstPNCcBu/5fKoOGVcFLvDYHPfCInvg1XGXL4rHgnK71iRlU4ziJculXGgRFEYarAN7DQ3B2MX0w0sz32DTLonpoD7aSvDGNTGK+3wfe+SaGEUnWM4ZdEqMogdsArsEba1YxXRl0cK9j26JmKnZlrQsSCXRUvAqpNf2e0nq4vTmfBbvcsE6+C9BK8RCbi/Myju8+l823i8BBgAb0AQfHTBwWAAAAABJRU5ErkJggg=="
alt="" />
</div>
Related
let canvas = document.getElementById("canvas");
let context = canvas.getContext("2d");
// for canvas size
var window_width = window.innerWidth;
var window_height = window.innerHeight;
canvas.style.background="yellow"
canvas.width = window_width;
canvas.height = window_height;
let hit_counter=0;
function randomIntFromInterval(min, max) { // min and max included
return Math.floor(Math.random() * (max - min + 1) + min)
}
class Circle {
constructor(xpos, ypos, radius, color, text) {
this.position_x = xpos;
this.position_y = ypos;
this.radius = radius;
this.text = text;
this.color = color;
}
// creating circle
draw(context) {
context.beginPath();
context.strokeStyle = this.color;
context.fillText(this.text, this.position_x, this.position_y);
context.textAlign = "center";
context.textBaseline = "middle"
context.font = "20px Arial";
context.lineWidth = 5;
context.arc(this.position_x, this.position_y, this.radius, 0, Math.PI * 2);
context.stroke();
context.closePath();
}
update() {
this.text=hit_counter;
context.clearRect(0, 0, window_width, window_height)
this.draw(context);
if ((this.position_x + this.radius) > window_width) {
this.dx = -this.dx;
}
if ((this.position_x - this.radius) < 0) {
this.dx = -this.dx;
}
if ((this.position_y - this.radius) < 0) {
this.dy = -this.dy;
}
if ((this.position_y + this.radius) > window_height) {
this.dy = -this.dy;
}
this.position_x += this.dx;
this.position_y += this.dy;
}
}
let my_circle = new Circle(100, 100, 50, 'Black', hit_counter);
my_circle.update();
<button>ex1</button>
<button>ex2</button>
<button>ex3</button>
<button>ex4</button>
<button>ex5</button>
<button>ex6</button>
<button>ex7</button>
<button>ex8</button>
<canvas id="canvas"></canvas>
HTML
How to arrange and style buttons in canvas? I tried adding CSS to buttons but it didn't work for me.. How to do that? How to arrange the buttons in center of canvas?
<button>ex1</button>
<button>ex2</button>
<button>ex3</button>
<button>ex4</button>
<button>ex5</button>
<button>ex6</button>
<button>ex7</button>
<button>ex8</button>
<canvas id="canvas"></canvas>
JS
How to arrange and style buttons in canvas. I tried adding CSS to buttons but it didn't work for me.. How to do that? How to arrange the buttons in center of canvas?
let canvas = document.getElementById("canvas");
let context = canvas.getContext("2d");
// for canvas size
var window_width = window.innerWidth;
var window_height = window.innerHeight;
canvas.style.background="yellow"
canvas.width = window_width;
canvas.height = window_height;
let hit_counter=0;
function randomIntFromInterval(min, max) { // min and max included
return Math.floor(Math.random() * (max - min + 1) + min)
}
class Circle {
constructor(xpos, ypos, radius, color, text) {
this.position_x = xpos;
this.position_y = ypos;
this.radius = radius;
this.text = text;
this.color = color;
}
// creating circle
draw(context) {
context.beginPath();
context.strokeStyle = this.color;
context.fillText(this.text, this.position_x, this.position_y);
context.textAlign = "center";
context.textBaseline = "middle"
context.font = "20px Arial";
context.lineWidth = 5;
context.arc(this.position_x, this.position_y, this.radius, 0, Math.PI * 2);
context.stroke();
context.closePath();
}
update() {
this.text=hit_counter;
context.clearRect(0, 0, window_width, window_height)
this.draw(context);
if ((this.position_x + this.radius) > window_width) {
this.dx = -this.dx;
}
if ((this.position_x - this.radius) < 0) {
this.dx = -this.dx;
}
if ((this.position_y - this.radius) < 0) {
this.dy = -this.dy;
}
if ((this.position_y + this.radius) > window_height) {
this.dy = -this.dy;
}
this.position_x += this.dx;
this.position_y += this.dy;
}
}
let my_circle = new Circle(100, 100, 50, 'Black', hit_counter);
my_circle.update();
you can put your buttons inside of a container and position it with absolute property in css
let canvas = document.getElementById("canvas");
let context = canvas.getContext("2d");
// for canvas size
var window_width = window.innerWidth;
var window_height = window.innerHeight;
canvas.style.background="yellow"
canvas.width = window_width;
canvas.height = window_height;
let hit_counter=0;
function randomIntFromInterval(min, max) { // min and max included
return Math.floor(Math.random() * (max - min + 1) + min)
}
class Circle {
constructor(xpos, ypos, radius, color, text) {
this.position_x = xpos;
this.position_y = ypos;
this.radius = radius;
this.text = text;
this.color = color;
}
// creating circle
draw(context) {
context.beginPath();
context.strokeStyle = this.color;
context.fillText(this.text, this.position_x, this.position_y);
context.textAlign = "center";
context.textBaseline = "middle"
context.font = "20px Arial";
context.lineWidth = 5;
context.arc(this.position_x, this.position_y, this.radius, 0, Math.PI * 2);
context.stroke();
context.closePath();
}
update() {
this.text=hit_counter;
context.clearRect(0, 0, window_width, window_height)
this.draw(context);
if ((this.position_x + this.radius) > window_width) {
this.dx = -this.dx;
}
if ((this.position_x - this.radius) < 0) {
this.dx = -this.dx;
}
if ((this.position_y - this.radius) < 0) {
this.dy = -this.dy;
}
if ((this.position_y + this.radius) > window_height) {
this.dy = -this.dy;
}
this.position_x += this.dx;
this.position_y += this.dy;
}
}
let my_circle = new Circle(100, 100, 50, 'Black', hit_counter);
my_circle.update();
.container{
position:absolute;
}
.container .buttons{
position: absolute;
top:0px;
padding:0.5rem;
}
.container .buttons button{
background:transparent;
padding:0.5rem;
}
<div class="container">
<div class="buttons">
<button>ex1</button>
<button>ex2</button>
<button>ex3</button>
<button>ex4</button>
<button>ex5</button>
<button>ex6</button>
<button>ex7</button>
<button>ex8</button>
</div>
<canvas id="canvas"></canvas>
</div>
I'm struggling with the implementation of a text particle in javascript.
My code is working fine with chromium-based browsers (Chromium: 84) but is unexpectedly slow on firefox (79.0).
I've searched a lot, but still don't find a solution and where the problem is.(This is pretty much linked to this Javascript Animation(Canvas) not working in firefox, Edge but works on Chrome).
Here is my codepen:
https://codepen.io/jgazeau/pen/LYNYPYB
function getRandomInt(max) {
return Math.floor(Math.random() * Math.floor(max));
}
function getCssVar(v) {
return getComputedStyle(document.documentElement).getPropertyValue(v);
}
let text404 = '404';
let canvas = document.getElementById('scene');
let ch = canvas.height = canvas.getBoundingClientRect().height;
let cw = canvas.width = canvas.getBoundingClientRect().width;
let sceneBackground = getCssVar('--scene-background');
let context = canvas.getContext('2d');
let previousMouseCoord = {x:0, y:0};
let mouseCoord = {x:0, y:0};
let sceneResize = false;
let particlesCount = 0;
let particles = [];
let colors = [
getCssVar('--particle-color-1'),
getCssVar('--particle-color-2'),
getCssVar('--particle-color-3'),
getCssVar('--particle-color-4'),
getCssVar('--particle-color-5')
];
const dpi = 200;
let Particle = function(x, y) {
this.x = getRandomInt(cw);
this.y = getRandomInt(ch);
this.coord = {x:x, y:y};
this.r = Math.min((getRandomInt((cw / dpi)) + 1), 6);
this.vx = (Math.random() - 0.5) * 100;
this.vy = (Math.random() - 0.5) * 100;
this.accX = 0;
this.accY = 0;
this.friction = Math.random() * 0.05 + 0.90;
this.color = colors[Math.floor(Math.random() * 6)];
}
Particle.prototype.render = function(isDisableMouse) {
this.accX = (this.coord.x - this.x) / 100;
this.accY = (this.coord.y - this.y) / 100;
this.vx += this.accX;
this.vy += this.accY;
this.vx *= this.friction;
this.vy *= this.friction;
this.x += this.vx;
this.y += this.vy;
if (!isDisableMouse) {
let a = this.x - mouseCoord.x;
let b = this.y - mouseCoord.y;
var distance = Math.sqrt(a * a + b * b);
if(distance < (cw / 15)) {
this.accX = (this.x - mouseCoord.x) / 100;
this.accY = (this.y - mouseCoord.y) / 100;
this.vx += this.accX;
this.vy += this.accY;
}
}
context.fillStyle = this.color;
context.beginPath();
context.arc(this.x, this.y, this.r, 0, Math.PI * 2, false);
context.fill();
context.closePath();
}
function onmouseCoordMove(e) {
mouseCoord.x = e.clientX;
mouseCoord.y = e.clientY;
}
function onTouchMove(e) {
if(e.touches.length > 0 ) {
mouseCoord.x = e.touches[0].clientX;
mouseCoord.y = e.touches[0].clientY;
}
}
function onTouchEnd() {
mouseCoord.x = -9999;
mouseCoord.y = -9999;
}
function initScene() {
ch = canvas.height = canvas.getBoundingClientRect().height;
cw = canvas.width = canvas.getBoundingClientRect().width;
context.clearRect(0, 0, canvas.width, canvas.height);
context.font = 'bold ' + (cw / 5) + 'px sans-serif';
context.fillStyle = sceneBackground;
context.textAlign = 'center';
context.fillText(text404, cw / 2, ch / 2);
let imageData = context.getImageData(0, 0, cw, ch).data;
context.clearRect(0, 0, canvas.width, canvas.height);
context.globalCompositeOperation = 'screen';
particles = [];
for(let y = 0; y < ch; y += Math.round(cw / dpi)) {
for(let x = 0; x < cw; x += Math.round(cw / dpi)) {
if(imageData[((x + y * cw) * 4) + 3] > 128){
particles.push(new Particle(x, y));
}
}
}
particlesCount = particles.length;
}
function renderScene() {
context.clearRect(0, 0, canvas.width, canvas.height);
let isDisableMouse = false;
if ((previousMouseCoord.x === mouseCoord.x) && (previousMouseCoord.x === mouseCoord.x)) {
isDisableMouse = true;
} else {
previousMouseCoord.x = mouseCoord.x;
previousMouseCoord.x = mouseCoord.x;
isDisableMouse = false;
}
for (let i = 0; i < particlesCount; i++) {
particles[i].render(isDisableMouse);
}
requestAnimationFrame(renderScene);
};
document.addEventListener('DOMContentLoaded', function() {
initScene();
renderScene();
window.addEventListener('mousemove', onmouseCoordMove);
window.addEventListener('touchmove', onTouchMove);
window.addEventListener('touchend', onTouchEnd);
window.addEventListener('resize', function() {
if (!sceneResize) {
requestAnimationFrame(function() {
initScene();
sceneResize = false;
});
sceneResize = true;
}
});
});
Can anyone know where this slow issue could come from ?
Thanks a lot for your help.
This is a code from codepen. I am trying to work on this one. This code works on chrome but does not work in firefox or edge. I tried to solve the issue but could not fix it. Is the problem with requestAnimationFrame or something else? Can anyone please help? Here is the codepen link: https://codepen.io/iremlopsum/pen/MKNaxd
var canvas = document.querySelector("#scene"),
ctx = canvas.getContext("2d"),
particles = [],
amount = 0,
mouse = {
x: 0,
y: 0
},
radius = 0.7; //Init radius of the force field
var colors = ["rgba(255,255,255, .6)", "rgba(255,255,255, .6)", "rgba(255,255,255, .6)", "rgba(255,255,255, .6)", "rgba(255,255,255, .6)", "rgba(255,255,255, .6)"];
var colorsTwo = ["rgba(255,255,255, .6)", "rgba(255,255,255, .6)", "rgba(255,255,255, .6)", "rgba(255,255,255, .6)", "rgba(255,255,255, .6)", "rgba(255,255,255, .6)"];
var copy = "Mighty Byte"; // Text to display
var initSize = Math.floor(Math.random() * .6) + 1 ;
var hoverSize = initSize + .7;
var ww = canvas.width = window.innerWidth;
var wh = canvas.height = window.innerHeight;
function Particle(x, y) {
this.x = Math.random() * ww;
this.y = Math.random() * wh;
this.dest = {
x: x,
y: y
};
//this.r = Math.random() * 1; // the size of bubbles
this.vx = (Math.random() - 0.5) * 2;
this.vy = (Math.random() - 0.5) * 2;
this.accX = 0;
this.accY = 0;
this.friction = Math.random() * 0.015 + 0.94; // force of bounce, just try to change 0.015 to 0.5
//this.color = colors[Math.floor(Math.random() * 10)];
//this.colorTwo = colorsTwo[Math.floor(Math.random() * 10)];
}
Particle.prototype.render = function() {
this.accX = (this.dest.x - this.x) / 200; //acceleration for X
this.accY = (this.dest.y - this.y) / 200; //acceleration for Y
this.vx += this.accX;
this.vy += this.accY;
this.vx *= this.friction;
this.vy *= this.friction;
this.x += this.vx;
this.y += this.vy;
ctx.fillStyle = this.color;
ctx.beginPath();
ctx.arc(this.x, this.y, this.r, Math.PI * 2, false);
ctx.fill();
var a = this.x - mouse.x;
var b = this.y - mouse.y;
var distance = Math.sqrt(a * a + b * b);
if (distance < (radius * 70)) {
this.accX = (this.x - mouse.x) / 20; //acceleration on mouseover X, smaller faster
this.accY = (this.y - mouse.y) / 20; //acceleration on mouseover Y, smaller faster
this.vx += this.accX;
this.vy += this.accY;
//ctx.fillStyle = this.colorTwo;
}
if (distance < (radius * 70)) {
this.colorTwo = colorsTwo[Math.floor(Math.random() * 10)];
ctx.fillStyle = this.colorTwo;
this.r = hoverSize; // the size of bubbles
}
if (distance > (radius * 70)) {
this.colorOne = colors[Math.floor(Math.random() * 10)];
ctx.fillStyle = this.colorOne;
this.r = initSize
}
}
function onMouseMove(e) {
mouse.x = e.clientX;
mouse.y = e.clientY;
}
function initScene() {
ww = canvas.width = window.innerWidth;
wh = canvas.height = window.innerHeight;
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.font = "bold " + (ww / 10) + "px sans-serif"; // Size of the text
ctx.textAlign = "center";
ctx.fillText(copy, ww / 2, wh / 2); //Centering
var data = ctx.getImageData(0, 0, ww, wh).data;
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.globalCompositeOperation = "screen";
particles = [];
for (var i = 0; i < ww; i += Math.round(ww / 400)) { //400 here represents the amount of particles
for (var j = 0; j < wh; j += Math.round(ww / 400)) {
if (data[((i + j * ww) * 4) + 3] > 250) {
particles.push(new Particle(i, j));
}
}
}
amount = particles.length;
}
function onMouseClick() {
radius = 4; //onclick expand radius
}
function offMouseClick() {
radius = 0.5; //offClick init radius
}
function delayedInitRadius() {
setTimeout(offMouseClick, 500); //delay for offClick init radius
}
function render(a) {
requestAnimationFrame(render);
ctx.clearRect(0, 0, canvas.width, canvas.height);
for (var i = 0; i < amount; i++) {
particles[i].render();
}
};
window.addEventListener("resize", initScene);
window.addEventListener("mousemove", onMouseMove);
window.addEventListener("mousedown", onMouseClick);
window.addEventListener("mouseup", delayedInitRadius);
initScene();
requestAnimationFrame(render);
the html file does not seem to be importing the javascript function particle() to upload i have the script in another file and i am importing it to my html file but it does not work , it might be some basic error i just cant figure it out here !
if you could fix this code i would really appreciate it .
var canvas = document.createElement("canvas");
c = canvas.getContext("2d");
var particles = {};
var particleIndex = 0;
var particleNum = 15;
// set canvas size
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
// add canvas to body
document.body.appendChild(canvas);
// style the canvas
c.fillStyle = "black";
c.fillRect(0, 0, canvas.width, canvas.height);
function Particle() {
this.x = canvas.width / 2;
this.y = canvas.height / 2;
this.vx = Math.random() * 10 - 5;
this.vy = Math.random() * 10 - 5;
this.gravity = 0.3;
particleIndex++;
particles[particleIndex] = this;
this.id = particleIndex;
this.life = 0;
this.maxLife = Math.random() * 30 + 60;
this.color = "hsla(" + parseInt(Math.random() * 360, 10) + ",90%,60%,0.5";
}
Particle.prototype.draw = function() {
this.x += this.vx;
this.y += this.vy;
if (Math.random() < 0.1) {
this.vx = Math.random() * 10 - 5;
this.vy = Math.random() * 10 - 5;
}
this.life++;
if (this.life >= this.maxLife) {
delete particles[this.id];
}
c.fillStyle = this.color;
//c.fillRect(this.x, this.y, 5, 10);
c.beginPath();
c.arc(this.x, this.y, 2.5, 0, 2 * Math.PI);
c.fill();
};
setInterval(function() {
//normal setting before drawing over canvas w/ black background
c.globalCompositeOperation = "source-over";
c.fillStyle = "rgba(0,0,0,0.5)";
c.fillRect(0, 0, canvas.width, canvas.height);
for (var i = 0; i < particleNum; i++) {
new Particle();
}
// c.globalCompositeOperation = "darken";
for (var i in particles) {
particles[i].draw();
}
}, 30);
<!DOCTYPE html5>
<html>
<head>
<title>disturbed</title>
<script src="toto.js" type="text/javascript"></script>
<script type="text/javascript">
window.onload = function() {
Particle();
};
</script>
</head>
<body>
</body>
</html>
function runParticles () {
var canvas = document.createElement("canvas");
c = canvas.getContext("2d");
var particles = {};
var particleIndex = 0;
var particleNum = 15;
// set canvas size
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
// add canvas to body
document.body.appendChild(canvas);
// style the canvas
c.fillStyle = "black";
c.fillRect(0, 0, canvas.width, canvas.height);
function Particle() {
this.x = canvas.width / 2;
this.y = canvas.height / 2;
this.vx = Math.random() * 10 - 5;
this.vy = Math.random() * 10 - 5;
this.gravity = 0.3;
particleIndex++;
particles[particleIndex] = this;
this.id = particleIndex;
this.life = 0;
this.maxLife = Math.random() * 30 + 60;
this.color = "hsla(" + parseInt(Math.random() * 360, 10) + ",90%,60%,0.5";
}
Particle.prototype.draw = function() {
this.x += this.vx;
this.y += this.vy;
if (Math.random() < 0.1) {
this.vx = Math.random() * 10 - 5;
this.vy = Math.random() * 10 - 5;
}
this.life++;
if (this.life >= this.maxLife) {
delete particles[this.id];
}
c.fillStyle = this.color;
//c.fillRect(this.x, this.y, 5, 10);
c.beginPath();
c.arc(this.x, this.y, 2.5, 0, 2 * Math.PI);
c.fill();
};
setInterval(function() {
//normal setting before drawing over canvas w/ black background
c.globalCompositeOperation = "source-over";
c.fillStyle = "rgba(0,0,0,0.5)";
c.fillRect(0, 0, canvas.width, canvas.height);
for (var i = 0; i < particleNum; i++) {
new Particle();
}
// c.globalCompositeOperation = "darken";
for (var i in particles) {
particles[i].draw();
}
}, 30);
}
<!DOCTYPE html5>
<html>
<head>
<title>disturbed</title>
<script src="toto.js" type="text/javascript"></script>
<script>
window.onload = () => runParticles();
</script>
</head>
<body>
</body>
</html>
Remove this:
<script type="text/javascript">
window.onload = function() {
Particle();
};
i have made a an animations in canvas html but now i want to make the origin from where the balls originate move around the canvas according to my mouse position. i want to add mouse event function but i can't seem to get the logic straightand add added to the code , any help would be appreciated !
function runParticles () {
var canvas = document.createElement("canvas");
c = canvas.getContext("2d");
var particles = {};
var particleIndex = 0;
var particleNum = 15;
// set canvas size
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
// add canvas to body
document.body.appendChild(canvas);
// style the canvas
c.fillStyle = "black";
c.fillRect(0, 0, canvas.width, canvas.height);
function Particle() {
this.x = canvas.width / 2;
this.y = canvas.height / 2;
this.vx = Math.random() * 10 - 5;
this.vy = Math.random() * 10 - 5;
this.gravity = 0.3;
particleIndex++;
particles[particleIndex] = this;
this.id = particleIndex;
this.life = 0;
this.maxLife = Math.random() * 30 + 60;
this.color = "hsla(" + parseInt(Math.random() * 360, 10) + ",90%,60%,0.5";
}
Particle.prototype.draw = function() {
this.x += this.vx;
this.y += this.vy;
if (Math.random() < 0.1) {
this.vx = Math.random() * 10 - 5;
this.vy = Math.random() * 10 - 5;
}
this.life++;
if (this.life >= this.maxLife) {
delete particles[this.id];
}
c.fillStyle = this.color;
//c.fillRect(this.x, this.y, 5, 10);
c.beginPath();
c.arc(this.x, this.y, 2.5, degToRad(0), degToRad(360));
c.fill();
};
setInterval(function() {
//normal setting before drawing over canvas w/ black background
c.globalCompositeOperation = "source-over";
c.fillStyle = "rgba(0,0,0,0.5)";
c.fillRect(0, 0, canvas.width, canvas.height);
for (var i = 0; i < particleNum; i++) {
new Particle();
}
// c.globalCompositeOperation = "darken";
for (var i in particles) {
particles[i].draw();
}
}, 30);
}
function degToRad(deg) {
var radians = (deg * Math.PI / 180) - Math.PI / 2;
return radians;
}
<!DOCTYPE html5>
<html>
<head>
<title>disturbed</title>
<script src="toto.js" type="text/javascript"></script>
<script>
window.onload = () => runParticles();
</script>
</head>
<body>
</body>
</html>
I've added a function to detect the mouse position:
function oMousePos(canvas, evt) {
var ClientRect = canvas.getBoundingClientRect();
return { //objeto
x: Math.round(evt.clientX - ClientRect.left),
y: Math.round(evt.clientY - ClientRect.top)
}
}
I've declared a variable m (the mouse).
var m = {x:canvas.width/2,y:canvas.height/2};
and I've changed the origin of the particles from this.x = canvas.width / 2;
this.y = canvas.height / 2;to this.x = m.x; this.y = m.y;
This is the position when the mouse do not move over the canvas
I've added an event "mousemove". When the mouse move over the canvas it's position change.
canvas.addEventListener("mousemove", (evt)=>{
m = oMousePos(canvas, evt);
})
I've also added an event "mouseleave". When the mouse leaves the canvas, the mouse goes back in the center.
canvas.addEventListener("mouseleave", (evt)=>{
m = {x:canvas.width/2,y:canvas.height/2};
})
Also I've changed the setInterval for requestAnimationFrame ( much more efficient ). The code inside is your code.
function runParticles () {
var canvas = document.createElement("canvas");
c = canvas.getContext("2d");
var particles = {};
var particleIndex = 0;
var particleNum = 8;
// set canvas size
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
var m = {x:canvas.width/2,y:canvas.height/2};///////
// add canvas to body
document.body.appendChild(canvas);
// style the canvas
c.fillStyle = "black";
c.fillRect(0, 0, canvas.width, canvas.height);
function Particle() {
this.x = m.x;//////////
this.y = m.y;//////////
this.vx = Math.random() * 10 - 5;
this.vy = Math.random() * 10 - 5;
this.gravity = 0.3;
particleIndex++;
particles[particleIndex] = this;
this.id = particleIndex;
this.life = 0;
this.maxLife = Math.random() * 30 + 60;
this.color = "hsla(" + parseInt(Math.random() * 360, 10) + ",90%,60%,0.5";
}
Particle.prototype.draw = function() {
this.x += this.vx;
this.y += this.vy;
if (Math.random() < 0.1) {
this.vx = Math.random() * 10 - 5;
this.vy = Math.random() * 10 - 5;
}
this.life++;
if (this.life >= this.maxLife) {
delete particles[this.id];
}
c.fillStyle = this.color;
//c.fillRect(this.x, this.y, 5, 10);
c.beginPath();
c.arc(this.x, this.y, 2.5, degToRad(0), degToRad(360));
c.fill();
};
function Draw() {
window.requestAnimationFrame(Draw);
c.globalCompositeOperation = "source-over";
c.fillStyle = "rgba(0,0,0,0.5)";
c.fillRect(0, 0, canvas.width, canvas.height);
for (var i = 0; i < particleNum; i++) {
new Particle();
}
// c.globalCompositeOperation = "darken";
for (var i in particles) {
particles[i].draw();
}
}
Draw();
///////////////////
canvas.addEventListener("mousemove", (evt)=>{
m = oMousePos(canvas, evt);
})
canvas.addEventListener("mouseleave", (evt)=>{
m = {x:canvas.width/2,y:canvas.height/2};
})
///////////////////
}
function degToRad(deg) {
var radians = (deg * Math.PI / 180) - Math.PI / 2;
return radians;
}
runParticles();
function oMousePos(canvas, evt) {
var ClientRect = canvas.getBoundingClientRect();
return { //objeto
x: Math.round(evt.clientX - ClientRect.left),
y: Math.round(evt.clientY - ClientRect.top)
}
}
body,canvas{margin:0;padding:0;}
I hope this helps.