Square on my canvas appears for a second and then disappears - javascript

This is a whole project so if there are constraints or variables not used, ignore them.
const WIDTH = 640;
const HEIGHT = 480;
const PLAYER_SIZE = 20;
const REPAINT_DELAY = 50;
const EASY_DELAY = 1750;
const MODERATE_DELAY = 1000;
const HARD_DELAY = 750;
const MAX_BLOCKS = 100;
var canvas;
var ctx;
var playerX = 310;
var playerY = 230;
var DX = 0;
var DY = 0;
window.onload = init;
function clearCanvas() {
ctx.clearRect(0, 0, WIDTH, HEIGHT);
}
function init() {
canvas = document.getElementById("myCanvas");
ctx = canvas.getContext("2d");
ctx.fillStyle = "#0000FF";
ctx.fillRect(playerX, playerY, PLAYER_SIZE, PLAYER_SIZE);
window.onkeydown = keyArrows;
return setInterval(draw, 10);
}
function draw() {
clearCanvas();
/*
** I think this is where something is going wrong.
** I tried moving around the `clearCanvas()` but that didn’t work.
** It just made the whole square not show up at all.
*/
if (playerX + DX > WIDTH || playerX + DX < 0)
DX = 0;
if (playerY + DY > HEIGHT || playerY + DY < 0)
DY = 0;
DX += playerX;
DY += playerY;
}
function keyArrows(e) {
if (e.keyCode == 37) {
DX = -5;
DY = 0;
} else if (e.keyCode == 38) {
DX = 0;
DY = -5;
} else if (e.keyCode == 39) {
DX = 5;
DY = 0;
} else if (e.keyCode == 40) {
DX = 0;
DY = 5;
}
}
init();
I’m trying to get the blue square to move. Would this code even work to make the square move around once it’s actually drawn?

Related

How can I reverse the direction of this square after it reaches a certain value?

I'm trying to create an idle animation where the red rectangle moves back and forth slightly in a loop. For some reason once it reaches the specified threshhold instead of proceeding to move in the opposite direction, it just stops.
What did I do wrong?
<canvas id="myCanvas" width="1500" height="500" style="border:1px solid #c3c3c3;">
Your browser does not support the canvas element.
</canvas>
<script>
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
// Spaceship structure
var shipWidth = 250;
var shipHeight = 100;
// Canvas parameters
var cWidth = canvas.width;
var cHeight = canvas.height;
// Positioning variables
var centerWidthPosition = (cWidth / 2) - (shipWidth / 2);
var centerHeightPosition = (cHeight / 2) - (shipHeight / 2);
var requestAnimationFrame = window.requestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.msRequestAnimationFrame;
function drawShip(){
ctx.clearRect(0, 0, cWidth, cHeight);
ctx.fillStyle = "#FF0000";
ctx.fillRect(centerWidthPosition,centerHeightPosition,shipWidth,shipHeight);
centerWidthPosition--;
if (centerWidthPosition < 400){
++centerWidthPosition;
}
requestAnimationFrame(drawShip);
}
drawShip();
</script>
#TheAmberlamps explained why it's doing that. Here I offer you a solution to achieve what I believe you are trying to do.
Use a velocity variable that changes magnitude. X position always increases by velocity value. Velocity changes directions at screen edges.
// use a velocity variable
var xspeed = 1;
// always increase by velocity
centerWidthPosition += xspeed;
// screen edges are 0 and 400 in this example
if (centerWidthPosition > 400 || centerWidthPosition < 0){
xspeed *= -1; // change velocity direction
}
I added another condition in your if that causes the object to bounce back and forth. Remove the selection after || if you don't want it doing that.
Your function is caught in a loop; once centerWidthPosition reaches 399 your conditional makes it increment back up to 400, and then it decrements back to 399.
here is another one as a brain teaser - how would go by making this animation bounce in the loop - basically turn text into particles and then reverse back to text and reverse back to particles and back to text and so on and on and on infinitely:
var random = Math.random;
window.onresize = function () {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
};
window.onresize();
var ctx = canvas.getContext('2d');
ctx.font = 'bold 50px "somefont"';
ctx.textBaseline = 'center';
ctx.fillStyle = 'rgba(255,255,255,1)';
var _particles = [];
var particlesLength = 0;
var currentText = "SOMETEXT";
var createParticle = function createParticle(x, y) {_particles.push(new Particle(x, y));};
var checkAlpha = function checkAlpha(pixels, i) {return pixels[i * 4 + 3] > 0;};
var createParticles = function createParticles() {
var textSize = ctx.measureText(currentText);
ctx.fillText(currentText,Math.round((canvas.width / 2) - (textSize.width / 2)),Math.round(canvas.height / 2));
var imageData = ctx.getImageData(1, 1, canvas.width, canvas.height);
var pixels = imageData.data;
var dataLength = imageData.width * imageData.height;
for (var i = 0; i < dataLength; i++) {
var currentRow = Math.floor(i / imageData.width);
var currentColumn = i - Math.floor(i / imageData.height);
if (currentRow % 2 || currentColumn % 2) continue;
if (checkAlpha(pixels, i)) {
var cy = ~~(i / imageData.width);
var cx = ~~(i - (cy * imageData.width));
createParticle(cx, cy);
}}
particlesLength = _particles.length;
};
var Point = function Point(x, y) {
this.set(x, y);
};
Point.prototype = {
set: function (x, y) {
x = x || 0;
y = y || x || 0;
this._sX = x;
this._sY = y;
this.reset();
},
add: function (point) {
this.x += point.x;
this.y += point.y;
},
multiply: function (point) {
this.x *= point.x;
this.y *= point.y;
},
reset: function () {
this.x = this._sX;
this.y = this._sY;
return this;
},
};
var FRICT = new Point(0.98);//set to 0 if no flying needed
var Particle = function Particle(x, y) {
this.startPos = new Point(x, y);
this.v = new Point();
this.a = new Point();
this.reset();
};
Particle.prototype = {
reset: function () {
this.x = this.startPos.x;
this.y = this.startPos.y;
this.life = Math.round(random() * 300);
this.isActive = true;
this.v.reset();
this.a.reset();
},
tick: function () {
if (!this.isActive) return;
this.physics();
this.checkLife();
this.draw();
return this.isActive;
},
checkLife: function () {
this.life -= 1;
this.isActive = !(this.life < 1);
},
draw: function () {
ctx.fillRect(this.x, this.y, 1, 1);
},
physics: function () {
if (performance.now()<nextTime) return;
this.a.x = (random() - 0.5) * 0.8;
this.a.y = (random() - 0.5) * 0.8;
this.v.add(this.a);
this.v.multiply(FRICT);
this.x += this.v.x;
this.y += this.v.y;
this.x = Math.round(this.x * 10) / 10;
this.y = Math.round(this.y * 10) / 10;
}
};
var nextTime = performance.now()+3000;
createParticles();
function clearCanvas() {
ctx.fillStyle = 'rgba(0,0,0,1)';
ctx.fillRect(0, 0, canvas.width, canvas.height);
}
(function clearLoop() {
clearCanvas();
requestAnimationFrame(clearLoop);
})();
(function animLoop(time) {
ctx.fillStyle = 'rgba(255,255,255,1)';
var isAlive = true;
for (var i = 0; i < particlesLength; i++) {
if (_particles[i].tick()) isAlive = true;
}
requestAnimationFrame(animLoop);
})();
function resetParticles() {
for (var i = 0; i < particlesLength; i++) {
_particles[i].reset();
}}

My HTML game is not running, what's wrong?

I wrote this game from a tutorial i read online, it was working just fine, until i messed it up, my developer tools console says theres a reference error but i just cant see it, please help, the error i get through my we developer console is "Uncaught ReferenceError: Draw is not defined(anonymous function) # games.html:228 "
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Gamedev Canvas Workshop</title>
<style>
* { padding: 0; margin: 0; }
canvas { background: #eee;
display: block;
margin: 0 auto;
}
#checking {
margin-left:650px;
}
#checking1 {
margin-left:650px;
}
#checking2 {
margin-left:650px;
}
#checking3 {
margin-left:650px;
}
</style>
</head>
<body>
<canvas id="myCanvas" width="480" height="320"></canvas>
<br/>
<div id ="checking">Current Position</div>
<div id ="checking1">Nothings Moving Bro</div>
<br/>
<div id ="checking3">Color State</div>
<div id ="checking2">Nope, still nothing</div>
<script>
// JavaScript code goes here
var checking1 = document.getElementById("checking1");
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
var x = canvas.width/2;
var y = canvas.height-30;
var ballRadius = 20;
var dx = 2;
var dy = -2;
var paddleheight = 10;
var paddlewidth = 50;
var paddleX = (canvas.height - paddlewidth)/2;
var RightKeyPressed = false;
var LeftKeyPressed = false;
document.addEventListener("keydown", keyDownHandler,false);
document.addEventListener("keyup",keyUpHandler,false);
function keyDownHandler(e){
if(e.keycode == 39){
RightKeyPressed = true;
}else if(e.keycode == 37){
LeftKeyPressed = true;
}
}
function keyUpHandler(e){
if(e.keycode == 39){
RightKeyPressed = false;
}else if(e.keycode == 37){
LeftKeyPressed = false;
}
function randomInt(min,max){
return Math.floor(Math.random() * (max - min))+ min; }
function paddle(){
ctx.beginPath;
ctx.rect(paddleX,canvas.height - paddleheight,paddlewidth,paddleheight);
ctx.fillStyle="#0095DD";
ctx.fill();
ctx.closePath;
}
function drawball(){
ctx.clearRect(0,0,canvas.width,canvas.height);
ctx.beginPath();
ctx.arc(x,y,ballRadius,0,Math.PI*2,false);
ctx.fillStyle = "rgb(0,149,221)";
ctx.fill();
ctx.closePath();
}
function Draw(){
ctx.clearRect(0,0,canvas.width,canvas.height);
drawball();
paddle();
if(y + dy > canvas.height - 20 || y + dy < ballRadius){
var cx = randomInt(0,255);
var cy = randomInt(0,255);
var cz = randomInt(0,255);
ctx.fillStyle = "rgb(cx,cy,cz)";
ctx.fill();
dy = -dy;
}
if ( x + dx > canvas.width - 20 || x + dx < ballRadius){
var cx = randomInt(0,255);
var cy = randomInt(0,255);
var cz = randomInt(0,255);
ctx.fillStyle = "rgb(cx,cy,cz)";
ctx.fill();
dx = -dx; }
x += dx;
y += dy
var color = ctx.fillStyle;
checking1.innerHTML = " x: " + x + "y: " + y ;
checking2.innerHTML = color ;
}
}
if(RightKeyPressed && paddleX < canvas.width - 50 ){
paddleX += 7;
}else if(LeftKeyPressed && paddleX > 0){
paddleX -= 7;
}
setInterval(Draw,10);
</script>
</body>
</html>
Your code throws the error because it cannot find the function Draw():
setInterval(Draw, 10);
This is because your function is not in the same scope. Your code structure is like this:
function keyUpHandler(e) {
...
function Draw(){
//Codes here
}
...
}
...
setInterval(Draw, 10);
Since the Draw() function is inside the keyUpHandler(e), it cannot be seen from any outside function (that is functions that are on a higher level/scope).
Hope this clears your mind :)
Check out this fiddle , you closing bracket of function keyDownHandlercode is wrong
var checking1 = document.getElementById("checking1");
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
var x = canvas.width / 2;
var y = canvas.height - 30;
var ballRadius = 20;
var dx = 2;
var dy = -2;
var paddleheight = 10;
var paddlewidth = 50;
var paddleX = (canvas.height - paddlewidth) / 2;
var RightKeyPressed = false;
var LeftKeyPressed = false;
document.addEventListener("keydown", keyDownHandler, false);
document.addEventListener("keyup", keyUpHandler, false);
function keyDownHandler(e) {
if (e.keycode == 39) {
RightKeyPressed = true;
} else if (e.keycode == 37) {
LeftKeyPressed = true;
}
}
function keyUpHandler(e) {
if (e.keycode == 39) {
RightKeyPressed = false;
} else if (e.keycode == 37) {
LeftKeyPressed = false;
}
}
function randomInt(min, max) {
return Math.floor(Math.random() * (max - min)) + min;
}
function paddle() {
ctx.beginPath;
ctx.rect(paddleX, canvas.height - paddleheight, paddlewidth, paddleheight);
ctx.fillStyle = "#0095DD";
ctx.fill();
ctx.closePath;
}
function drawball() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.beginPath();
ctx.arc(x, y, ballRadius, 0, Math.PI * 2, false);
ctx.fillStyle = "rgb(0,149,221)";
ctx.fill();
ctx.closePath();
}
function zan(){
alert('test');
}
function Draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
drawball();
paddle();
if (y + dy > canvas.height - 20 || y + dy < ballRadius) {
var cx = randomInt(0, 255);
var cy = randomInt(0, 255);
var cz = randomInt(0, 255);
ctx.fillStyle = "rgb(cx,cy,cz)";
ctx.fill();
dy = -dy;
}
if (x + dx > canvas.width - 20 || x + dx < ballRadius) {
var cx = randomInt(0, 255);
var cy = randomInt(0, 255);
var cz = randomInt(0, 255);
ctx.fillStyle = "rgb(cx,cy,cz)";
ctx.fill();
dx = -dx;
}
x += dx;
y += dy
var color = ctx.fillStyle;
checking1.innerHTML = " x: " + x + "y: " + y;
checking2.innerHTML = color;
}
if (RightKeyPressed && paddleX < canvas.width - 50) {
paddleX += 7;
} else if (LeftKeyPressed && paddleX > 0) {
paddleX -= 7;
}
setInterval(Draw, 10);
You probably forgot to close your keyuphandler function (currently you have like 3 function inside it until you finally close it at line 193).
add a function closure at about line 88 to close your keyuphandler.
Than you have a extra function closure at line 193 remove that and it works
(by function closure i mean brackets {} )

Canvas Asteroids game

I'm making Asteroids game in html5 with canvas. I've made moveable ship, which can rotate right and left and can move forward. I've added friction to slow it down when keys aren't pressed. Next thing to do is shooting bullets/lasers. I have yet only one shot and bullet goes forward, but it follow the movement of ship too :/ I don't know how to detach it from the ship and how to make more bullets.
Here's the code:
window.addEventListener('keydown',doKeyDown,true);
window.addEventListener('keyup',doKeyUp,true);
var canvas = document.getElementById('pageCanvas');
var context = canvas.getContext('2d');
var angle = 0;
var H = window.innerHeight; //*0.75,
var W = window.innerWidth; //*0.75;
canvas.width = W;
canvas.height = H;
var xc = W/2; //zeby bylo w centrum :v
var yc = H/2; //jw.
var x = xc;
var y = yc;
var dv = 0.2;
var dt = 1;
var vx = 0;
var vy = 0;
var fps = 30;
var maxVel = 10;
var frict = 0.99;
var brakes = 0.90;
var keys = new Array();
var fire = false;
var laser = false;
///////////////////lasery xD
var lx = 25,
ly = 9,
lw = 4,
lh = 4;
function doKeyUp(evt){
keys[evt.keyCode] = false;
fire = false;
}
function doKeyDown(evt){
keys[evt.keyCode] = true;
}
//OOOOOOOOOOOOOOOOOOLASEROOOOOOOOOOOOOOOOOOOOOOOOOOO
function drawLaser() {
context.fillStyle = "red";
context.fillRect(lx,ly,lw,lh);
}
function moveLaser() {
lx += 2;
}
//OOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO
function ogienZdupy(){
context.fillStyle = "red";
context.beginPath();
context.moveTo(-2,2);
context.lineTo(2,10);
context.lineTo(-2,18);
context.lineTo(-25,10);
context.lineTo(-2,2);
context.strokeStyle = "red";
context.stroke();
}
function convertToRadians(degree) {
return degree*(Math.PI/180);
}
function incrementAngle() {
angle += 5;
if(angle > 360){
angle = 0;
}
}
function decrementAngle(){
angle -= 5;
if(angle > 360){
angle = 0;
}
}
function xyVelocity(){
vx += dv * Math.cos(convertToRadians(angle)); //* friction;
vy += dv * Math.sin(convertToRadians(angle)); //* friction;
if(vx > maxVel){
vx = maxVel;
}
if(vy > maxVel){
vy = maxVel;
}
}
function shipMovement(){
if(38 in keys && keys[38]){
xyVelocity();
fire = true;
}
if(40 in keys && keys[40]){
vx = 0;
vy = 0;
}
if(37 in keys && keys[37]){
decrementAngle();
};
if (39 in keys && keys[39]){
incrementAngle();
};
if (32 in keys && keys[32]){
laser = true;
};
}
function xyAndFriction(){
x += vx * dt;
y += vy * dt;
vx *= frict;
vy *= frict;
}
function outOfBorders(){
if(x > W){
x = x - W;
}
if(x< 0){
x = W;
}
if(y > H){
y = y - H;
}
if(y < 0){
y = H;
}
}
function blazeatron420(){
context.beginPath();
context.moveTo(0,0);
context.lineTo(20,10);
context.lineTo(0,20);
context.lineTo(7,10);
context.lineTo(0,0);
context.strokeStyle = "green";
context.stroke();
}
function space(){
context.fillStyle = "black";
context.fillRect(0,0,W,H);
}
function drawEverything() {
shipMovement();
xyAndFriction();
outOfBorders();
//context.save();
space();
context.save();
context.translate(x,y);
//context.translate(25,25);
context.rotate(convertToRadians(angle));
context.translate(-7,-10);
if(fire){
ogienZdupy();
}
if(laser){
drawLaser();
moveLaser();
}
context.fillStyle = "green";
//context.fillText(vx + " km/h",50,50);
/*context.fillText("dupa",-30,0);
context.beginPath();
context.moveTo(-20,5);
context.lineTo(-5,10);
context.strokeStyle = "green"; //KOLOR LINII ;_;
context.stroke();*/
blazeatron420();
context.restore();
}
setInterval(drawEverything, 20);
And the fiddle http://jsfiddle.net/tomasthall/q40zvd6v/1/
I moved your laser drawing out of the rotated context.
Initiated lx and ly to x y in the moment of firing.
laser = true;
lx = x;
ly = y;
http://jsfiddle.net/q40zvd6v/2/
Now you need to just give the laser a proper vector.
That can be calculated from the angle of your ship and some trigonometry.
if (32 in keys && keys[32]){
laser = true;
lx = x;
ly = y;
var angle_in_radians = convertToRadians(angle);
lvx = Math.cos(angle_in_radians);
lvy = Math.sin(angle_in_radians);
};
And it shoots fine now:
http://jsfiddle.net/q40zvd6v/4/
Looks much nicer if you add the ship vector to projectile vector though.
if (32 in keys && keys[32]){
laser = true;
lx = x;
ly = y;
var angle_in_radians = convertToRadians(angle);
lvx = Math.cos(angle_in_radians);
lvy = Math.sin(angle_in_radians);
lvx += vx;
lvy += vy;
};
http://jsfiddle.net/q40zvd6v/5/
Good luck on your game :>
this be your problem right here:
context.rotate(convertToRadians(angle));
context.translate(-7,-10);
you rotate everything on the canvas..
when in fact you should only be rotating the blazeatron420
Please look at this question:
How do I rotate a single object on an html 5 canvas?
and see the solutions for rotating a single "object"..

How to make the objects fall in javascript?

I am trying to make this game, you should not collide the falling object. I have the objects falling and I have my black square, but it flashes when I run it and Im not sure how to make the code stop when the two objects collide together.
here is the code that I have so far!
<html>
<body>
<canvas id="canvasRegn" width="600" height="450"style="margin:100px;"></canvas>
<script>
var ctx;
var imgBg;
var imgDrops;
var noOfDrops = 50;
var fallingDrops = [];
function drawBackground(){
ctx.drawImage(imgBg, 0, 0); //Background
}
function draw() {
drawBackground();
for (var i=0; i< noOfDrops; i++)
{
ctx.drawImage (fallingDrops[i].image, fallingDrops[i].x, fallingDrops[i].y); //The rain drop
fallingDrops[i].y += fallingDrops[i].speed; //Set the falling speed
if (fallingDrops[i].y > 480) { //Repeat the raindrop when it falls out of view
fallingDrops[i].y = -25 //Account for the image size
fallingDrops[i].x = Math.random() * 800; //Make it appear randomly along the width
}
}
}
function setup() {
var canvas = document.getElementById('canvasRegn');
if (canvas.getContext) {
ctx = canvas.getContext('2d');
imgBg = new Image();
imgBg.src = "http://www.hamdancommunications.com/HComm/img/wite%20square.png";
setInterval(draw, 36);
for (var i = 0; i < noOfDrops; i++) {
var fallingDr = new Object();
fallingDr["image"] = new Image();
fallingDr.image.src = 'http://s18.postimg.org/o6jpmdf9x/Line1.jpg';
fallingDr["x"] = Math.random() * 800;
fallingDr["y"] = Math.random() * 5;
fallingDr["speed"] = 3 + Math.random() * 5;
fallingDrops.push(fallingDr);
anotherGame();
}
}
}
setup();
function anotherGame(){
var canvas = document.getElementById("canvasRegn");
var ctx = canvas.getContext('2d');
canvas.addEventListener("mousedown", clicked);
canvas.addEventListener("mousemove", moved);
canvas.addEventListener("mouseup", released);
var isclicked = 0;
var square = new Object();
square.color = "black";
square.x = 100;
square.y = 100;
square.w = 50;
square.h = 50;
var offX = 0;
var offY = 0;
function draw(){
ctx.clearRect(0,0,canvas.width,canvas.height);
ctx.fillStyle = square.color;
ctx.fillRect(square.x,square.y,square.w,square.h);
}
function game(){
}
function clicked(e){
var x = e.offsetX;
var y = e.offsetY;
if(x >= square.x && x <= square.x + square.w &&
y >= square.y && y <= square.y + square.h){
isclicked = 1;
offX = x - square.x;
offY = y - square.y;
}
}
function moved(e){
if(isclicked == 1){
var x = e.offsetX;
var y = e.offsetY;
square.x = x - offX;
square.y = y - offY;
}
}
function released(e){
var x = e.offsetX;
var y = e.offsetY;
isclicked = 0;
}
var drawtimer = setInterval(draw, 1000/30);
var gametimer = setInterval(game, 1000/10);
}
</script>
</body>
</html>

Getting mouse position within canvas

I am trying to modified this effect to work within my canvas. However, I can't seem to get the mouse position to work properly. The hover area isn't contained to my canvas.
Here's a CSSdeck of how i tried to implement it: http://cssdeck.com/labs/ukktjtis
Effect:
function hoverText(){
window.requestAnimFrame = (function(){
return window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
function( callback ){
window.setTimeout(callback, 1000 / 60);
};
})();
var canvas = document.getElementById("canvas"),
ctx = canvas.getContext("2d"),
keyword = "MacroPlay Games",
imageData,
density = 3,
mouse = {},
hovered = false,
colors = ["0,120,232", "8,200,255", "30,140,255"],
minDist = 20,
bounceFactor = 0.7;
var W = window.innerWidth, H = window.innerHeight;
canvas.width = W;
canvas.height = H;
document.addEventListener("mousemove", function(e) {
mouse.x = e.pageX-50;
mouse.y = e.pageY+200;
}, false);
// Particle Object
var Particle = function() {
this.w = Math.random() * 10.5;
this.h = Math.random() * 10.5;
this.x = -W;
this.y = -H;
this.free = false;
this.vy = -5 + parseInt(Math.random() * 10) / 2;
this.vx = -4 + parseInt(Math.random() * 8);
// Color
this.a = Math.random();
this.color = colors[parseInt(Math.random()*colors.length)];
this.setPosition = function(x, y) {
this.x = x;
this.y = y;
};
this.draw = function() {
ctx.fillStyle = "rgba("+this.color+","+this.a+")";
ctx.fillRect(this.x, this.y, this.w, this.h);
}
};
var particles = [];
// Draw the text
function drawText() {
ctx.clearRect(0, 0, W, H);
ctx.fillStyle = "#000000";
ctx.font = "100px 'Arial', sans-serif";
ctx.textAlign = "center";
ctx.fillText(keyword, W/2, H/2);
}
// Clear the canvas
function clear() {
ctx.clearRect(0, 0, W, H);
}
// Get pixel positions
function positionParticles() {
// Get the data
imageData = ctx.getImageData(0, 0, W, W);
data = imageData.data;
// Iterate each row and column
for (var i = 0; i < imageData.height; i += density) {
for (var j = 0; j < imageData.width; j += density) {
// Get the color of the pixel
var color = data[((j * ( imageData.width * 4)) + (i * 4)) - 1];
// If the color is black, draw pixels
if (color == 255) {
particles.push(new Particle());
particles[particles.length - 1].setPosition(i, j);
}
}
}
}
drawText();
positionParticles();
// Update
function update() {
clear();
for(i = 0; i < particles.length; i++) {
var p = particles[i];
if(mouse.x > p.x && mouse.x < p.x + p.w && mouse.y > p.y && mouse.y < p.y + p.h)
hovered = true;
if(hovered == true) {
var dist = Math.sqrt((p.x - mouse.x)*(p.x - mouse.x) + (p.y - mouse.y)*(p.y - mouse.y));
if(dist <= minDist)
p.free = true;
if(p.free == true) {
p.y += p.vy;
p.vy += 0.15;
p.x += p.vx;
// Collision Detection
if(p.y + p.h > H) {
p.y = H - p.h;
p.vy *= -bounceFactor;
// Friction applied when on the floor
if(p.vx > 0)
p.vx -= 0.1;
else
p.vx += 0.1;
}
if(p.x + p.w > W) {
p.x = W - p.w;
p.vx *= -bounceFactor;
}
if(p.x < 0) {
p.x = 0;
p.vx *= -0.5;
}
}
}
ctx.globalCompositeOperation = "lighter";
p.draw();
}
}
(function animloop(){
requestAnimFrame(animloop);
update();
})();
}
It's highly advised you use jquery (or some js lib) to avoid cross-browser issues like getting the mouse position.
You can easily get the mouse position in any browser using jquery like this:
// get the position of the canvas relative to the web page
var canvasOffset=$("#canvas").offset();
var offsetX=canvasOffset.left;
var offsetY=canvasOffset.top;
// then in the mouse handler, get the exact mouse position like this:
function handleMouseDown(e){
mouseX=parseInt(e.clientX-offsetX);
mouseY=parseInt(e.clientY-offsetY);
// Put your mousedown stuff here
}
// tell the browser to send mousedown events to the handleMouseDown function
$("#canvas").mousedown(function(e){handleMouseDown(e);});
I personally prefer a library like hammer.js. I've use it for all my projects - check it out, it's pretty good.

Categories

Resources