I'm new in programming things, So I wanted to start good projects with a snake game with canvas, Now I make one but it does not work well. I have a snake but I have a problem while adding it to the head.
ctx.fillStyle = "white";
drwhd.fillStyle ="blue";
for (var i = 0; i < snakeTrail.length; i++) {
ctx.fillRect(
snakeTrail[i].x * tileSize,
snakeTrail[i].y * tileSize,
tileSize,
tileSize
);
}
drwhd.fillRect(
snakeHead[k].x * tileSize,
snakeHead[k].y * tileSize,
tileSize,
tileSize
);
I tried these codes for the head . There is not an error but it should draw body with white and head with a blue. It draws all blue. I hope someone can fix this.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Snake</title>
</head>
<body>
<canvas id="canvas" width="400" height="400"></canvas>
<div id="score"></div>
<div id="highscore"></div>
<script>
var score = 0;
var highScore = 1;
var gridSize = (tileSize = 20); // 20 x 20 = 400
var nextX = (nextY = 0);
//var jj = "https://i.hizliresim.com/p24p2r.png";
// TISSS YILAAAN
var defaultTailSize = 3;
var tailSize = defaultTailSize;
var snakeTrail = [];
var snakeHead = [];
var snakeX = (snakeY = 10);
// Amasya Elması
var appleX = (appleY = 15);
// Ekrana Çiz
function draw() {
// Yılanı sonraki pos'a (pozisyona) ilerlet - move snake to next pos
snakeX += nextX;
snakeY += nextY;
// Yılan Oyun Alanının Dışına Çıkarsa - Snake go to out of canvas
if (snakeX < 0) {
snakeX = gridSize - 1;
}
if (snakeX > gridSize - 1) {
snakeX = 0;
}
if (snakeY < 0) {
snakeY = gridSize - 1;
}
if (snakeY > gridSize - 1) {
snakeY = 0;
}
//Yılan Elmayı Yakalarsa - Snake Eats The Apple
if (snakeX == appleX && snakeY == appleY) {
tailSize++;
score++;
appleX = Math.floor(Math.random() * gridSize);
appleY = Math.floor(Math.random() * gridSize);
}
//Background
ctx.fillStyle = "black";
ctx.fillRect(0, 0, canvas.width, canvas.height);
// Draw Snake
ctx.fillStyle = "white";
drwhd.fillStyle = "blue";
for (var i = 0; i < snakeTrail.length; i++) {
ctx.fillRect(
snakeTrail[i].x * tileSize,
snakeTrail[i].y * tileSize,
tileSize,
tileSize
);
drwhd.fillRect(
snakeHead[0].x * tileSize,
snakeHead[0].y * tileSize,
tileSize,
tileSize
);
//Yılan Kendine Çarparsa - Snake Hit Himself
if (snakeTrail[i].x == snakeX && snakeTrail[i].y == snakeY) {
tailSize = defaultTailSize;
score = 0;
}
if (highScore < score) {
highScore = score;
}
}
// Amasya Elmasını Boya :D - Paint Apple
ctx.fillStyle = "red";
ctx.fillRect(appleX * tileSize, appleY * tileSize, tileSize, tileSize);
//set snake trail
snakeTrail.push({
x: snakeX,
y: snakeY
});
snakeHead.push({
x: snakeX,
y: snakeY
});
while (snakeTrail.length > tailSize) {
snakeTrail.shift();
snakeHead.shift();
}
//PUANI YAZDIR
ctx.fillStyle = "white";
ctx.fillText("Skor : " + score, 25, 25);
ctx.fillText("En Yüksek :" + highScore, 25, 45);
}
// tuşlar
function keyDownEvent(e) {
if (e.keyCode == 87 && nextY != 1) {
nextX = 0;
nextY = -1;
}
if (e.keyCode == 83 && nextY != -1) {
nextX = 0;
nextY = 1;
}
if (e.keyCode == 68 && nextX != -1) {
nextX = 1;
nextY = 0;
}
if (e.keyCode == 65 && nextX != 1) {
nextX = -1;
nextY = 0;
}
}
var canvas, ctx;
canvas = document.getElementById("canvas");
ctx = canvas.getContext("2d");
drwhd = canvas.getContext("2d");
document.addEventListener("keydown", keyDownEvent);
// her saniye X'i renderla
var x = 8;
setInterval(draw, 1000 / x);
</script>
</body>
</html>
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 making a simple brick breaker game using Java Script, and my console is showing me error while displaying blocks on to the canvas, they are being drawn onto the canvas but all the other objects are not working and console is showing
index.js:173 Uncaught TypeError: Cannot read property 'show' of undefined
at update (index.js:173)
at index.js:177
if you comment out from line no:172 and 173, which is a for loop that tells the canvas to draw them on it
everything's is working fine.
one more thing: that canvasRendering...rundedRectangle is a function that draws rounded edge rectangles
someone please find a solution!
CanvasRenderingContext2D.prototype.roundedRectangle = function(x, y, width, height, rounded) {
const radiansInCircle = 2 * Math.PI
const halfRadians = (2 * Math.PI)/2
const quarterRadians = (2 * Math.PI)/4
// top left arc
this.arc(rounded + x, rounded + y, rounded, -quarterRadians, halfRadians, true)
// line from top left to bottom left
this.lineTo(x, y + height - rounded)
// bottom left arc
this.arc(rounded + x, height - rounded + y, rounded, halfRadians, quarterRadians, true)
// line from bottom left to bottom right
this.lineTo(x + width - rounded, y + height)
// bottom right arc
this.arc(x + width - rounded, y + height - rounded, rounded, quarterRadians, 0, true)
// line from bottom right to top right
this.lineTo(x + width, y + rounded)
// top right arc
this.arc(x + width - rounded, y + rounded, rounded, 0, -quarterRadians, true)
// line from top right to top left
this.lineTo(x + rounded, y)
}
var canvas= document.getElementById("gameCanvas");
var ctx = canvas.getContext("2d");
function Player(x,y,w,h){
this.x = x;
this.y = y;
this.w = w;
this.h = h;
this.show = function(){
ctx.beginPath();
ctx.rect(this.x, this.y, this.w, this.h);
ctx.fillStyle = "#ffff";
ctx.fill();
ctx.closePath();
}
this.move = function(speed){
this.x += speed;
}
}
function Ball(x,y,r){
this.x = x;
this.y = y;
this.r = r;
this.show = function(){
ctx.beginPath();
ctx.arc(this.x,this.y,this.r,0,2* Math.PI);
ctx.fillStyle = "tomato";
ctx.fill();
ctx.closePath();
}
this.move= function(speedX,speedY){
this.show();
this.speed = 2;
this.x += speedX;
this.y += speedY;
}
}
function Block(x,y,w,h){
this.x = x;
this.y = y;
this.w = w;
this.h = h;
this.show= function(color){
ctx.beginPath();
ctx.roundedRectangle(this.x,this.y,this.w,this.h,7);
ctx.fillStyle = color;
ctx.fill();
ctx.closePath();
};
};
var player = new Player(canvas.width/2-50,canvas.height*0.95,100,20);
var ball = new Ball(canvas.width/2-5, player.y-20,15);
var rigthPressed = false;
var leftPressed = false;
var blocks = [];
var rowCount = 5;
var columnCount = 6;
var noInRow = 6;
var blockCount = (rowCount*columnCount)+1;
var blockRow = 0;
var blockCol = 0;
var ballSpeedX = 5;
var ballSpeedY = -10;
for(let i = 1; i < blockCount; i++){
blocks.push(new Block(blockCol*60+25,blockRow*60+30,50,50));
blockCol++;
if(i % noInRow == 0){
blockRow++;
blockCol = 0;
}
}
window.addEventListener("keydown", function(e){
if(e.keyCode == 39){
rigthPressed = true;
}
if(e.keyCode == 37){
leftPressed = true;
}
});
window.addEventListener("keyup", function(e){
if(e.keyCode == 39){
rigthPressed = false;
}
if(e.keyCode == 37){
leftPressed = false;
}
});
function objMovement(){
if(rigthPressed){
player.move(5);
if (player.x > canvas.width-player.w){
player.x = canvas.width-player.w;
}
}
if(leftPressed){
player.move(-5);
if(player.x < 0){
player.x = 0;
}
}
if(ball.x > canvas.width-ball.r || ball.x < 0+ball.r){
ballSpeedX = -ballSpeedX;
}
if (ball.y > canvas.height-ball.r || ball.y < 0+ball.r){
ballSpeedY = -ballSpeedY;
}
if(ball.x<player.x+player.w &&ball.x>player.x && ball.y>player.y){
ballSpeedY = -ballSpeedY;
ballSpeedX= ballSpeedX;
}
function Bump(){
if (ball.x>player.x && ball.x<player.x+player.w/2){
if (ball.y >= player.y){
ballSpeedX = -5;
}
}
if(ball.x>player.x+player.w/2 && ball.x<player.x+player.w){
if(ball.y >= player.y){
ballSpeedX = 5;
}
}
}
//Bump();
}
function update(){
ctx.clearRect(0,0,canvas.width,canvas.height);
ball.show();
ball.move(ballSpeedX,ballSpeedY);
player.show();
objMovement();
for(let i=0;i<blockCount;i++){
blocks[i].show("violet");
}
window.requestAnimationFrame(update);
}
update();
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>🌝🩲🩲🌝</title>
<style>
#body{
background-color: rgb(31, 30, 30);
}
#gameCanvas{
border: 15px solid rgb(44, 44, 44);
border-radius: 20px;
background-color:rgb(19, 18, 18);
margin: 250px;
}
</style>
</head>
<body id="body">
<canvas id="gameCanvas" width=400 height=800></canvas>
<script type="text/javascript" src="./index.js"></script>
</body>
</html>
When you create blocks you start from 1
for (let i = 1; i < blockCount; i++) {
blocks.push(new Block(blockCol * 60 + 25, blockRow * 60 + 30, 50, 50));
...
so when you update you need to consider that
function update() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ball.show();
ball.move(ballSpeedX, ballSpeedY);
player.show();
objMovement();
for (let i = 0; i < blockCount -1; i++) { // or for (let i = 0; i < blocks.length; i++) {
blocks[i].show("violet");
}
window.requestAnimationFrame(update);
}
I'm trying to get my head around using javascript in the html < canvas >, and I started with the MDN Breakout game tutorial. Here is how the complete game looks like. I'm stuck with one of the exercises and I really could not find any solution to my issue after an hour of googling!! :((. The following code generates a ball on the canvas.
ctx.beginPath();
ctx.arc(x, y, radius, 0, Math.PI * 2);
ctx.fillStyle = '#FFFFF';
ctx.fill();
ctx.closePath();
I needed the ball to change its colour after it collides with one of the bricks. In order to achieve that, I created a variable to store the colour value: let colour = '#FFFFF';, and later in a function which detects collisions, changed the value of this variable. It worked fine, however, whenever the ball changed its colour, so did the bricks and the paddle. As I tried to fix this, I found out that whenever I manually change the colour of either a ball, a brick or a paddle (all of which are set in different functions), all of the objects change the colour as well.
This is very strange, because if in an emply .js file I make just two shapes and colour them differently it works fine:
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
ctx.beginPath();
ctx.rect(0, 0, 20, 40);
ctx.fillStyle = 'cyan';
ctx.fill();
ctx.closePath();
ctx.beginPath();
ctx.arc(50, 50, 20, 0, Math.PI*2);
ctx.fillStyle = 'black';
ctx.fill();
ctx.closePath();
But with all the game code I have right now, I can not assign different colour to different objects, they all change colour instead! I have no idea how to fix this and change just the colour of the ball! Anyone knows what might be causing the issue? Please help, thank you so much in advance 🙏
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
//Ball variables
const radius = 10;
let colour = '#FFFFF';
let x = canvas.width / 2;
let y = canvas.height - 30;
let dx = 2;
let dy = -2;
//Paddle
const paddleHeight = 10;
let paddleWidth = 100;
let paddleX = (canvas.width - paddleWidth) / 2;
//Paddle movement
var rightPressed = false;
var leftPressed = false;
//Bricks
var brickRowCount = 3;
var brickColumnCount = 5;
var brickWidth = 75;
var brickHeight = 20;
var brickPadding = 10;
var brickOffsetTop = 30;
var brickOffsetLeft = 30;
var bricks = [];
for (var c = 0; c < brickColumnCount; c++) {
bricks[c] = [];
for (var r = 0; r < brickRowCount; r++) {
bricks[c][r] = {
x: 0,
y: 0,
status: 1
};;
}
}
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
drawBall();
drawPaddle();
drawBricks();
collisionDetection();
x += dx;
y += dy;
if (rightPressed && paddleX < canvas.width - paddleWidth) {
paddleX += 7;
} else if (leftPressed && paddleX > 0) {
paddleX -= 7;
}
}
function drawBall() {
ctx.beginPath();
ctx.arc(x, y, radius, 0, Math.PI * 2);
ctx.fillStyle = colour;
ctx.fill();
ctx.closePath();
//Bounce off the walls
if (x + dx > canvas.width - radius || x + dx < radius) {
dx = -dx;
}
if (y + dy < radius) {
dy = -dy;
} else if (y + dy > canvas.height - radius) {
//Collision detection (ball + paddle)
if (x > paddleX && x < paddleX + paddleWidth) {
dy = -dy;
} else {
//alert("GAME OVER");
document.location.reload();
}
}
}
function drawPaddle() {
ctx.beginPath();
ctx.rect(paddleX, canvas.height - paddleHeight, paddleWidth, paddleHeight);
ctx.fillStyle = '#FFFFF';
ctx.fill();
ctx.closePath();
}
function drawBricks() {
for (var c = 0; c < brickColumnCount; c++) {
for (var r = 0; r < brickRowCount; r++) {
if (bricks[c][r].status == 1) {
var brickX = (c * (brickWidth + brickPadding)) + brickOffsetLeft;
var brickY = (r * (brickHeight + brickPadding)) + brickOffsetTop;
bricks[c][r].x = brickX;
bricks[c][r].y = brickY;
ctx.beginPath();
ctx.rect(brickX, brickY, brickWidth, brickHeight);
ctx.fillStyle = "#FFFFF";
ctx.fill();
ctx.closePath();
}
}
}
}
document.addEventListener("keydown", keyDownHandler, false);
document.addEventListener("keyup", keyUpHandler, false);
function keyDownHandler(e) {
if (e.key == "Right" || e.key == "ArrowRight") {
rightPressed = true;
} else if (e.key == "Left" || e.key == "ArrowLeft") {
leftPressed = true;
}
}
function keyUpHandler(e) {
if (e.key == "Right" || e.key == "ArrowRight") {
rightPressed = false;
} else if (e.key == "Left" || e.key == "ArrowLeft") {
leftPressed = false;
}
}
function collisionDetection() {
for (var c = 0; c < brickColumnCount; c++) {
for (var r = 0; r < brickRowCount; r++) {
var b = bricks[c][r];
if (b.status == 1) {
if (x > b.x && x < b.x + brickWidth && y > b.y && y < b.y + brickHeight) {
dy = -dy;
b.status = 0;
colour = '#ff9ecb';
}
}
}
}
}
var interval = setInterval(draw, 10);
<!DOCTYPE html>
<html>
<head>
<title>Breakout Game</title>
</head>
<body>
<canvas id='canvas' height='320' width='480'></canvas>
<script src="app.js"></script>
</body>
</html>
Looks like a minor error with the colour hex codes you're using for your fillStyle, which are invalid. See the corrections in the snippet below from:
let colour = '#FFFFF'; // Six characters invalid
To:
let colour = '#FF0000'; // Seven characters valid
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
//Ball variables
const radius = 10;
// Fix colour
let colour = '#FF0000';
let x = canvas.width / 2;
let y = canvas.height - 30;
let dx = 2;
let dy = -2;
//Paddle
const paddleHeight = 10;
let paddleWidth = 100;
let paddleX = (canvas.width - paddleWidth) / 2;
//Paddle movement
var rightPressed = false;
var leftPressed = false;
//Bricks
var brickRowCount = 3;
var brickColumnCount = 5;
var brickWidth = 75;
var brickHeight = 20;
var brickPadding = 10;
var brickOffsetTop = 30;
var brickOffsetLeft = 30;
var bricks = [];
for (var c = 0; c < brickColumnCount; c++) {
bricks[c] = [];
for (var r = 0; r < brickRowCount; r++) {
bricks[c][r] = {
x: 0,
y: 0,
status: 1
};;
}
}
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
drawBall();
drawPaddle();
drawBricks();
collisionDetection();
x += dx;
y += dy;
if (rightPressed && paddleX < canvas.width - paddleWidth) {
paddleX += 7;
} else if (leftPressed && paddleX > 0) {
paddleX -= 7;
}
}
function drawBall() {
// Update to valid colour
ctx.fillStyle = colour;
ctx.beginPath();
ctx.arc(x, y, radius, 0, Math.PI * 2);
ctx.fill();
ctx.closePath();
//Bounce off the walls
if (x + dx > canvas.width - radius || x + dx < radius) {
dx = -dx;
}
if (y + dy < radius) {
dy = -dy;
} else if (y + dy > canvas.height - radius) {
//Collision detection (ball + paddle)
if (x > paddleX && x < paddleX + paddleWidth) {
dy = -dy;
} else {
//alert("GAME OVER");
document.location.reload();
}
}
}
function drawPaddle() {
// Update to valid colour
ctx.fillStyle = '#00FF00';
// Consider using fillRect
ctx.fillRect(paddleX, canvas.height - paddleHeight, paddleWidth, paddleHeight);
}
function drawBricks() {
for (var c = 0; c < brickColumnCount; c++) {
for (var r = 0; r < brickRowCount; r++) {
if (bricks[c][r].status == 1) {
var brickX = (c * (brickWidth + brickPadding)) + brickOffsetLeft;
var brickY = (r * (brickHeight + brickPadding)) + brickOffsetTop;
bricks[c][r].x = brickX;
bricks[c][r].y = brickY;
// Update to valid colour
ctx.fillStyle = "#FFFFaa";
// Consider using fillRect
ctx.fillRect(brickX, brickY, brickWidth, brickHeight);
}
}
}
}
document.addEventListener("keydown", keyDownHandler, false);
document.addEventListener("keyup", keyUpHandler, false);
function keyDownHandler(e) {
if (e.key == "Right" || e.key == "ArrowRight") {
rightPressed = true;
} else if (e.key == "Left" || e.key == "ArrowLeft") {
leftPressed = true;
}
}
function keyUpHandler(e) {
if (e.key == "Right" || e.key == "ArrowRight") {
rightPressed = false;
} else if (e.key == "Left" || e.key == "ArrowLeft") {
leftPressed = false;
}
}
function collisionDetection() {
for (var c = 0; c < brickColumnCount; c++) {
for (var r = 0; r < brickRowCount; r++) {
var b = bricks[c][r];
if (b.status == 1) {
if (x > b.x && x < b.x + brickWidth && y > b.y && y < b.y + brickHeight) {
dy = -dy;
b.status = 0;
colour = '#ff9ecb';
}
}
}
}
}
var interval = setInterval(draw, 10);
<!DOCTYPE html>
<html>
<head>
<title>Breakout Game</title>
</head>
<body>
<canvas id='canvas' height='320' width='480'></canvas>
<script src="app.js"></script>
</body>
</html>
Also, consider using fillRect() as shown above, for a slightly simpler implementation. Hope that helps!
I would like to know how the "moving effect" it's made in this site:
http://www.perturbator.com/
I mean the pink lines, not the logo ()wichi is a simple parallax).
EDIT (I can't answer myself in 8 hours):
The code it's in the base.js file. It drawns the dots and then the lines.
$(function(){
var header = $('.site-header'),
canvas = $('<canvas></canvas>').appendTo(header)[0],
ctx = canvas.getContext('2d'),
color = '#fc335c',
idle = null, mousePosition;
canvas.width = window.innerWidth;
canvas.height = header.outerHeight();
canvas.style.display = 'block';
ctx.fillStyle = color;
ctx.lineWidth = .1;
ctx.strokeStyle = color;
var mousePosition = {
x: 30 * canvas.width,
y: 30 * canvas.height
},
dots = {
nb: 150,
distance: 90,
d_radius: 900,
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(var i = 0, dot=false; i < dots.nb; i++){
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(var i = 0; i < dots.nb; i++){
for(var 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(var i = 0; i < dots.nb; i++){
dots.array.push(new Dot());
dot = dots.array[i];
dot.create();
}
dot.line();
dot.animate();
}
idle = setInterval(createDots, 1000/30);
$(canvas).on('mousemove mouseleave', function(e){
if(e.type == 'mousemove'){
mousePosition.x = canvas.width / 2;
mousePosition.y = canvas.height / 2;
}
if(e.type == 'mouseleave'){
mousePosition.x = canvas.width / 2;
mousePosition.y = canvas.height / 2;
}
});
});
If you're talking about the pinkish background getting bigger and smaller, I believe it is done with a CSS3 animation http://www.w3schools.com/css/css3_animations.asp
You can see the details following the DOM chain:
<div id="home">
<div>...
<div>...
<div class="bg-layer">
If you were talking about the 3D "Perturbator", then I'd guess something related to 3Dtransforms in a JS script, but I can't tell much more...
<html>
<header>
<link href='css.css' rel='stylesheet'>
<meta charset="UTF-8">
<title> moving box </title>
<script type= 'text/javascript'>
var rectangle = {
x: 100,
y: 100,
width: 100,
height: 100,
};
var mx = 4;
var my = 4;
var cheight = 700;
var cwidth = 700;
var e = event.keyCode;
function checkmx() {
if (rectangle.x + 100 > cwidth){
mx = -4;
}
if (rectangle.x < 0){
mx = 4;
}
}
function checkmy() {
if (rectangle.y + 100 > cheight){
my = -4;
}
if (rectangle.y < 0){
my = 4;
}
}
function keydowncontrol(){
if (e == 37){
mx = -1;
my = 0;
}
if (e == 38){
mx = 0;
my = -1;
}
if (e == 39){
mx = 1;
my = 0;
}
if (e == 40){
mx = 0;
my = 1;
}
//if (e == 35){
//mx = 0
//mx = 0
//}
}
function draw() {
checkmx();
checkmy();
keydowncontrol();
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var nextx = rectangle.x + mx;
var nexty = rectangle.y + my;
rectangle.x = nextx
rectangle.y = nexty
ctx.clearRect(0, 0, cwidth, cheight);
ctx.beginPath();
ctx.rect(rectangle.x, rectangle.y, rectangle.width, rectangle.height);
ctx.fillStyle = '#FF0000';
ctx.fill();
ctx.stroke();
}
function init() {
checkmx();
checkmy();
window.onkeydown = keydowncontrol();// how can does this notice the key pressed
draw();
}
</script>
</header>
<body onload='setInterval(init,10)'>
<canvas id="canvas" width="700" height="700"></canvas>
</body>
</html>
I am trying to animate a box. I'm not sure how the window.onkeydown and event.keycode work. My goal is to have the mx and my variables change depending on the keys pressed. Should keydowncontrol() be in the draw() function or init() function?
Try this:
<html>
<head>
<link href='css.css' rel='stylesheet' />
<meta charset="UTF-8" />
<title>Moving box</title>
<script type='text/javascript'>
var rectangle = {
x: 100,
y: 100,
width: 100,
height: 100
};
var mx = 4;
var my = 4;
var cheight = 700;
var cwidth = 700;
var e = event.keyCode;
function checkmx() {
if (rectangle.x + 100 > cwidth) {
mx = -4;
}
if (rectangle.x < 0) {
mx = 4;
}
}
function checkmy() {
if (rectangle.y + 100 > cheight) {
my = -4;
}
if (rectangle.y < 0) {
my = 4;
}
}
function keydowncontrol(e) {
//alert(e);
if (e.keyCode == 37) {
mx = -1;
my = 0;
}
if (e.keyCode == 38) {
mx = 0;
my = -1;
}
if (e.keyCode == 39) {
mx = 1;
my = 0;
}
if (e.keyCode == 40) {
mx = 0;
my = 1;
}
//if (e == 35){
//mx = 0
//mx = 0
//}
}
function draw() {
checkmx();
checkmy();
//keydowncontrol();
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var nextx = rectangle.x + mx;
var nexty = rectangle.y + my;
rectangle.x = nextx
rectangle.y = nexty
ctx.clearRect(0, 0, cwidth, cheight);
ctx.beginPath();
ctx.rect(rectangle.x, rectangle.y, rectangle.width, rectangle.height);
ctx.fillStyle = '#FF0000';
ctx.fill();
ctx.stroke();
}
//document.attachEvent("onkeypress", keydowncontrol);
</script>
</head>
<body onload='setInterval(draw, 10)' onkeydown="keydowncontrol(event)">
<canvas id="canvas" width="700" height="700"></canvas>
</body>
</html>