Javascript particles are clipping over the edges - javascript

I have this small particle script that I adjusted to my liking, but I have one problem.
Once the particles come to the edge, they get clipped a bit (maybe 10 - 15px), is there any padding attribute for canvas that I could use to give them a bit of space?
I've created snippet bellow to show what's the problem if anyone is interested to help out?
let resizeReset = function() {
w = canvasBody.width = 800;
h = canvasBody.height = 460;
}
const opts = {
particleColor: "rgb(200,200,200)",
lineColor: "rgb(200,200,200)",
particleAmount: 8,
defaultSpeed: 0.05,
variantSpeed: 1,
defaultRadius: 5,
variantRadius: 10,
linkRadius: 500,
};
window.addEventListener("resize", function(){
deBouncer();
});
let deBouncer = function() {
clearTimeout(tid);
tid = setTimeout(function() {
resizeReset();
}, delay);
};
let checkDistance = function(x1, y1, x2, y2){
return Math.sqrt(Math.pow(x2 - x1, 2) + Math.pow(y2 - y1, 2));
};
let linkPoints = function(point1, hubs){
for (let i = 0; i < hubs.length; i++) {
let distance = checkDistance(point1.x, point1.y, hubs[i].x, hubs[i].y);
let opacity = 1 - distance / opts.linkRadius;
if (opacity > 0) {
drawArea.lineWidth = 0.5;
drawArea.strokeStyle = `rgba(${rgb[0]}, ${rgb[1]}, ${rgb[2]}, ${opacity})`;
drawArea.beginPath();
drawArea.moveTo(point1.x, point1.y);
drawArea.lineTo(hubs[i].x, hubs[i].y);
drawArea.closePath();
drawArea.stroke();
}
}
}
Particle = function(xPos, yPos){
this.x = Math.random() * w;
this.y = Math.random() * h;
this.speed = opts.defaultSpeed + Math.random() * opts.variantSpeed;
this.directionAngle = Math.floor(Math.random() * 360);
this.color = opts.particleColor;
this.radius = opts.defaultRadius + Math.random() * opts. variantRadius;
this.vector = {
x: Math.cos(this.directionAngle) * this.speed,
y: Math.sin(this.directionAngle) * this.speed
};
this.update = function(){
this.border();
this.x += this.vector.x;
this.y += this.vector.y;
};
this.border = function(){
if (this.x >= w || this.x <= 0) {
this.vector.x *= -1;
}
if (this.y >= h || this.y <= 0) {
this.vector.y *= -1;
}
if (this.x > w) this.x = w;
if (this.y > h) this.y = h;
if (this.x < 0) this.x = 0;
if (this.y < 0) this.y = 0;
};
this.draw = function(){
drawArea.beginPath();
drawArea.arc(this.x, this.y, this.radius, 0, Math.PI*2);
drawArea.closePath();
drawArea.fillStyle = this.color;
drawArea.fill();
};
};
function setup(){
particles = [];
resizeReset();
for (let i = 0; i < opts.particleAmount; i++){
particles.push( new Particle() );
}
window.requestAnimationFrame(loop);
}
function loop(){
window.requestAnimationFrame(loop);
drawArea.clearRect(0,0,w,h);
for (let i = 0; i < particles.length; i++){
particles[i].update();
particles[i].draw();
}
for (let i = 0; i < particles.length; i++){
linkPoints(particles[i], particles);
}
}
const canvasBody = document.getElementById("canvas"),
drawArea = canvasBody.getContext("2d");
let delay = 200, tid,
rgb = opts.lineColor.match(/\d+/g);
resizeReset();
setup();
body {
background: #222;
margin: 0rem;
padding: 20px;
font-family: Futura, sans-serif;
display: flex;
justify-content: center;
}
#canvas {
// position: absolute;
display: block;
// top: 0;
// left: 0;
z-index: -1;
width: 80%;
}
<canvas id="canvas"></canvas>

Add the radius to the position on the edge detection
However I found a problem : if a circle start in an edge, it don't seems to move.
let resizeReset = function() {
w = canvasBody.width = 800;
h = canvasBody.height = 460;
}
const opts = {
particleColor: "rgb(200,200,200)",
lineColor: "rgb(200,200,200)",
particleAmount: 8,
defaultSpeed: 0.05,
variantSpeed: 1,
defaultRadius: 5,
variantRadius: 10,
linkRadius: 500,
};
window.addEventListener("resize", function(){
deBouncer();
});
let deBouncer = function() {
clearTimeout(tid);
tid = setTimeout(function() {
resizeReset();
}, delay);
};
let checkDistance = function(x1, y1, x2, y2){
return Math.sqrt(Math.pow(x2 - x1, 2) + Math.pow(y2 - y1, 2));
};
let linkPoints = function(point1, hubs){
for (let i = 0; i < hubs.length; i++) {
let distance = checkDistance(point1.x, point1.y, hubs[i].x, hubs[i].y);
let opacity = 1 - distance / opts.linkRadius;
if (opacity > 0) {
drawArea.lineWidth = 0.5;
drawArea.strokeStyle = `rgba(${rgb[0]}, ${rgb[1]}, ${rgb[2]}, ${opacity})`;
drawArea.beginPath();
drawArea.moveTo(point1.x, point1.y);
drawArea.lineTo(hubs[i].x, hubs[i].y);
drawArea.closePath();
drawArea.stroke();
}
}
}
Particle = function(xPos, yPos){
this.x = Math.random() * w;
this.y = Math.random() * h;
this.speed = opts.defaultSpeed + Math.random() * opts.variantSpeed;
this.directionAngle = Math.floor(Math.random() * 360);
this.color = opts.particleColor;
this.radius = opts.defaultRadius + Math.random() * opts. variantRadius;
this.vector = {
x: Math.cos(this.directionAngle) * this.speed,
y: Math.sin(this.directionAngle) * this.speed
};
this.update = function(){
this.border();
this.x += this.vector.x;
this.y += this.vector.y;
};
this.border = function(){
if (this.x + this.radius >= w || this.x - this.radius<= 0) { // Changes here
this.vector.x *= -1;
}
if (this.y + this.radius >= h || this.y - this.radius <= 0) { // And here
this.vector.y *= -1;
}
if (this.x > w) this.x = w;
if (this.y > h) this.y = h;
if (this.x < 0) this.x = 0;
if (this.y < 0) this.y = 0;
};
this.draw = function(){
drawArea.beginPath();
drawArea.arc(this.x, this.y, this.radius, 0, Math.PI*2);
drawArea.closePath();
drawArea.fillStyle = this.color;
drawArea.fill();
};
};
function setup(){
particles = [];
resizeReset();
for (let i = 0; i < opts.particleAmount; i++){
particles.push( new Particle() );
}
window.requestAnimationFrame(loop);
}
function loop(){
window.requestAnimationFrame(loop);
drawArea.clearRect(0,0,w,h);
for (let i = 0; i < particles.length; i++){
particles[i].update();
particles[i].draw();
}
for (let i = 0; i < particles.length; i++){
linkPoints(particles[i], particles);
}
}
const canvasBody = document.getElementById("canvas"),
drawArea = canvasBody.getContext("2d");
let delay = 200, tid,
rgb = opts.lineColor.match(/\d+/g);
resizeReset();
setup();
body {
background: #222;
margin: 0rem;
padding: 20px;
font-family: Futura, sans-serif;
display: flex;
justify-content: center;
}
#canvas {
// position: absolute;
display: block;
// top: 0;
// left: 0;
z-index: -1;
width: 80%;
background-color:white;
}
<canvas id="canvas"></canvas>

Related

How to make Javascript font responsive?

I'm trying to rework this codepen: https://codepen.io/christhuong/pen/XxzNWK
const data = {
font: {
family: 'Oswald',
size: 70,
weight: 'bold'
},
colors: ['rgb(248, 225, 0)', 'rgb(232, 0, 137)', 'rgb(0, 170, 234)'],
text: `INTERACTIVE * DEVELOPER`,
textlength: 0
}
const canvas = {
elem: document.querySelector('canvas'),
init() {
return this.elem.getContext('2d')
},
resize() {
canvas.elem.width = innerWidth;
canvas.elem.height = innerHeight;
}
}
canvas.resize();
const ctx = canvas.init();
const pointer = {
x: innerWidth/2, y: innerHeight/2,
r: 220
}
class CHAR {
constructor(char, x, y, color, layer) {
this.char = char;
this.cx = x;
this.cy = y;
this.color = color;
this.layer = layer;
this.r = 0;
this.alpha = 0;
this.dx = this.cx;
this.dy = this.cy;
}
static measuretext(text) {
return ctx.measureText(text).width;
}
static dist(x1, y1, x2, y2) {
return Math.sqrt(Math.pow(x1 - x2, 2) + Math.pow(y1 - y2, 2));
}
static getAngle(x1, y1, x2, y2) {
return Math.atan2(y2 - y1, x2 - x1);
}
static init(text, x, y) {
ctx.font = `${data.font.weight} ${data.font.size}px ${data.font.family}`;
ctx.textBaseline = 'middle';
ctx.globalCompositeOperation = 'darken';
for (let color = 0; color < data.colors.length; color++) {
let layer = 1;
switch (color) {
case 0:
layer = 0.5;
break;
case 1:
layer = 0.7;
break;
case 2:
layer = 1;
break;
}
const strs = text.split(' * ');
const textlength = strs.map(str => this.measuretext(str));
data.textlength = Math.max(...textlength);
const textheight = this.measuretext('M') * 1.5;
for (let i = 0; i < strs.length; i++) {
let ww = 0;
for (let j = 0; j < strs[i].length; j++) {
const xx = x - textlength[i] / 2 + ww;
const yy = i == 0 ? y - textheight / 2 : y + textheight / 2;
chars.push(new CHAR(strs[i][j], Math.round(xx), Math.round(yy), data.colors[color], layer));
ww += this.measuretext(strs[i][j]);
}
}
}
}
static draw() {
for (let i = 0; i < data.colors.length; i++) {
ctx.fillStyle = data.colors[i];
for (let j = 0; j < chars.length; j++) {
if (chars[j].color == data.colors[i]) {
ctx.fillText(chars[j].char, chars[j].dx, chars[j].dy);
}
}
}
}
render() {
this.dx += (this.cx - this.dx) * 0.2;
this.dy += (this.cy - this.dy) * 0.2;
}
update() {
const dis = CHAR.dist(pointer.x, pointer.y, this.cx, this.cy);
if (dis < pointer.r) {
this.alpha = CHAR.getAngle(pointer.x, pointer.y, this.cx, this.cy) + Math.PI;
this.r = this.layer * dis * (pointer.r - dis) / pointer.r;
this.dx += (this.cx + this.r * Math.cos(this.alpha) - this.dx) * 0.2;
this.dy += (this.cy + this.r * Math.sin(this.alpha) - this.dy) * 0.2;
} else {
this.render()
}
}
}
let chars = [];
CHAR.init(data.text, innerWidth / 2, innerHeight / 2);
setTimeout(() => {
chars = [];
CHAR.init(data.text, innerWidth / 2, innerHeight / 2);
}, 10);
window.addEventListener('mousemove', e => {
pointer.x = e.clientX; pointer.y = e.clientY;
})
window.addEventListener('touchmove', e => {
e.preventDefault();
pointer.x = e.targetTouches[0].clientX;
pointer.y = e.targetTouches[0].clientY;
})
window.addEventListener('resize', () => {
canvas.resize();
chars = [];
CHAR.init(data.text, innerWidth / 2, innerHeight / 2);
})
const run = () => {
requestAnimationFrame(run);
ctx.clearRect(innerWidth / 2 - data.textlength, innerHeight / 2 - 0.7 * data.textlength, 2 * data.textlength, 1.4 * data.textlength);
if (Math.abs(pointer.x - innerWidth / 2) < data.textlength &&
Math.abs(pointer.y - innerHeight / 2) < 0.7 * data.textlength) {
chars.forEach(e => e.update())
} else { chars.forEach(e => e.render()) }
CHAR.draw();
}
setTimeout(run, 50);
#import url('https://fonts.googleapis.com/css?family=Oswald')
*
margin: 0
padding: 0
font-family: 'Oswald', sans-serif
body
overflow: hidden
canvas
filter: blur(1px)
<canvas>
I'm struggling to make whole text responsive, there is const size, It's not reacting to any css styling, so I guess there is need to adapt responsivness in script, but I don't know how adapt any ready solutions like for example this one: http://jsfiddle.net/xVB3t/2/ please help!
Something like this ?
function magicFunctionToGetSize() {
return parseInt(window.innerWidth/10);
}
const data = {
font: {
family: 'Oswald',
size: 70,
weight: 'bold'
},
colors: ['rgb(248, 225, 0)', 'rgb(232, 0, 137)', 'rgb(0, 170, 234)'],
text: `INTERACTIVE * DEVELOPER`,
textlength: 0
}
const canvas = {
elem: document.querySelector('canvas'),
init() {
return this.elem.getContext('2d')
},
resize() {
canvas.elem.width = innerWidth;
canvas.elem.height = innerHeight;
}
}
canvas.resize();
let ctx = canvas.init();
const pointer = {
x: innerWidth/2, y: innerHeight/2,
r: 220
}
class CHAR {
constructor(char, x, y, color, layer) {
this.char = char;
this.cx = x;
this.cy = y;
this.color = color;
this.layer = layer;
this.r = 0;
this.alpha = 0;
this.dx = this.cx;
this.dy = this.cy;
}
static measuretext(text) {
return ctx.measureText(text).width;
}
static dist(x1, y1, x2, y2) {
return Math.sqrt(Math.pow(x1 - x2, 2) + Math.pow(y1 - y2, 2));
}
static getAngle(x1, y1, x2, y2) {
return Math.atan2(y2 - y1, x2 - x1);
}
static init(text, x, y) {
const fontSize = magicFunctionToGetSize();
ctx.font = `${data.font.weight} ${fontSize}px ${data.font.family}`;
ctx.textBaseline = 'middle';
ctx.globalCompositeOperation = 'darken';
for (let color = 0; color < data.colors.length; color++) {
let layer = 1;
switch (color) {
case 0:
layer = 0.5;
break;
case 1:
layer = 0.7;
break;
case 2:
layer = 1;
break;
}
const strs = text.split(' * ');
const textlength = strs.map(str => this.measuretext(str));
data.textlength = Math.max(...textlength);
const textheight = this.measuretext('M') * 1.5;
for (let i = 0; i < strs.length; i++) {
let ww = 0;
for (let j = 0; j < strs[i].length; j++) {
const xx = x - textlength[i] / 2 + ww;
const yy = i == 0 ? y - textheight / 2 : y + textheight / 2;
chars.push(new CHAR(strs[i][j], Math.round(xx), Math.round(yy), data.colors[color], layer));
ww += this.measuretext(strs[i][j]);
}
}
}
}
static draw() {
for (let i = 0; i < data.colors.length; i++) {
ctx.fillStyle = data.colors[i];
for (let j = 0; j < chars.length; j++) {
if (chars[j].color == data.colors[i]) {
ctx.fillText(chars[j].char, chars[j].dx, chars[j].dy);
}
}
}
}
render() {
this.dx += (this.cx - this.dx) * 0.2;
this.dy += (this.cy - this.dy) * 0.2;
}
update() {
const dis = CHAR.dist(pointer.x, pointer.y, this.cx, this.cy);
if (dis < pointer.r) {
this.alpha = CHAR.getAngle(pointer.x, pointer.y, this.cx, this.cy) + Math.PI;
this.r = this.layer * dis * (pointer.r - dis) / pointer.r;
this.dx += (this.cx + this.r * Math.cos(this.alpha) - this.dx) * 0.2;
this.dy += (this.cy + this.r * Math.sin(this.alpha) - this.dy) * 0.2;
} else {
this.render()
}
}
}
let chars = [];
CHAR.init(data.text, innerWidth / 2, innerHeight / 2);
setTimeout(() => {
chars = [];
CHAR.init(data.text, innerWidth / 2, innerHeight / 2);
}, 10);
window.addEventListener('mousemove', e => {
pointer.x = e.clientX; pointer.y = e.clientY;
})
window.addEventListener('touchmove', e => {
e.preventDefault();
pointer.x = e.targetTouches[0].clientX;
pointer.y = e.targetTouches[0].clientY;
})
window.addEventListener('resize', () => {
canvas.resize();
chars = [];
ctx = canvas.init();
CHAR.init(data.text, innerWidth / 2, innerHeight / 2);
})
const run = () => {
requestAnimationFrame(run);
ctx.clearRect(innerWidth / 2 - data.textlength, innerHeight / 2 - 0.7 * data.textlength, 2 * data.textlength, 1.4 * data.textlength);
if (Math.abs(pointer.x - innerWidth / 2) < data.textlength &&
Math.abs(pointer.y - innerHeight / 2) < 0.7 * data.textlength) {
chars.forEach(e => e.update())
} else { chars.forEach(e => e.render()) }
CHAR.draw();
}
setTimeout(run, 50);
#import url('https://fonts.googleapis.com/css?family=Oswald')
*
margin: 0
padding: 0
font-family: 'Oswald', sans-serif
body
overflow: hidden
canvas
filter: blur(1px)
<canvas>

Invert direction of game

I am developing a basic game where the user needs to go through the openings and avoid crashing with the obstacles. My issue now is that the flow of the game is from the bottom to the top, when in fact I need the obstacles to come from the top to the bottom.
What am I missing in the code? Any help is appreciated.
let myObstacles = [];
let myGameArea = {
canvas: document.createElement("canvas"),
frames: 0,
start: function() {
this.canvas.width = 700;
this.canvas.height = 500;
this.context = this.canvas.getContext("2d");
this.canvas.classList.add('canvasBg');
document.body.insertBefore(this.canvas, document.body.childNodes[0]);
this.interval = setInterval(updateGameArea, 20);
},
clear: function() {
this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
},
stop: function() {
clearInterval(this.interval);
},
score: function() {
var points = Math.floor(this.frames / 5);
this.context.font = "18px serif";
this.context.fillStyle = "black";
this.context.fillText("Score: " + points, 350, 50);
}
}
class Component {
constructor(width, height, color, x, y) {
this.width = width;
this.height = height;
this.color = color;
this.x = x;
this.y = y;
this.speedX = 0;
this.speedY = 0;
}
update() {
let ctx = myGameArea.context;
ctx.fillStyle = this.color;
ctx.fillRect(this.x, this.y, this.width, this.height);
}
newPos() {
this.x += this.speedX;
this.y += this.speedY;
}
left() {
return this.x;
}
right() {
return this.x + this.width;
}
top() {
return this.y;
}
bottom() {
return this.y + this.height;
}
crashWith(obstacle) {
return !(
this.bottom() < obstacle.top() ||
this.top() > obstacle.bottom() ||
this.right() < obstacle.left() ||
this.left() > obstacle.right()
);
}
}
function checkGameOver() {
let crashed = myObstacles.some(function(obstacle) {
return player.crashWith(obstacle);
});
if (crashed) {
myGameArea.stop();
}
}
document.onkeydown = function(e) {
switch (e.keyCode) {
case 38: // up arrow
player.speedY -= 1;
break;
case 40: // down arrow
player.speedY += 1;
break;
case 37: // left arrow
player.speedX -= 1;
break;
case 39: // right arrow
player.speedX += 1;
break;
}
};
function updateObstacles() {
for (i = 0; i < myObstacles.length; i++) {
myObstacles[i].y += -3;
myObstacles[i].update();
}
myGameArea.frames += 1;
if (myGameArea.frames % 60 === 0) {
let x = myGameArea.canvas.width;
let y = myGameArea.canvas.height;
let minWidth = 20;
let maxWidth = 200;
let width = Math.floor(
Math.random() * (maxWidth - minWidth + 1) + minWidth
);
var minGap = 70;
var maxGap = 200;
var gap = Math.floor(Math.random() * (maxGap - minGap + 1) + minGap);
myObstacles.push(new Component(width, 10, "green", 0, y));
myObstacles.push(
new Component(y-width-gap, 10, "green", width+gap, y)
);
}
}
document.onkeyup = function(e) {
player.speedX = 0;
player.speedY = 0;
};
function updateGameArea() {
myGameArea.clear();
player.newPos();
player.update();
updateObstacles();
checkGameOver();
myGameArea.score();
};
myGameArea.start();
let player = new Component(30, 30, "red", 0, 110);
I got it to work by changing 3 things in your updateObstacles function.
First, change myObstacles[i].y += -3 to myObstacles[i].y += 3
Second, change let y = myGameArea.canvas.height to let y = 0
Third, change
new Component(y-width-gap, 10, "green", width+gap, y)
to
new Component(x-width-gap, 10, "green", width+gap, y)
Full code:
function updateObstacles() {
for (i = 0; i < myObstacles.length; i++) {
myObstacles[i].y += 3;
myObstacles[i].update();
}
myGameArea.frames += 1;
if (myGameArea.frames % 60 === 0) {
let x = myGameArea.canvas.width;
let y = 0;
let minWidth = 20;
let maxWidth = 200;
let width = Math.floor(
Math.random() * (maxWidth - minWidth + 1) + minWidth
);
var minGap = 70;
var maxGap = 200;
var gap = Math.floor(Math.random() * (maxGap - minGap + 1) + minGap);
myObstacles.push(new Component(width, 10, "green", 0, y));
myObstacles.push(
new Component(x-width-gap, 10, "green", width+gap, y)
);
}
}
Example jsfiddle

Remove objects in the canvas in certain coordinates

I would like to remove the balls already generated in the canvas on the click and decrease the counter on the bottom, but my function does not work. Here is my code concerning the part of the ball removal.
Is it possible to use a div to get the same result and to facilitate the removal of the balls? thank you
ball.onclick = function removeBalls(event) {
var x = event.clientX;
var y = event.clientY;
ctx.clearRect(x, y, 100, 50);
ctx.fillStyle = "#000000";
ctx.font = "20px Arial";
ctx.fillText("Balls Counter: " + balls.length - 1, 10, canvas.height - 10);
}
below I enclose my complete code
// GLOBAL VARIBLES
var gravity = 4;
var forceFactor = 0.3; //0.3 0.5
var mouseDown = false;
var balls = []; //hold all the balls
var mousePos = []; //hold the positions of the mouse
var ctx = canvas.getContext('2d');
var heightBrw = canvas.height = window.innerHeight;
var widthBrw = canvas.width = window.innerWidth;
var bounciness = 1; //0.9
window.onload = function gameCore() {
function onMouseDown(event) {
mouseDown = true;
mousePos["downX"] = event.pageX;
mousePos["downY"] = event.pageY;
}
canvas.onclick = function onMouseUp(event) {
mouseDown = false;
balls.push(new ball(mousePos["downX"], mousePos["downY"], (event.pageX - mousePos["downX"]) * forceFactor,
(event.pageY - mousePos["downY"]) * forceFactor, 5 + (Math.random() * 10), bounciness, random_color()));
ball
}
function onMouseMove(event) {
mousePos['currentX'] = event.pageX;
mousePos['currentY'] = event.pageY;
}
function resizeWindow(event) {
canvas.height = window.innerHeight;
canvas.width = window.innerWidth;
}
function reduceBounciness(event) {
if (bounciness == 1) {
for (var i = 0; i < balls.length; i++) {
balls[i].b = bounciness = 0.9;
document.getElementById("btn-bounciness").value = "⤽ Bounciness";
}
} else {
for (var i = 0; i < balls.length; i++) {
balls[i].b = bounciness = 1;
document.getElementById("btn-bounciness").value = " ⤼ Bounciness";
}
}
return bounciness;
}
function reduceSpeed(event) {
for (var i = 0; i < balls.length; i++) {
balls[i].vx = velocityX = 20 + c;
balls[i].vy = velocityY = 20 + c;
}
}
function speedUp(event) {
for (var i = 0; i < balls.length; i++) {
balls[i].vx = velocityX = 120 + c;
balls[i].vy = velocityY = 120 + c;
}
}
function stopGravity(event) {
if (gravity == 4) {
for (var i = 0; i < balls.length; i++) {
balls[i].g = gravity = 0;
balls[i].vx = velocityX = 0;
balls[i].vy = velocityY = 0;
document.getElementById("btn-gravity").value = "►";
}
} else {
for (var i = 0; i < balls.length; i++) {
balls[i].g = gravity = 4;
balls[i].vx = velocityX = 100;
balls[i].vy = velocityY = 100;
document.getElementById("btn-gravity").value = "◾";
}
}
}
ball.onclick = function removeBalls(event) {
var x = event.clientX;
var y = event.clientY;
ctx.clearRect(x, y, 100, 50);
ctx.fillStyle = "#000000";
ctx.font = "20px Arial";
ctx.fillText("Balls Counter: " + balls.length - 1, 10, canvas.height - 10);
}
document.getElementById("btn-gravity").addEventListener("click", stopGravity);
document.getElementById("btn-speed-up").addEventListener("click", speedUp);
document.getElementById("btn-speed-down").addEventListener("click", reduceSpeed);
document.getElementById("btn-bounciness").addEventListener("click", reduceBounciness);
document.addEventListener("mousedown", onMouseDown);
document.addEventListener("mousemove", onMouseMove);
window.addEventListener('resize', resizeWindow);
}
// GRAPHICS CODE
function circle(x, y, r, c) { // x position, y position, r radius, c color
//draw a circle
ctx.beginPath(); //approfondire
ctx.arc(x, y, r, 0, Math.PI * 2, true);
ctx.closePath();
//fill
ctx.fillStyle = c;
ctx.fill();
//stroke
ctx.lineWidth = r * 0.1; //border of the ball radius * 0.1
ctx.strokeStyle = "#000000"; //color of the border
ctx.stroke();
}
function random_color() {
var letter = "0123456789ABCDEF".split(""); //exadecimal value for the colors
var color = "#"; //all the exadecimal colors starts with #
for (var i = 0; i < 6; i++) {
color = color + letter[Math.round(Math.random() * 15)];
}
return color;
}
function selectDirection(fromx, fromy, tox, toy) {
ctx.beginPath();
ctx.moveTo(fromx, fromy);
ctx.lineTo(tox, toy);
ctx.moveTo(tox, toy);
}
//per velocità invariata rimuovere bounciness
function draw_ball() {
this.vy = this.vy + gravity * 0.1; // v = a * t
this.x = this.x + this.vx * 0.1; // s = v * t
this.y = this.y + this.vy * 0.1;
if (this.x + this.r > canvas.width) {
this.x = canvas.width - this.r;
this.vx = this.vx * -1 * this.b;
}
if (this.x - this.r < 0) {
this.x = this.r;
this.vx = this.vx * -1 * this.b;
}
if (this.y + this.r > canvas.height) {
this.y = canvas.height - this.r;
this.vy = this.vy * -1 * this.b;
}
if (this.y - this.r < 0) {
this.y = this.r;
this.vy = this.vy * 1 * this.b;
}
circle(this.x, this.y, this.r, this.c);
}
// OBJECTS
function ball(positionX, positionY, velosityX, velosityY, radius, bounciness, color, gravity) {
this.x = positionX;
this.y = positionY;
this.vx = velosityX;
this.vy = velosityY;
this.r = radius;
this.b = bounciness;
this.c = color;
this.g = gravity;
this.draw = draw_ball;
}
// GAME LOOP
function game_loop() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
if (mouseDown == true) {
selectDirection(mousePos['downX'], mousePos['downY'], mousePos['currentX'], mousePos['currentY']);
}
for (var i = 0; i < balls.length; i++) {
balls[i].draw();
}
ctx.fillStyle = "#000000";
ctx.font = "20px Arial";
ctx.fillText("Balls Counter: " + balls.length, 10, canvas.height - 10);
}
setInterval(game_loop, 10);
* {
margin: 0px; padding: 0px;
}
html, body {
width: 100%; height: 100%;
}
#canvas {
display: block;
height: 95%;
border: 2px solid black;
width: 98%;
margin-left: 1%;
}
#btn-speed-up, #btn-speed-down, #btn-bounciness, #btn-gravity{
padding: 0.4%;
background-color: beige;
text-align: center;
font-size: 20px;
font-weight: 700;
float: right;
margin-right: 1%;
margin-top:0.5%;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Power Balls</title>
<link rel="stylesheet" type="text/css" href="css/style.css">
</head>
<body>
<canvas id="canvas"></canvas>
<input type="button" value="⤼ Bounciness" id="btn-bounciness"></input>
<input type="button" onclick="c+=10" value="+ Speed" id="btn-speed-up"></input>
<input type="button" value="◾" id="btn-gravity"></input>
<input type="button" onclick="c+= -10" value=" - Speed" id="btn-speed-down"></input>
<script src="js/main.js"></script>
</body>
</html>
I see two problems:
ball.onclick will not get triggered, as ball it is not a DOM object. Instead, you need to work with canvas.onclick. Check whether the user clicked on a ball or on empty space to decide whether to delete or create a ball.
To delete the ball, ctx.clearRect is not sufficient. This will clear the ball from the currently drawn frame, but the object still remains in the array balls and will therefore be drawn again in the next frame via balls[i].draw();. Instead, you need to remove the clicked ball entirely from the array, e. g. by using splice.
Otherwise, nice demo! :)
This cannot be done because the canvas is an immediate mode API. All you can do is draw over the top but this is not reliable.
https://en.wikipedia.org/wiki/Immediate_mode_(computer_graphics)
You will have to store each item in a separate data structure, then re-draw whenever a change occurs. In your case there is an array of balls, so you should remove the one that was clicked, before redrawing the entire array.
Each time you remove something, clear the canvas then re-draw each ball.
There are optimisations you can make if this is too slow.

Draw with realX, realY, etc using Interp

I have a problem with using the interp to improve my drawing function. For some reason the realX returns undefined every 3 frames. I'm using this guide to implement this functionality. The end goal is to make the collision system work so it would reflect bullets on an incomming shield (basicly how the bullets currently interact with the canvas borders. This is part of the code:
//INT
var canvas = document.getElementById('ctx'),
cw = canvas.width,
ch = canvas.height,
cx = null,
bX = canvas.getBoundingClientRect().left,
bY = canvas.getBoundingClientRect().top,
mX,
mY,
lastFrameTimeMs = 0,
maxFPS = 60,
fps = 60,
timestep = 1000/fps,
lastTime = (new Date()).getTime(),
currentTime = 0,
delta = 0,
framesThisSecond = 0,
lastFpsUpdate = 0,
running = false,
started = false,
frameID = 0;
var gametimeStart = Date.now(),
frameCount = 0,
score = 0,
player,
enemyList = {},
boostList = {},
bulletList = {},
pulseList = {},
shieldList = {};
//CREATE , create object
var Unit = function(){
this.x;
this.y;
this.realX;
this.realY;
this.type = "unit";
this.hp = 0;
this.color;
this.collision = function(arc){
return this.x + this.r + arc.r > arc.x
&& this.x < arc.x + this.r + arc.r
&& this.y + this.r + arc.r > arc.y
&& this.y < arc.y + this.r + arc.r
};
this.position = function(delta){
boundX = document.getElementById('ctx').getBoundingClientRect().left;
boundY = document.getElementById('ctx').getBoundingClientRect().top;
this.realX = this.x;
this.realX = this.y;
this.realR = this.r;
this.x += this.spdX * delta / 1000;
this.y += this.spdY * delta / 1000;
if (this.x < this.r || this.x + this.r > cw){
this.spdX = -this.spdX;
if (Math.random() < 0.5) {
this.spdY += 100;
} else {
this.spdY -= 100;
}
}
if (this.y < this.r || this.y + this.r > ch){
this.spdY = -this.spdY;
if (Math.random() < 0.5) {
this.spdX += 100;
} else {
this.spdX -= 100;
}
}
};
this.draw = function(interp){
ctx.save();
ctx.fillStyle = this.color;
ctx.beginPath();
//THIS DOESN'T WORK, the code is working perfectly without it
this.x = (this.realX + (this.x - this.realX) * interp);
this.y = (this.realY + (this.y - this.realY) * interp);
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
ctx.arc(this.x,this.y,this.r,0,2*Math.PI,false);
ctx.fill();
ctx.restore();
};
}
//Player
var Player = function(){
//Coördinates
this.x = 50;
this.y = 50;
this.r = 10;
//Stats
this.spdX = 30;
this.spdY = 5;
this.atkSpd = 1;
this.hp = 100;
//Other
this.name;
this.color = "green";
this.type = "player";
this.angle = 1;
this.attack = function attack(enemy){
enemy.hp -= 10;
};
};
Player.prototype = new Unit();
//Boost
var Boost = function(){
//Coördinates
this.x = 300;
this.y = 300;
this.r = 5;
};
Boost.prototype = new Unit();
//Bullet
var Bullet = function(){
//Coördinates
this.x = player.x;
this.y = player.y;
this.r = 3;
//Stats
var angle = player.angle*90;
this.spdX = Math.cos(angle/180*Math.PI)*200;
this.spdY = Math.sin(angle/180*Math.PI)*200;
//Other
if (player.angle === 4)
player.angle = 0;
player.angle++;
};
Bullet.prototype = new Unit();
var player = new Player();
var boost = new Boost();
var bullet = new Bullet();
//UPDATE
update = function(delta){
bullet.position(delta);
if(player.collision(boost)){
alert("collide");
}
};
//DRAW
draw = function(interp){
ctx.clearRect(0,0,cw,ch);
fpsDisplay.textContent = Math.round(fps) + ' FPS';
boost.draw(interp);
bullet.draw(interp);
player.draw(interp);
};
//LOAD
if (!document.hidden) { console.log("viewed"); }
function panic() { delta = 0; }
function begin() {}
function end(fps) {
if (fps < 25) {
fpsDisplay.style.color = "red";
}
else if (fps > 30) {
fpsDisplay.style.color = "black";
}
}
function stop() {
running = false;
started = false;
cancelAnimationFrame(frameID);
}
function start() {
if (!started) {
started = true;
frameID = requestAnimationFrame(function(timestamp) {
draw(1);
running = true;
lastFrameTimeMs = timestamp;
lastFpsUpdate = timestamp;
framesThisSecond = 0;
frameID = requestAnimationFrame(mainLoop);
});
}
}
function mainLoop(timestamp) {
if (timestamp < lastFrameTimeMs + (1000 / maxFPS)) {
frameID = requestAnimationFrame(mainLoop);
return;
}
delta += timestamp - lastFrameTimeMs;
lastFrameTimeMs = timestamp;
begin(timestamp, delta);
if (timestamp > lastFpsUpdate + 1000) {
fps = 0.25 * framesThisSecond + 0.75 * fps;
lastFpsUpdate = timestamp;
framesThisSecond = 0;
}
framesThisSecond++;
var numUpdateSteps = 0;
while (delta >= timestep) {
update(timestep);
delta -= timestep;
if (++numUpdateSteps >= 240) {
panic();
break;
}
}
draw(delta / timestep);
end(fps);
frameID = requestAnimationFrame(mainLoop);
}
start();
if (typeof (canvas.getContext) !== undefined) {
ctx = canvas.getContext('2d');
ctx.font = '30px Arial';
}
//CONTROLLES
//Mouse Movement
document.onmousemove = function(mouse){
var mouseX = mouse.clientX - bX;
var mouseY = mouse.clientY - bY;
if(mouseX < player.width/2)
mouseX = player.width/2;
if(mouseX > cw-player.width/2)
mouseX = cw-player.width/2;
if(mouseY < player.height/2)
mouseY = player.height/2;
if(mouseY > ch-player.height/2)
mouseY = ch-player.height/2;
player.x = mX = mouseX;
player.y = mY = mouseY;
}
//Pauze Game
var pauze = function(){
if(window.event.target.id === "pauze"){
stop();
}
if(window.event.target.id === "ctx"){
start();
}
};
document.addEventListener("click", pauze);
html {
height: 100%;
box-sizing: border-box;
}
*,*:before,*:after {
box-sizing: inherit;
}
body {
position: relative;
margin: 0;
padding-bottom: 6rem;
min-height: 100%;
font-family: "Helvetica Neue", Arial, sans-serif;
}
main {
margin: 0 auto;
padding-top: 64px;
max-width: 640px;
width: 94%;
}
main h1 {
margin-top: 0;
}
canvas {
border: 1px solid #000;
}
<canvas id="ctx" width="500" height="500"></canvas>
<div id="fpsDisplay" style="font-size:50px; position:relative; margin: 0 auto;"></div>
<p id="status"></p>
<button id="pauze">Pauze</button>
Declare, define, use.
The problem is you are using a variables that are undefined.
You have 3 objects, Player, Boost, and Bullet each of which you assign the object Unit to their prototypes.
You declare and define unit
function Unit(){
this.x;
this.y;
this.realX;
this.realY;
// blah blah
this.draw = function(){
// blah blah
this.draw = function (interp) {
ctx.save();
ctx.fillStyle = this.color;
ctx.beginPath();
// this.realX and this.realY are undefined
this.x = (this.realX + (this.x - this.realX) * interp);
this.y = (this.realY + (this.y - this.realY) * interp);
ctx.arc(this.x, this.y, this.r, 0, 2 * Math.PI, false);
ctx.fill();
ctx.restore();
};
}
Then Player
var Player = function () {
//Coördinates
this.x = 50;
this.y = 50;
this.r = 10;
//Stats
// etc....
};
Then add a Unit to the prototype.
Player.prototype = new Unit();
This gives Player the unit properties x, y, realX, realY But realX and realY are undefined. Same with the two other objects Boost, Bullet
Any existing properties with the same name stay as is and keep their values. Any properties not in Player will get them from Unit, but in unit you have only declared the properties realX, realY you have not defined them.
You need to define the properties by giving them a value before you use them. You can do this in Unit
function Unit(){
this.x = 0; // default value I am guessing
this.y = 0;
this.realX = 10;
this.realY = 10;
Then in Player
function Player(){
this.x = 50; // these will keep the value they have
this.y = 50;
// realX and realY will have the defaults when you add to the prototype
// Or you can define them here
this.realX = 20;
this.realY = 20;
Before you can use a variable you must define what it is or check if it is defined and take the appropriate action.
// in draw function.
if(this.realX === undefined){
this.realX = 100; // set the default if not defined;
}
BTW you should get rid of the alerts they are very annoying when you have them appear one after the other without a chance to navigate away from the page.

How to remove canvas background and display full background image

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

Categories