I can't find what is causing the canvas to show nothing. Please help me!
Here is the image that shows what is happening http://imgur.com/So67XMM
In the body tag I'm calling the function inicializar, like this: <
body onload="inicializar()">
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
canvas.width = 600;
canvas.height = 480;
var w = canvas.width;
var h = canvas.height;
var friction = 0.98,
alturaJogador,
larguraJogador,
pontosJogador,
espaco,
keys = [];
var jogador1 = {
x: w / 2,
y: h / 2,
s: 2,
vx: 0,
vy: 0,
dir: 0
};
var bola = {
x: canvas.width / 2,
y: 250,
d: 10,
s: 2,
vx: 0,
vy: 0
};
function inicializar() {
alturaJogador = 25;
larguraJogador = 25;
pontosJogador = 0;
canvas = document.getElementById("canvas");
context = canvas.getContext("2d");
espaco = false;
setInterval(update, 10);
}
function intersects(x1, y1, w1, h1, x2, y2, w2, h2) {
if (w2 !== Infinity && w1 !== Infinity) {
w2 += x2;
w1 += x1;
if (isNaN(w1) || isNaN(w2) || x2 > w1 || x1 > w2) {
return false;
}
}
if (y2 !== Infinity && h1 !== Infinity) {
h2 += y2;
h1 += y1;
if (isNaN(h1) || isNaN(y2) || y2 > h1 || y1 > h2) {
return false;
}
}
return true;
}
function update() {
if (keys[38]) {
if (jogador1.vy > -jogador1.s) {
jogador1.vy--;
}
}
if (keys[40]) {
if (jogador1.vy < jogador1.s) {
jogador1.vy++;
}
}
if (keys[39]) {
if (jogador1.vx < jogador1.s) {
jogador1.vx++;
}
}
if (keys[37]) {
if (jogador1.vx > -jogador1.s) {
jogador1.vx--;
}
}
if (keys[32]) {
espaco = true;
} else {
espaco = false;
}
var vB = 10;
var angle = Math.atan(Math.abs(jogador1.vy / jogador1.vx));
var vBx = Math.cos(angle) * vB;
if (jogador1.vx < 0) {
vBx *= -1;
}
var vBy = Math.sin(angle) * vB;
if (jogador1.vy < 0) {
vBy *= -1;
}
jogador1.vy *= friction;
jogador1.y += jogador1.vy / 2;
jogador1.vx *= friction;
jogador1.x += jogador1.vx / 2;
if (jogador1.x >= 575) {
jogador1.x = 575;
} else if (jogador1.x <= 0) {
jogador1.x = 0;
}
if (jogador1.y > 455) {
jogador1.y = 455;
} else if (y <= 0) {
jogador1.y = 0;
}
ctx.clearRect(0, 0, 600, 480);
ctx.beginPath();
ctx.fillRect(jogador1.x, jogador1.y, alturaJogador, larguraJogador);
ctx.fill();
ctx.beginPath();
ctx.arc(bola.x, bola.y, bola.d, 0, Math.PI * 2, true);
ctx.fill();
ctx.font = "32pt Tahoma";
ctx.fillText(pontosJogador, canvas.width - 70, 50);
ctx.fillText(jogador1.vx, canvas.width - 570, 50);
ctx.fillText(jogador1.vy, canvas.width - 570, 90);
ctx.fillText(jogador1.dir, canvas.width - 570, 130);
}
update();
document.body.addEventListener("keydown", function(e) {
keys[e.keyCode] = true;
});
document.body.addEventListener("keyup", function(e) {
keys[e.keyCode] = false;
});
canvas {
border: 1px solid #000000;
}
<canvas id="canvas" width="600" height="480">
Navegador não suporta HTML5
</canvas>
<!DOCTYPE html>
<head>
<title>Game</title>
<style type="text/css">
canvas {
border: 1px solid #000000;
}
</style>
</head>
<body onload="inicializar()">
<canvas id="canvas" width="600" height="480">
HTML5 not supported
</canvas>
<script type="text/javascript">
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
canvas.width = 600;
canvas.height = 480;
var w = canvas.width;
var h = canvas.height;
var friction = 0.98,
alturaJogador,
larguraJogador,
pontosJogador,
espaco,
keys = [];
var jogador1 = {
x: w / 2,
y: h / 2,
s: 2,
vx: 0,
vy: 0,
dir: 0
};
var bola = {
x: canvas.width / 2,
y: 250,
d: 10,
s: 2,
vx: 0,
vy: 0
};
function inicializar() {
alturaJogador = 25;
larguraJogador = 25;
pontosJogador = 0;
canvas = document.getElementById("canvas");
context = canvas.getContext("2d");
espaco = false;
setInterval(update, 10);
}
function intersects(x1, y1, w1, h1, x2, y2, w2, h2) {
if (w2 !== Infinity && w1 !== Infinity) {
w2 += x2;
w1 += x1;
if (isNaN(w1) || isNaN(w2) || x2 > w1 || x1 > w2){
return false;
}
}
if (y2 !== Infinity && h1 !== Infinity) {
h2 += y2;
h1 += y1;
if (isNaN(h1) || isNaN(y2) || y2 > h1 || y1 > h2){
return false;
}
}
return true;
}
function update() {
if(keys[38]) {
if(jogador1.vy > -jogador1.s) {
jogador1.vy--;
}
}
if(keys[40]) {
if(jogador1.vy < jogador1.s) {
jogador1.vy++;
}
}
if(keys[39]) {
if(jogador1.vx < jogador1.s) {
jogador1.vx++;
}
}
if(keys[37]) {
if(jogador1.vx > -jogador1.s) {
jogador1.vx--;
}
}
if(keys[32]) {
espaco = true;
} else {
espaco = false;
}
var vB=10;
var angle=Math.atan(Math.abs(jogador1.vy/jogador1.vx));
var vBx = Math.cos(angle)*vB;
if (jogador1.vx < 0) {
vBx *= -1;
}
var vBy = Math.sin(angle)*vB;
if (jogador1.vy < 0) {
vBy *= -1;
}
jogador1.vy *= friction;
jogador1.y += jogador1.vy /2;
jogador1.vx *= friction;
jogador1.x += jogador1.vx/2;
if(jogador1.x >= 575) {
jogador1.x = 575;
} else if(jogador1.x <= 0) {
jogador1.x = 0;
}
if(jogador1.y > 455) {
jogador1.y = 455;
} else if(y <= 0) {
jogador1.y = 0;
}
ctx.clearRect(0, 0, 600, 480);
ctx.beginPath();
ctx.fillRect(jogador1.x, jogador1.y, alturaJogador, larguraJogador);
ctx.fill();
ctx.beginPath();
ctx.arc(bola.x, bola.y, bola.d, 0, Math.PI * 2, true);
ctx.fill();
ctx.font = "32pt Tahoma";
ctx.fillText(pontosJogador, canvas.width - 70, 50);
ctx.fillText(jogador1.vx, canvas.width - 570, 50);
ctx.fillText(jogador1.vy, canvas.width - 570, 90);
ctx.fillText(jogador1.dir, canvas.width - 570, 130);
}
update();
document.body.addEventListener("keydown", function (e) {
keys[e.keyCode] = true;
});
document.body.addEventListener("keyup", function (e) {
keys[e.keyCode] = false;
});
</script>
</body>
</html>
Give the body an id:
<body id="body">
Then go into javascript to interact:
var body = document.getElementById("body");
body.onload = function () {
inicializar();
}
I hope this helped :)
Related
Im making a pong game and I want to make the ball have a speedX and a speedY that is added to the ball that makes it move along the X and Y axis but im not sure how to adjust those variables based off of the balls angle. In function ballPhysics() I need to replace the 0's with something to get the speed it should go along that axis. But if anyone finds anything else that should be worked on itd be great if you let me know thanks.
let cvs, ctx;
let width = 600, height = 500;
let keysPressed = [];
class Wall {
constructor(x, y, w, h, speed) {
this.x = x;
this.y = y;
this.w = w;
this.h = h;
this.speed = speed;
}
}
class Ball {
constructor(x, y , w, h, speedX, speedY, angle) {
this.x = x;
this.y = y;
this.w = w;
this.h = h;
this.speedX = speedX;
this.speedY = speedY;
this.angle = angle;
}
}
let left = new Wall(25, 250, 10, 100, 10);
let right = new Wall(width-25, 250, 10, 100, 10)
let ball = new Ball(width/2, height/2, 5, 5, 0, 0, 0);
function ballPhysics() {
ball.x += ball.speedX;
ball.y += ball.speedY;
ball.speedX = 0//figure out direction;
ball.speedY = 0//figure out direction;
}
function start() {
ball.x = width/2;
ball.y = height/2;
if(Math.random() < 0.5) {
ball.angle = 90;
} else {
ball.angle = -90;
}
console.log(ball.angle);
}
function update() {
setInterval(function () {
ballPhysics();
for(let i = 0; i < keysPressed.length; i++) {
if(keysPressed[i] == 'KeyW' && left.y >= 0) {
left.y -= left.speed;
}
if(keysPressed[i] == 'KeyS' && left.y + left.h <= height) {
left.y += left.speed;
}
if(keysPressed[i] == 'ArrowUp' && right.y >= 0) {
right.y -= right.speed;
}
if(keysPressed[i] == 'ArrowDown' && right.y + right.h <= height) {
right.y += right.speed;
}
if(keysPressed[i] == 'Space') {
start();
}
}
}, 16)
}
function renderPlayers() {
ctx.fillStyle = '#FF0000';
ctx.fillRect(left.x, left.y, left.w, left.h);
ctx.fillRect(right.x, right.y, right.w, right.h);
}
function renderBall() {
ctx.fillStyle = '#0000FF';
ctx.fillRect(ball.x, ball.y, ball.w, ball.h);
}
function render() {
ctx.clearRect(0, 0, cvs.width, cvs.height);
renderBall();
renderPlayers();
requestAnimationFrame(render);
}
window.addEventListener("DOMContentLoaded", function () {
cvs = document.getElementById("cvs");
ctx = cvs.getContext("2d");
cvs.width = width;
cvs.height = height;
update();
render();
});
window.addEventListener('keydown', function(e) {
if(!keysPressed.includes(e.code)) {
keysPressed.push(e.code);
}
});
window.addEventListener('keyup', function(e) {
for(let i = 0; i < keysPressed.length; i++) {
if(keysPressed[i] == e.code) {
keysPressed.splice(i, 1);
}
}
});
#cvs {
border: solid 1px black;
background: #D1C3C3;
}
<!DOCTYPE html>
<html lang="en">
<head>
<title>Platformer</title>
<link rel="stylesheet" href="/style.css" />
<script src="/script.js" defer></script>
</head>
<body>
<canvas width="0" height="0" id="cvs"></canvas>
</body>
</html>
I'm currently making a game and I am at the point where I'm trying to implement powerups. For the power ups I use a for loop that creates an object which allows me to give them different characteristics.
var type;
Powerups = [];
for(var j = 0; j < 325; j++) {
if (type="undefined"){
type = "scoreUp";
} else if(type="scoreUp"){
type = "horizonUp"
} else if (type="horizonUp"){
type = "newBall"
} else if (type="newBall") {
type = "scoreUp"
}
Powerups.push({
"x": randInt(20,360),
"y": 345 + (j * 240),
"width": 10,
"type": type
})
}
I then use rect circle collision that allows me to detect if the player collides with a powerup. If it does, the following line of code runs Powerups.splice(j, 1)
One thing that I've noticed is that the powerups never change and always increase score when a collision occurs. I think that this is because of the code that I use to remove the power up when colliding.
Is there a way where I could make it work as intended
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var isMenu = true;
var isPlaying = false;
var testing = true;
var gameOver = false;
var pause;
var pressingLeft = false;
var pressingRight = false;
var pressingP = false;
var Platforms = [];
var Powerups = [];
var difficulty = 1;
var playerGravity = 1;
var Player = { color: "red", radius: 7.5, stepY: 1.5, x: 175, y: 75 };
var Score = 0;
var speed = 1;
var type;
var moveR = 2;
var moveL = 2;
function PlayerColliding(circle, rect) {
var distX = Math.abs(circle.x - rect.x - rect.width / 2);
var distY = Math.abs(circle.y - rect.y - 20 / 2);
if (distX > (rect.width / 2 + circle.radius) && (distX) - 70 < (rect.width / 2 + circle.radius)) return false;
if (distY > (20 / 2 + circle.radius)) return false;
if (distX <= (rect.width / 2)) return true;
if (distY >= (20 / 2)) return true;
var dx = distX - rect.width / 2;
var dy = distY - 20 / 2;
return (dx * dx + dy * dy <= (circle.radius * circle.radius));
}
function PowerColliding(circle, rect) {
var distX = Math.abs(circle.x - rect.x - rect.width / 2);
var distY = Math.abs(circle.y - rect.y - 20 / 2);
if (distX > (rect.width / 2 + circle.radius)) return false;
if (distY > (20 / 2 + circle.radius)) return false;
if (distX <= (rect.width / 2)) return true;
if (distY >= (20 / 2)) return true;
var dx = distX - rect.width / 2;
var dy = distY - 20 / 2;
return (dx * dx + dy * dy <= (circle.radius * circle.radius));
}
function drawBackground(Player) {
ctx.fillStyle = "black"; ctx.fillRect(0, 0, canvas.width, canvas.height);
if (isMenu && !isPlaying) {
Score = 0;
createText("60px monospace", "white", "FallDown", 45, 130);
createText("34px Arial", "white", "PLAY", 130, 240);
createText("34px Arial", "white", "LEADERBOARD", 50, 300);
createText("34px Arial", "white", "SETTINGS", 90, 360);
createText("34px Arial", "white", "INFO", 130, 420);
}
if(isMenu && isPlaying) {
createText("60px monospace", "white", "Game Mode", 40, 130);
createText("34px Arial", "white", "CLASSIC", 110, 240);
createText("34px Arial", "white", "VERSUS", 113.5, 300);
}
else if(pause) {
isPlaying = false;
createText("60px monospace", "white", "PAUSED", 90, 130);
createText("34px Arial", "white", "RESUME", 115, 260);
createText("34px Arial", "white", "SETTINGS", 100, 340);
createText("34px Arial", "white", "QUIT", 145, 420);
}
else if(!isMenu && isPlaying) {
if (testing) {
Platforms = [];
for (var i = 0; i < 1300; i++) {
Platforms.push({
"x": 10,
"y": 300 + (i * 60),
"width": (Math.random() * canvas.width) - 60
});
}
testing = false;
Powerups = [];
for(var j = 0; j < 325; j++) {
if (type="undefined"){
type = "scoreUp";
} else if(type="scoreUp"){
type = "horizonUp"
} else if (type="horizonUp"){
type = "newBall"
} else if (type="newBall") {
type = "scoreUp"
}
Powerups.push({
"x": randInt(20,360),
"y": 345 + (j * 240),
"width": 10,
"type": type
})
}
}
if(Player.y<=0) {
restartGame()
}
var playerCollided;
for (var i in Platforms) {
ctx.fillStyle = "#00ffff";
ctx.fillRect(10, Platforms[i].y, Platforms[i].width, 20);
var totalTest = Platforms[i].width + 60;
ctx.fillRect(totalTest + 30, Platforms[i].y, canvas.width - totalTest, 20);
Platforms[i].y -= 1;
if (!playerCollided) {
if (PlayerColliding(Player, Platforms[i])) {
playerGravity = -1;
playerCollided = true;
} else {
playerGravity = 2.5;
}
}
}
var powerCollided;
for (var j in Powerups) {
ctx.fillStyle = "#ff00ff";
ctx.fillRect(Powerups[j].x, Powerups[j].y, Powerups[j].width, 10);
Powerups[j].y -= 1;
if (!powerCollided) {
if (PowerColliding(Player, Powerups[j])) {
powerCollided = true;
Powerups.splice(j, 1)
if(type="scoreUp") {
Score += 75
} else if (type="horizonUp") {
moveR+= 0.5;
moveL+=0.5;
console.log("hup")
}
}
}
}
displayScore();
detectBorderCollision();
detectPlayerCollision();
drawPlayer();
drawBorder();
}
if (Platforms.length === 7) Platforms = [];
}
function displayScore() {
ctx.beginPath();
Score +=1;
ctx.font = "15px arial black";
ctx.fillStyle = 'white';
ctx.strokeStyle = 'black';
ctx.fillText(Score, 180, 50);
ctx.lineWidth = 0.25;
ctx.strokeText(Score, 180, 50);
ctx.fill();
ctx.stroke();
ctx.closePath();
}
function detectBorderCollision() {
if (Player.x > 370 - Player.radius) {
Player.x = 370 - Player.radius;
} else if (Player.x < 3.8 + Player.radius * 2) {
Player.x = 3.8 + Player.radius * 2
}
}
function detectPlayerCollision() {
}
function randInt(min, max) {
return ~~(Math.random() * (max - min + 1) + min);
}
function drawPlayer() {
ctx.beginPath();
ctx.fillStyle = Player.color;
ctx.arc(Player.x, Player.y, Player.radius, 0, 2 * Math.PI);
ctx.fill();
ctx.closePath();
Player.y += playerGravity;
if (pressingRight) {
Player.x += 2;
} else if (pressingLeft) {
Player.x -= 2;
}
/*
ctx.fillStyle = "#00ffff"; ctx.fillRect(10, 160, 300, 20); */ }
function drawBorder() {
ctx.beginPath();
ctx.strokeStyle = "#00ffff";
ctx.lineWidth = 10;
ctx.moveTo(5, 0);
ctx.lineTo(5, 640);
ctx.moveTo(375, 0);
ctx.lineTo(375, 640);
ctx.stroke();
ctx.closePath();
}
function createText(font, color, value, posX, posY) {
ctx.font = font;
ctx.fillStyle = color;
ctx.fillText(value, posX, posY)
}
function isInside(realX, realY, x1, x2, y1, y2) {
return (realX > x1 && realX < x2) && (realY > y1 && realY < y2)
}
function drawGame() {
drawBackground(Player);
}
function startDrawing() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
drawGame();
requestAnimationFrame(startDrawing);
}
function restartGame() {
isPlaying = false;
isMenu = true;
pause = false;
Player.y= 75;
Player.x = 175
Platforms = [];
var Score = 1;
testing = true;
pressingLeft = false;
pressingRight = false;
var moveR = 2;
var moveL = 2;
}
function Init() {
requestAnimationFrame(startDrawing);
canvas.addEventListener("click", function(evt) {
var rect = canvas.getBoundingClientRect();
var mouseX = evt.clientX - rect.left;
var mouseY = evt.clientY - rect.top;
if (isMenu && !isPlaying) {
if (isInside(mouseX, mouseY, 115, 230, 220, 270)) {
isPlaying = true;
isMenu = false;
} else if (isInside(mouseX, mouseY, 35, 320, 300, 345)) {
console.log("Leaderboard");
} else if (isInside(mouseX, mouseY, 75, 270, 380, 430)) {
console.log("Settings");
}
} else if (pause) {
if(isInside(mouseX, mouseY, 110, 270, 230, 260)) {
pause = false;
isPlaying = true;
} else if (isInside(mouseX, mouseY, 95, 270, 310, 345)) {
console.log('settings')
} else if (isInside(mouseX, mouseY, 140, 230, 390, 425)) {
console.log('quit')
restartGame();
}
}
});
window.addEventListener("keydown", function(evt) {
if (!isMenu && isPlaying || pause) {
if (evt.keyCode === 39) { // right
pressingRight = true;
} else if (evt.keyCode === 37) { // left
pressingLeft = true;
} else if (evt.keyCode === 80) {
pressingP = true;
pause = !pause;
if(!pause) {
isPlaying = true;
}
}
}
});
window.addEventListener("keyup", function(evt) {
if (!isMenu && isPlaying) {
if (evt.keyCode === 39) { // right
pressingRight = false;
} else if (evt.keyCode === 37) { // left
pressingLeft = false;
}
}
});
}
Init();
<html>
<head>
<title>Falldown</title>
</head>
<body>
<canvas id="canvas" width = "380" height= "640"></canvas>
<script src="beta.js"></script>
</body>
</html>
Here is a site, in it a canvas (airplane), which lags when scrolling, appear artifacts, and in different ways, depending on what you scroll - with the mouse wheel or scrollbar. If you comment out parallax or video at the beginning, nothing changes. During the scrolling of calls to the house does not happen. Lags either from behind the airplane script, or because of a clearRect. How can I optimize and get rid of artifacts? The code on the codepen (it works fine)
var scrolled;
var positionsArr = [];
var commonHeight = 0;
var canvas = document.querySelector('#canvas');
var canvasB = document.querySelector('#canvasback');
var ctx = canvas.getContext('2d');
var ctxB = canvasB.getContext('2d');
var centerX, centerY, radius, pointsOffset, radiusRatio, centerXRatio,
firstPoint, lastPoint, jet, blocksPosition, jetPositionY, jetTop, tabletOffset, headerHeight, canvasClearWidth;
var wWidth, mediaMobile, mediaTablet, mediaDesktop1, mediaDesktop2, mediaDesktop3;
jet = new Image();
jet.src = 'http://silencer.website/alkor/images/jet.png';
jet.onload = function () {
adaptive();
}
$(window).on('resize', function () {
adaptive();
});
function adaptive() {
mediaMobile = mediaTablet = mediaDesktop1 = mediaDesktop2 = mediaDesktop3 = false;
wWidth = $(window).width();
// Параметры для дуги по умолчанию
tabletOffset = 0;
radiusRatio = .95;
centerXRatio = 1.25;
// Параметры для дуги на разных разрешениях (перезаписывают параметры по умолчанию)
if (wWidth < 768) {
mediaMobile = true;
}
if (wWidth >= 768 && wWidth < 1024) {
mediaTablet = true;
tabletOffset = 120;
}
if (wWidth >= 1024 && wWidth < 1280) {
mediaDesktop1 = true;
tabletOffset = -40;
radiusRatio = 1.1;
centerXRatio = 1.03;
}
if (wWidth >= 1280 && wWidth < 1440) {
mediaDesktop2 = true;
tabletOffset = -20;
}
if (wWidth >= 1440) {
mediaDesktop3 = true;
tabletOffset = -20;
}
if (!mediaMobile) {
setTimeout(function () {
doCanvas();
}, 500);
} else {
ctx.clearRect(0, 0, canvas.width, canvas.height);
$(window).off('scroll', onScroll);
}
}
function doCanvas() {
$(window).on('scroll', onScroll);
var marginBottom = 120;
commonHeight = 0;
$('.history__item').each(function () {
commonHeight = commonHeight + $(this).height() + marginBottom;
});
commonHeight = commonHeight - marginBottom;
canvasWidth = $('.history').width() * .3;
canvasHeight = $('.history__blocks').height();
canvas.width = canvasWidth;
canvas.height = canvasHeight;
canvasB.width = canvas.width;
canvasB.height = canvas.height;
offsetLeft = $('.history__blocks')[0].offsetLeft;
$('#canvas, #canvasback').css('marginLeft', -offsetLeft);
radius = commonHeight * radiusRatio;
centerX = -commonHeight / centerXRatio + offsetLeft + tabletOffset;
centerY = commonHeight / 2;
pointsOffset = 100;
canvasClearWidth = centerX + radius + 110;
blocksPosition = $('.history__blocks')[0].offsetTop;
jetPositionY = $('.history')[0].offsetTop;
headerHeight = $('.history__title').height();
jetTop = $(window).height() / 2;
jetOnScroll = jetTop - headerHeight - jetPositionY;
positionsArr = [];
lastIndex = $('.history__item').length - 1;
darkened = $('.history__item');
for (var i = 0; i < $('.history__item').length; i++) {
var position = $('.history__item').eq(i)[0].offsetTop - blocksPosition + pointsOffset;
positionsArr.push(position);
if (i == 0) {
firstPoint = position;
}
if (i == $('.history__item').length - 1) {
lastPoint = position;
}
}
draw();
drawBackground();
setTimeout(function () {
if (mediaTablet) {
jetPositionLine(firstPoint);
} else {
jetPosition(firstPoint);
}
}, 100);
}
function drawBackground() {
if (mediaTablet) {
drawLine();
} else {
drawArc();
}
}
function draw(currentY) {
for (var i = 0; i < positionsArr.length; i++) {
addPoint(positionsArr[i], currentY, i);
}
}
function drawArc() {
var firstPointRad = Math.asin((centerY - firstPoint) / radius);
var lastPointRad = Math.asin((centerY - lastPoint) / radius);
ctxB.beginPath();
ctxB.lineWidth = 3;
ctxB.save();
ctxB.arc(centerX, centerY, radius, 1.5, lastPointRad, true);
ctxB.strokeStyle = '#99daf0';
ctxB.setLineDash([8, 5]);
ctxB.lineDashOffset = 1;
ctxB.globalCompositeOperation = 'destination-over';
ctxB.stroke();
ctxB.restore();
}
function drawLine() {
ctxB.beginPath();
ctxB.lineWidth = 3;
ctxB.save();
ctxB.lineTo(tabletOffset, firstPoint);
ctxB.lineTo(tabletOffset, lastPoint);
ctxB.strokeStyle = '#99daf0';
ctxB.setLineDash([8, 5]);
ctxB.lineDashOffset = 1;
ctxB.globalCompositeOperation = 'destination-over';
ctxB.stroke();
ctxB.restore();
}
function addPoint(y, currentY, i) {
if (mediaTablet) {
var currentX = tabletOffset;
} else {
var angle = Math.asin((centerY - y) / radius);
var currentX = centerX + radius * (Math.cos(angle));
}
ctx.beginPath();
ctx.arc(currentX, y, 8, 0, 2 * Math.PI, false);
ctx.lineWidth = 3;
ctx.fillStyle = '#00a3da';
ctx.globalCompositeOperation = 'source-over';
if (currentY + 10 >= y) {
ctx.strokeStyle = '#fff';
darkened.eq(i).removeClass('darkened');
} else {
ctx.strokeStyle = '#99daf0';
darkened.eq(i).addClass('darkened');
}
ctx.fill();
ctx.stroke();
}
function jetPosition(y) {
var angle = Math.asin((centerY - y) / radius);
var currentX = centerX + radius * (Math.cos(angle) - 1);
var firstPointRad = Math.asin((centerY - firstPoint) / radius);
// if (toUp) { // Самолетик вверх-вниз
var jetAngle = Math.acos((centerY - y) / radius);
// } else {
// var jetAngle = Math.acos((centerY - y) / radius) + Math.PI;
// }
ctx.beginPath();
ctx.arc(centerX, centerY, radius, -angle, -firstPointRad, true);
ctx.globalCompositeOperation = 'source-over';
ctx.lineWidth = 3;
ctx.strokeStyle = '#fff';
ctx.stroke();
draw(y);
ctx.save();
ctx.translate(currentX + radius, y)
ctx.rotate(jetAngle - 1.6);
ctx.globalCompositeOperation = 'source-over';
ctx.drawImage(jet, -106, -80, 212, 160);
ctx.restore();
}
function jetPositionLine(y) {
ctx.beginPath();
ctx.lineTo(tabletOffset, firstPoint);
ctx.lineTo(tabletOffset, y);
ctx.lineWidth = 3;
ctx.strokeStyle = '#fff';
ctx.stroke();
draw(y);
ctx.beginPath();
ctx.save();
ctx.globalCompositeOperation = 'source-over';
ctx.drawImage(jet, tabletOffset - 106, y - 80, 212, 160);
ctx.restore();
}
function onScroll() {
requestAnimationFrame(scrollCanvas);
};
function scrollCanvas() {
var prevScroll = scrolled;
scrolled = window.pageYOffset;
toUp = prevScroll < scrolled;
var positionY = scrolled + jetOnScroll;
if (positionY >= firstPoint) {
if (positionY <= lastPoint) {
ctx.clearRect(0, 0, canvasClearWidth, canvasHeight);
if (mediaTablet) {
jetPositionLine(positionY);
} else {
jetPosition(positionY);
}
} else {
$('.history__item').eq(lastIndex).removeClass('darkened');
}
}
if (!mediaMobile && !mediaTablet) {
parallaxScroll();
}
}
I want to move the balls in correct direction when bat collide with them, like in this example
It doesn't have to be this good though. Working correctly is the goal here.
So far, what I've got can be seen in the following url:
https://jsfiddle.net/qphqvntx/4/
The problem is with the collision, when bat hit the balls. It's behaving very weird.
//Canvas Variable
var mainCanvas = document.getElementById("mainCanvas");
var ctx = mainCanvas.getContext("2d");
var canvasHeight = mainCanvas.height;
var canvasWidth = mainCanvas.width;
var borderRadius = 10;
var bottomRadius = 120;
var gravity = 0.2;
var animate = false;
//Ball Object related variable
var balls = [];
var ballObj = {
x: 0,
y: 0,
velocity: {x: 0, y: 0},
};
var ball = '';
var debugBall = '';
var ballRadius = 10;
var dumping = 0.99;
var ballSpeed = 6;
var force = 1.8;
var setBallTimer = 150;
var updateBallTimer = 0;
var target;
var distanceX;
var distancey;
var j, balls2;
//Bat related variable
var batXPos = 200;
var batYPos = canvasHeight - bottomRadius - 120;
var batHeight = 100;
var batWidth = 10;
var mouse = [0, 0];
var point = [170, 175];
var dx, dy;
//run related variable
var oneRunLine = 60;
var twoRunLine = 90;
var fourRunLine = 100;
var outTopLine = 450;
var oneRunChain = canvasHeight - bottomRadius;
var twoRunChain = canvasHeight - bottomRadius - oneRunLine;
var fourRunChain = canvasHeight - bottomRadius - oneRunLine - twoRunLine;
var sixRunChain = canvasHeight - bottomRadius - oneRunLine - twoRunLine - fourRunLine;
var circleUnderMouse;
var mouse = {
x: 0,
y: 0,
down: false
}
var res;
var previousEvent = false;
function executeFrame() {
if (animate) {
requestAnimFrame(executeFrame);
}
ctx.lineWidth = "3";
ctx.strokeRect(0, 0, mainCanvas.width, mainCanvas.height);
ctx.strokeRect(0, 0, mainCanvas.width, mainCanvas.height - bottomRadius);
ctx.fillStyle = 'rgba(255,255,255,0.3)';
ctx.fillRect(0, 0, mainCanvas.width, mainCanvas.height);
update();
if (balls.length != '0') {
balls.forEach(function (ball, j, i) {
drawBall(ball);
createBat();
});
}
}
initializeGame();
function update() {
if (balls.length != '0') {
balls.forEach(function (ball, balli, ballj) {
ball.addGravity();
ball.velocity.y *= dumping;
ball.velocity.x *= dumping;
ball.y += ball.velocity.y;
ball.x += ball.velocity.x * force;
if (hitGround(ball) == true) {
ball.y = mainCanvas.height - bottomRadius;
ball.velocity.y = -Math.abs(ball.velocity.y);
}
if (hitLeft(ball) == true) {
ball.velocity.x = Math.abs(ball.velocity.x);
}
var hit = linePoint(point[0], point[1], mouse[0], mouse[1], ball.x, ball.y, ball);
if (hit == true) {
//console.log("hit");
} else {
//console.log("not yet");
}
for (j = balli + 1; j < balls.length; j++) {
balls2 = ballj[j];
var dx = balls2.x - ball.x;
var dy = balls2.y - ball.y;
var d = Math.sqrt(dx * dx + dy * dy);
if (d < 2 * ballRadius) {
if (d === 0) {
d = 0.1;
}
var unitX = dx / d;
var unitY = dy / d;
var newForce = -1;
var forceX = unitX * newForce;
var forceY = unitY * newForce;
ball.velocity.x += forceX;
ball.velocity.y += forceY;
balls2.velocity.x -= forceX;
balls2.velocity.y -= forceY;
}
}
});
}
updateBallTimer++;
if (updateBallTimer >= setBallTimer) {
createBall();
updateBallTimer = 0;
}
}
function initializeGame() {
createBall();
createBat();
}
function createBall() {
randomPoint(50, 150);
ball = instantiateBall(canvasWidth, target.y, ballObj);
ball.velocity.x -= getRandomNumber(4, 6);
}
function instantiateBall(xPos, yPos, ball) {
ball = {
x: xPos,
y: yPos,
velocity: {x: 0, y: 0},
addGravity: function () {
return this.velocity.y += gravity;
},
onCanvas: false
};
balls.push(ball);
drawBall(ball);
return ball;
}
function drawBall(ball) {
if (ball != '') {
ctx.beginPath();
ctx.arc(ball.x, ball.y, ballRadius, 0, 2 * Math.PI, false);
ctx.fillStyle = "#000";
ctx.fill();
}
}
function createBat() {
// ctx.clearRect(0, 0, width, height)
dx = mouse[0] - point[0],
dy = mouse[1] - point[1];
rot = Math.atan2(dy, dx);
ctx.fillStyle = 'red';
ctx.fillRect(point[0], point[1], 10, 10);
ctx.fillStyle = 'gray';
ctx.save();
ctx.translate(point[0], point[1]);
ctx.rotate(rot);
ctx.fillRect(0, 0, batHeight, batWidth);
ctx.moveTo(point[0], point[1]);
ctx.lineTo(point[0] + (mouse[0] - point[0]) + 0.5, point[1] + (mouse[1] - point[1]) * 0.5);
//ctx.stroke();
ctx.restore();
}
function linePoint(x1, y1, x2, y2, px, py, ball) {
var d1 = dist(px, py, x1, y1);
var d2 = dist(px, py, x2, y2);
var lineLen = dist(x1, y1, x2, y2);
var buffer = 3;
var batAngle = Math.atan2(d2, d1);
var batAngleX = Math.sin(batAngle);
var batAngleY = -Math.cos(batAngle);
if (d1 + d2 >= lineLen - buffer && d1 + d2 <= lineLen + buffer) {
var d = 2 * (ball.velocity.x * batAngleX + ball.velocity.y * batAngleY);
ball.x -= d * batAngleX;
ball.x -= d * batAngleY;
ball.velocity.x -= d * batAngleX + res;
ball.velocity.y -= d * batAngleY + res;
return true;
}
return false;
}
function dist(x1, y1, x2, y2) {
var xs = x2 - x1,
ys = y2 - y1;
xs *= xs;
ys *= ys;
return Math.sqrt(xs + ys);
}
function getRandomNumber(min, max) {
return Math.random() * (max - min) + min;
}
function randomPoint(min, max) {
var rndNum = Math.random() * (max - min) + min;
target = {
x: canvasWidth,
y: rndNum
};
// ctx.beginPath();
// ctx.arc(rndNum, canvasHeight, ballRadius, 0, 2 * Math.PI, false);
// ctx.fillStyle = "#ff0";
// ctx.fill();
}
function isOnCanvas(obj) {
if (obj.x <= mainCanvas.width && obj.y <= mainCanvas.height - bottomRadius) {
return true;
}
return false;
}
function hitGround(obj) {
if (obj.y >= mainCanvas.height - bottomRadius) {
//console.log("hit the ground");
return true;
}
return false;
}
function hitTop(obj) {
if (obj.y <= borderRadius) {
//console.log("hit the top");
return true;
}
return false;
}
function hitLeft(obj) {
if (obj.x <= borderRadius) {
//console.log("hit the left");
return true;
}
return false;
}
function hitRight(obj) {
if (obj.x >= mainCanvas.width - borderRadius) {
//console.log("hit the left");
return true;
}
return false;
}
function drawLineRandomPoint(moveX, moveY, lineX, lineY, strColor) {
ctx.beginPath();
ctx.moveTo(moveX, moveY);
ctx.lineTo(lineX, lineY);
ctx.strokeStyle = strColor;
ctx.stroke();
}
mainCanvas.addEventListener('mousemove', function (e) {
e.time = Date.now();
res = makeVelocityCalculator(e, previousEvent);
previousEvent = e;
mouse[0] = e.clientX;
mouse[1] = e.clientY;
});
function makeVelocityCalculator(e_init, e) {
var x = e_init.clientX, new_x, new_y, new_t,
x_dist, y_dist, interval, velocity,
y = e_init.clientY,
t;
if (e === false) {
return 0;
}
t = e.time;
new_x = e.clientX;
new_y = e.clientY;
new_t = Date.now();
x_dist = new_x - x;
y_dist = new_y - y;
interval = new_t - t;
// update values:
x = new_x;
y = new_y;
velocity = Math.sqrt(x_dist * x_dist + y_dist * y_dist) / interval;
return velocity;
}
mainCanvas.addEventListener('mouseover', function (e) {
animate = true;
executeFrame();
});
mainCanvas.addEventListener("mouseout", function (e) {
animate = false;
});
executeFrame();
window.requestAnimFrame = (function () {
return window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
function (callback) {
window.setTimeout(callback, 1000 / 60);
};
})();
<body>
<canvas id="mainCanvas" height="400" width="600"></canvas>
<script src="main.js" type="text/javascript"></script>
</body>
I work with this code for show HTML5 canvas animated in over my div:
HTML:
<div class="ls-slide" id="asb">
<div id="smile" style="width:100%;height:359px;">
<canvas style="position: absolute; width: 100%; z-index: 3; display: block;" height="359" width="2111">
</canvas>
</div>
</div>
JS:
window.onload = function() {
travers();
var lastHeight = $("#asb").height();
var canvas = document.querySelector('canvas');
ctx = canvas.getContext('2d');
color = '#aaa';
var check = respondCanvas();
canvas.width = check[1];
canvas.height = lastHeight;
canvas.style.display = 'block';
ctx.fillStyle = color;
ctx.lineWidth = .1;
ctx.strokeStyle = color;
function respondCanvas() {
var width = [];
width[0] = $('#smile').width(); //max width
width[1] = $('canvas').width(); //max width
return width;
//Call a function to redraw other content (texts, images etc)
}
function checkheight() {
var height = $('#asb').height(); //max width
//console.log(height);
// return height;
}
var mousePosition = {
x: 30 * canvas.width / 100,
y: 30 * canvas.height / 100
};
if (canvas.width <= 1000) {
var numdot = 100;
} else if (canvas.width <= 800) {
var numdot = 80;
} else if (canvas.width <= 500) {
var numdot = 35;
} else {
var numdot = 300;
}
var dots = {
nb: numdot,
distance: 70,
d_radius: 50,
array: []
};
function Dot() {
this.x = Math.random() * canvas.width;
this.y = Math.random() * canvas.height;
this.vx = -.5 + Math.random();
this.vy = -.5 + Math.random();
this.radius = Math.random();
}
Dot.prototype = {
create: function() {
ctx.beginPath();
ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2, false);
ctx.fill();
},
animate: function() {
for (i = 0; i < dots.nb; i++) {
var dot = dots.array[i];
if (dot.y < 0 || dot.y > canvas.height) {
dot.vx = dot.vx;
dot.vy = -dot.vy;
} else if (dot.x < 0 || dot.x > canvas.width) {
dot.vx = -dot.vx;
dot.vy = dot.vy;
}
dot.x += dot.vx;
dot.y += dot.vy;
}
},
line: function() {
for (i = 0; i < dots.nb; i++) {
for (j = 0; j < dots.nb; j++) {
i_dot = dots.array[i];
j_dot = dots.array[j];
if ((i_dot.x - j_dot.x) < dots.distance && (i_dot.y - j_dot.y) < dots.distance && (i_dot.x - j_dot.x) > -dots.distance && (i_dot.y - j_dot.y) > -dots.distance) {
if ((i_dot.x - mousePosition.x) < dots.d_radius && (i_dot.y - mousePosition.y) < dots.d_radius && (i_dot.x - mousePosition.x) > -dots.d_radius && (i_dot.y - mousePosition.y) > -dots.d_radius) {
ctx.beginPath();
ctx.moveTo(i_dot.x, i_dot.y);
ctx.lineTo(j_dot.x, j_dot.y);
ctx.stroke();
ctx.closePath();
}
}
}
}
}
};
function createDots() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
for (i = 0; i < dots.nb; i++) {
dots.array.push(new Dot());
dot = dots.array[i];
dot.create();
}
dot.line();
dot.animate();
}
$("canvas").mousemove(function(parameter) {
mousePosition.x = parameter.pageX - 0;
mousePosition.y = parameter.pageY - 300;
});
setInterval(createDots, 1000 / 30);
};
But, In action not work and I can't see dotted animation(I checked in chrome,ff). How do fix this?!
demo : https://jsfiddle.net/5pzvh8ko/
You can try it better by giving an ID to you canvas tag, and then use "document.getElementById()", to access your canvas tag, i think it is a better method and even simpler.here is an example:
canvas tag with id:
<canvas ID="canvas_id" style="position: absolute; width: 100%; z-index:3; display: block;" height="359" width="2111">
then use JavaScript to access it this way:
var canvas = document.getElementById("canvas_id");
This might not be all you need but you can at least try it that way.