detecting collisions on the canvas - javascript

im trying to make a game where collisions happen between the protagonist and the antagonist. I cant get the collision to work though, i've tried using the x and y position then the x and y positions plus the width and the height of the protagonist and the antagonist
var canvas = document.getElementById('canvas');
var PX = 10;
var PY = 10;
var PW = 10;
var PH = 10;
var P = PX + PY;
var EX1 = 100;
var EY1 = 100;
var EW1 = 10;
var EH1 = 10;
var E1 = EX1 + EY1;
window.addEventListener("keydown", charMove);
window.addEventListener("keyup", charMove);
window.addEventListener("keypress", charMove);
window.onload = function() {
context = canvas.getContext("2d");
canvas.style.background = "black";
var framesPerSecond = 30;
setInterval(function() {
draw();
move();
}, 1000/framesPerSecond);
}
function draw() {
//EX context.fillRect(PosX, PosY, width, height);
//draws protagonist
context.beginPath();
context.clearRect(0, 0, canvas.width, canvas.height);
context.fillStyle = "blue"
context.fillRect(PX, PY, PW, PH);
context.stroke();
context.closePath();
//draws antagonist(s)
context.beginPath();
context.fillStlyle = "red";
context.fillRect(EX1, EY1, EW1, EH1);
context.stroke();
context.closePath();
}
function move() {
}
function charMove(){
var x = event.which || event.keyCode;
if(x == 37){
PX -= 1;
}
if(x == 38){
PY -= 1;
}
if(x == 39){
PX += 1;
}
if(x == 40){
PY += 1;
}
}
//detect collision
setInterval(function() {
if(PX > EX1 || PX + PW < EX1 + EW1 && PY + PH > EY1 + EH1 || PY + PH < EY1 + EH1){
window.alert("collision");
}
}, 1);
<html>
<head>
</head>
<body>
<canvas width="500px" height="500px" id="canvas" class="canvas">
</body>
</html>

Your formula for collision is wrong.
This problem is called Axis Aligned Bounding Box collision.
Two AABBs collide if their projections to each axis collide. In your 2-dimensinal case you have to consider the horizontal and vertical projections.
The projections are segments of 1-d space. Collision for those is very easy: if the start or the end of a segment is on the other they collide. Formally start2 <= start1 <= end2 or start2 <= end1 <= end2
In code:
intersects([p.x, p.x + p.width], [e.x, e.x + e.width]) && intersects([p.y, p.y + p.height], [e.y, e.y + e.height])
where
function intersects(seg1, seg2) {
return contains(seg1, seg2[0]) || contains(seg1, seg2[1])
}
function contains(segment, point) {
return segment[0] <= point && point <= segment[1]
}

Related

how to make 2 animated squares run through the screen at different speeds? + how to make them collide with a bigger square (player)

I need to make a game in javascript. In the game, the player is a green square, which, moves only when you click on it. In the game, there are 2 enemies: a small red square and a more extensive (still small) blue square. They move on the same axis, in the gameplay you are supposed to dodge the squares. (I am very amateur)
how it should look: https://www.youtube.com/watch?v=b64KUt38-i8&feature=youtu.be
The red square moves at 30 pixels every frame, and the blue one moves at 20 pixels.
code (there is already the green square, part of the blue square):
var canvasObject = document.getElementById("myCanvas");
var ctx = canvasObject.getContext("2d");
var squareTopLeftX = 300;
var squareTopLeftY = 100;
var WIDTH = 400;
var HEIGHT = 500;
var squareX = 1;
var squareY = 100;
var diffY = 1;
var squareSize2 = 10;
var modulo = 1; // a variable used to change player's position when clicked
var framecounter = 10;
var interval = setInterval(draw, framecounter);
function DrawSquare() {
ctx.fillRect(squareTopLeftX, squareTopLeftY, 50, 50); // player
}
function drawSquareBlue() { // blue square, enemy
ctx.beginPath();
ctx.fillRect(squareX, squareY, squareSize2, squareSize2);
}
function MouseClick() {
var posX = window.event.pageX - canvasObject.offsetLeft;
var posY = window.event.pageY - canvasObject.offsetTop;
if (modulo % 2 == 1) {
if (posX >= squareTopLeftX && posX <= (squareTopLeftX + 50) && posY >= squareTopLeftY && posY <= (squareTopLeftY + 50)) {
squareTopLeftY = 300;
modulo++;
}
} else {
if (posX >= squareTopLeftX && posX <= (squareTopLeftX + 50) && posY >= squareTopLeftY && posY <= (squareTopLeftY + 50)) {
squareTopLeftY = 100;
modulo++;
}
}
}
var score = 0;
function drawRect() {
ctx.fillRect(0, 0, WIDTH, HEIGHT);
}
function draw() {
framecounter++;
/*if (squareTopLeftX>=squareX2 && squareTopLeftX<=(squareX2 + squareSize) && squareTopLeftY>=squareY2 && squareTopLeftY<=(squareY2 + squareSize)) {
document.write("game over<br>");
document.write("your score: " + score);
clearInterval(interval);
} */
if (squareX <= 0)
diffY = -diffY;
squareX = squareX + diffY;
ctx.fillStyle = "white";
drawRect();
ctx.fillStyle = "green";
DrawSquare();
ctx.fillStyle = "blue";
drawSquareBlue();
}
interval;
<canvas id="myCanvas" onClick="MouseClick()" width="400" height="500" style="border:1px solid #d3d3d3;"></canvas>

how to define a color for an instance of a class in Java Scipt

I've making a breakout game and I had to make some blocks and give them random colors defined in a array, but for making more blocks I had to use a for loop. So, when I add them to my update function, colors are flashing at frame rate. I think you'll understand better if you run the snippet
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;
};
}
var colors = ['#A5E75A','#7254AD','#FFD606','#FF093D'];
function Block(x,y,w,h){
this.x = x;
this.y = y;
this.w = w;
this.h = h;
this.status =1;
this.show= function(color){
ctx.beginPath();
ctx.roundedRectangle(this.x,this.y,this.w,this.h,5);
//ctx.arc(this.x,this.y,10,0,2*Math.PI);
//ctx.fillStyle = colors[Math.floor(Math.random()*colors.length)];
ctx.fillStyle = color;
ctx.fill();
ctx.closePath();
};
}
var player = new Player(canvas.width/2-50,780,100,20);
var ball = new Ball(player.x+player.w/2, player.y,15);
var rigthPressed = false;
var leftPressed = false;
var blocks = [];
var rowCount = 5;
var columnCount = 6;
var noInRow = 6;
var blockCount = (rowCount*columnCount)+1;
var rc = {blockRow : 0,
blockCol : 0};
for(let i = 0; i < blockCount; i++){
blocks.push(new Block(rc.blockCol*60+25,rc.blockRow*60-30,50,50));
rc.blockCol++;
if(i % noInRow === 0){
rc.blockRow++;
rc.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 && ball.y<player.y+player.h){
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 reload(){
if (ball.y>canvas.height){
//alert('gameOver');
ball.x =player.x+player.w/2;
ball.y = player.y-ball.r;
ballSpeedX = 0;
ballSpeedY = 0;
}
}
var ballSpeedX = 0;
var ballSpeedY = -0;
function collision(){
for(let i=1;i<blockCount;i++){
if(ball.x>blocks[i].x &&
ball.x<blocks[i].x+blocks[i].w &&
ball.y>blocks[i].y &&
ball.y<blocks[i].y+blocks[i].h){
blocks[i].status = 0;
ballSpeedY = -ballSpeedY;
blocks.splice(i,1);
blockCount--;
//ballSpeedX = 0;
//ballSpeedY = 0;
console.log('hit');
}
}
}
function update(){
ctx.clearRect(0,0,canvas.width,canvas.height);
objMovement();
for(let i=1;i<blockCount;i++){
if(blocks[i].status == 1){
blocks[i].show(colors[Math.floor(Math.random()*colors.length)]);
}
}
collision();
ball.show();
ball.move(ballSpeedX,ballSpeedY);
player.show();
reload();
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>
Because you remove and redraw all rectangles from the canvas each update and assign a new color on show, they get assigned a new color each update. You might be able to avert this by adding a property color to the rectangle, which is initialised (once, so in the initial for loop) with a random color, and alter the show function to use this.color rather than accept a color as an argument. This way, you don't assign a new color to a rectangle each update, and it won't change color each update.

Canvas collision

I am a new in javascript and trying to find out how to make a collision with ball and plank which will stop the game and alert player with something like "You lost". But I only want red balls to hit the plank and blue to pass on without touching. Here is code that I am working on. (I dont mind if you could help to do collision only with both balls)
var spawnRate = 100;
var spawnRateOfDescent = 2;
var lastSpawn = -10;
var objects = [];
var startTime = Date.now();
function spawnRandomObject() {
var t;
if (Math.random() < 0.50) {
t = "red";
} else {
t = "blue";
}
var object = {
type: t,
x: Math.random() * (canvas.width - 30) + 15,
y: 0
}
objects.push(object);
}
function animate() {
var time = Date.now();
if (time > (lastSpawn + spawnRate)) {
lastSpawn = time;
spawnRandomObject();
}
for (var i = 0; i < objects.length; i++) {
var object = objects[i];
object.y += spawnRateOfDescent;
ctx.beginPath();
ctx.arc(object.x, object.y, 8, 0, Math.PI * 2);
ctx.closePath();
ctx.fillStyle = object.type;
ctx.fill();
}
}
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
var paddleHeight = 10;
var paddleWidth = 60;
var paddleY = 480
var paddleX = (canvas.width-paddleWidth)/2;
var rightPressed = false;
var leftPressed = false;
document.addEventListener("keydown", keyDownHandler, false);
document.addEventListener("keyup", keyUpHandler, false);
function keyDownHandler(e) {
if(e.keyCode == 39) {
rightPressed = true;
}
else if(e.keyCode == 37) {
leftPressed = true;
}
}
function keyUpHandler(e) {
if(e.keyCode == 39) {
rightPressed = false;
}
else if(e.keyCode == 37) {
leftPressed = false;
}
}
function drawPaddle() {
ctx.beginPath();
ctx.rect(paddleX, paddleY, paddleWidth, paddleHeight);
ctx.fillStyle = "#0095DD";
ctx.fill();
ctx.closePath();
}
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
drawPaddle();
animate();
if(rightPressed && paddleX < canvas.width-paddleWidth) {
paddleX += 3;
}
else if(leftPressed && paddleX > 0) {
paddleX -= 3;
}
}
setInterval(draw, 10);
Thanks!
If you have an object like this:
let ball = { type: 'red', x: 10, y: 10, width: 10, height: 10 };
You might want to consider adding a method to this to check if it overlaps any other rectangle:
ball.overlapsBall = function( otherBall ){
return !(
otherBall.x + otherBall.width < this.x
&& otherBall.y + otherBall.height < this.y
&& otherBall.y > this.y + this.height
&& otherBall.x > this.x + this.height
);
}
You do this by checking if it does not overlap, which is only true if one box is entirely outside of the other (have a read through the if statement and try to visualise it, its actually rather simple)
In your draw function you could now add a loop to see if any overlap occurs:
var overlap = objects.filter(function( ball ) { return paddle.overlapsBall( ball ) });
You could even place an if statement to check it's type! (The filter will take you entire array of balls and check the overlaps, and remove anything from the array that does not return true. Now you can use overlaps.forEach(function( ball ){ /* ... */}); to do something with all the balls that overlapped your paddle.)
One last thing, if you are planning on doing this with many objects you might want to consider using a simple class like this for every paddle or ball you make:
class Object2D {
constructor(x = 0, y = 0;, width = 1, height = 1){
this.x = x;
this.y = x;
this.width = width;
this.height = height;
}
overlaps( otherObject ){
!( otherObject.x + otherObject.width < this.x && otherObject.y + otherObject.height < this.y && otherObject.y > this.y + this.height && otherObject.x > this.x + this.height );
}
}
This allows you to this simple expression to create a new object that automatically has a method to check for overlaps with similar objects:
var paddle = new Object2D(0,0,20,10);
var ball = new Object2D(5,5,10,10);
paddle.overlaps( ball ); // true!
On top of that, you are ensured that any Object2D contains the values you will need for your calculations. You can check if this object is if the right type using paddle instanceof Object2D (which is true).
Note Please note, as #Janje so continuously points out in the comments below, that we are doing a rectangle overlap here and it might create some 'false positives' for all the pieces of rectangle that aren't the circle. This is good enough for most cases, but you can find the math for other overlaps and collisions easily ith a quick google search.
Update: Simple Implementation
See below for a very simple example of how overlaps work in action:
var paddle = { x: 50, y: 50, width: 60, height: 20 };
var box = { x: 5, y: 20, width: 20, height: 20 };
var canvas = document.createElement('canvas');
var ctx = canvas.getContext('2d');
document.body.appendChild( canvas );
canvas.width = 300;
canvas.height = 300;
function overlaps( a, b ){
return !!( a.x + a.width > b.x && a.x < b.x + b.width
&& a.y + a.height > b.y && a.y < b.y + b.height );
}
function animate(){
ctx.clearRect( 0, 0, canvas.width, canvas.height );
ctx.fillStyle = overlaps( paddle, box ) ? "red" : "black";
ctx.fillRect( paddle.x, paddle.y, paddle.width, paddle.height );
ctx.fillRect( box.x, box.y, box.width, box.height );
window.requestAnimationFrame( animate );
}
canvas.addEventListener('mousemove', function(event){
paddle.x = event.clientX - paddle.width / 2;
paddle.y = event.clientY - paddle.height / 2;
})
animate();

object moves through keyboard arrow keys using html5 and javascript

how can i move the object with keyboard keys using html5 and javascript. Here i tried it with below code but it is not moving can any one help to move the object using keyboard arrow keys?
<!DOCTYPE html>
<html>
<head>
</head>
<body onLoad="gameLoop()" onkeydown="keyDown(event)" onkeyup="keyUp(event)" bgcolor='green'>
<canvas id="mycanvas"></canvas>
<script>
var canvas = document.getElementById('mycanvas');
var ctx = canvas.getContext('2d');
ctx.beginPath();
ctx.arc(100, 100, 50, 0.25 * Math.PI, 1.25 * Math.PI, false);
ctx.fillStyle = "rgb(255, 255, 0)";
ctx.fill();
ctx.beginPath();
ctx.arc(100, 100, 50, 0.75 * Math.PI, 1.75 * Math.PI, false);
ctx.fill();
ctx.beginPath();
ctx.arc(100, 75, 10, 0, 2 * Math.PI, false);
ctx.fillStyle = "rgb(0, 0, 0)";
ctx.fill();
//moves//
var xpos=500;
var ypos=550;
var xspeed=1;
var yspeed=0;
var maxspeed=5;
//boundaries//
var minx=500;
var miny=200;
var maxx=990;
var maxy=400;
//controller
var upPressed=0;
var downPressed=1;
var leftPressed=0;
var rightPressed=0;
function slowDownX()
{
if(xspeed > 0) xspeed=xspeed-1; if(xspeed<0) xspeed=xspeed+1;
}
function slowDownY()
{
if(yspeed > 0)
yspeed = yspeed-1;
if(yspeed < 0)
yspeed = yspeed+1;
}
function gameLoop()
{
xpos=Math.min(Math.max(xpos+xspeed,minx),maxx); ypos=Math.min(Math.max(ypos+yspeed,miny),maxy);
xpos = document.getElementById('mycanvas').style.left;
ypos = document.getElementById('mycanvas').style.top;
if (upPressed == 1)
yspeed = Math.max(yspeed - 3,-3*maxSpeed);
if (downPressed == 1)
yspeed = Math.min(yspeed + 3,3*maxSpeed)
if (rightPressed == 1)
xspeed = Math.min(xspeed + 1,1*maxSpeed);
if (leftPressed == 1)
xspeed = Math.max(xspeed - 1,-1*maxSpeed);
if (upPressed == 0 && downPressed == 0)
slowDownY();
if (leftPressed == 0 && rightPressed == 0)
slowDownX();
return setTimeout("gameLoop()",10);
}
function keyDown(e)
{
var code = e.keyCode ? e.keyCode : e.which;
if (code == 38)
upPressed = 1;
if (code == 40)
downPressed = 1;
if (code == 37)
leftPressed = 1;
if (code == 39)
rightPressed = 1;
}
function keyUp(e)
{
var code = e.keyCode ? e.keyCode : e.which;
if (code == 38)
upPressed = 0;
if (code == 40)
downPressed = 0;
if (code == 37)
leftPressed = 0;
if (code == 39)
rightPressed = 0;
}
</script>
</body>
</html>
Here are the basics of drawing a shape on the html canvas and moving it with arrowkeys
Disclaimer: this code is not best game technique, it’s meant for clear instruction. ;)
First create a few variables that define a ball:
// the ball will be at coordinates 70,75
var ballX=70;
var ballY=75;
// the ball will have a radius of 15;
var ballRadius=15;
Next create a function that will draw that ball at the specified coordinates
function draw(){
// clear the canvas for the next frame
ctx.clearRect(0,0,canvas.width,canvas.height);
// draw a ball that the use can move with left/right arrow keys
// the ball's center will be at BallX / BallY
// the ball will have a radius of BallRadius
ctx.beginPath();
ctx.arc(ballX,ballY,ballRadius,0,Math.PI*2,false);
ctx.closePath();
ctx.fill();
}
Now listen for user’s keystrokes.
// Listen for when the user presses a key down
window.addEventListener("keydown", keyDownHandler, true);
When the user presses a key down:
If the user presses the left or right arrows, move the ball by changing it’s “ballX” coordinate.
After changing the balls position, redraw the canvas
This code handles when a key is down (called by the addEventListener):
// Here we just handle command keys
function keyDownHandler(event){
// get which key the user pressed
var key=event.which;
// Let keypress handle displayable characters
if(key>46){ return; }
switch(key){
case 37: // left key
// move the ball 1 left by subtracting 1 from ballX
ballX -= 1;
break;
case 39: // right key
// move the ball 1 right by adding 1 to ballX
ballX += 1;
break;
default:
break;
}
// redraw the ball in its new position
draw();
}
Here is code and a Fiddle: http://jsfiddle.net/m1erickson/TsXmx/
<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" media="all" href="css/reset.css" /> <!-- reset css -->
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<style>
body{ background-color: ivory; padding:20px;}
#canvas{border:1px solid red;}
</style>
<script>
$(function(){
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
ctx.strokeStyle="blue";
ctx.fillStyle="red";
var ballX=70;
var ballY=75;
var ballRadius=15;
var leftWall=30;
var rightWall=120;
draw();
function draw(){
// clear the canvas for the next frame
ctx.clearRect(0,0,canvas.width,canvas.height);
// tell canvas to start a new path
// draw walls on left and right
ctx.beginPath();
ctx.moveTo(leftWall,0);
ctx.lineTo(leftWall,canvas.height);
ctx.moveTo(rightWall,0);
ctx.lineTo(rightWall,canvas.height);
ctx.lineWidth=2;
ctx.stroke();
// draw a ball that the use can move with left/right arrow keys
ctx.beginPath();
ctx.arc(ballX,ballY,ballRadius,0,Math.PI*2,false);
ctx.closePath();
ctx.fill();
}
// Here we just handle command keys
function keyDownHandler(event){
// get which key the user pressed
var key=event.which;
// Let keypress handle displayable characters
if(key>46){ return; }
switch(key){
case 37: // left key
// move the ball 1 left by subtracting 1 from ballX
ballX -= 1;
// calc the ball's left edge
var ballLeft=ballX-ballRadius;
// Keep the ball from moving through the left wall
if(ballLeft<=leftWall){ ballX=leftWall+ballRadius; }
break;
case 39: // right key
// move the ball 1 right by adding 1 to ballX
ballX += 1;
// calc the ball's right edge
var ballRight=ballX+ballRadius;
// Keep the ball from moving through the right wall
if(ballRight>=rightWall){ ballX=rightWall-ballRadius; }
break;
default:
break;
}
// redraw everything
draw();
}
// Listen for when the user presses a key down
window.addEventListener("keydown", keyDownHandler, true);
}); // end $(function(){});
</script>
</head>
<body>
<p>Click in the red box to get keyboard focus</p>
<p>Then Move ball with left and right arrow keys</p>
<canvas id="canvas" width=200 height=150></canvas>
</body>
</html>
two ball are move diff. side on key board .
first ball to move to keyboard to up, down , right, left key
second ball move to A(left side), W(up side) ,D(right side) and S(down side).
just copy and past in your screen.
<html>
<head>
<title> game</title>
</head>
<body>
<canvas id="canvas" width="307" height= "211" style= "border:1px solid #ff0000 ;" mxrgin = right >
</canvas>
<script>
var x = 10;
var x1= 280;
var y = 10;
var y1 = 10;
var dx = 2;
var dx1 = 3;
var dy = 1;
var dy1 =1;
var ctx;
var ctx1;
var WIDTH=300;
var HEIGHT=200;
var a="";
var b="";
var sp= 500;
var timer=[];
var down = [];
var up;
document.onkeydown=k_down;
document.onkeyup=k_up;
var left=false;
var right=false;
var up1=false;
var down1=false;
var flag=false;
var aa=false;
init();
function k_down(e)
{
down[e.keyCode]=true;
clearInterval(timer);
//sp=10;
if(down[37])
{
if(sp>2)
{
sp++;
}
dy=0;
dx=-3;
left=true;
flag=false;
//down=[];
}
else if(down[38])
{
if(sp>2)
{
sp++;
}
dx=0;
dy=-4;
up1=true;
flag=false;
//down=[];
}
else if(down[39])
{
if(sp>2)
{
sp++;
}
dy=0;
dx=3;
right=true;
flag=false;
//down=[];
}
else if(down[40])
{
if(sp>2)
{
sp++;
}
dx=0;
dy=4;
down1=true;
flag=false;
//down=[];
}
if(down[65])
{
dy1=0;
dx1=-3;
}
else if(down[87])
{
dx1=0;
dy1=-4;
}
else if(down[68])
{
dy1=0;
dx1=3;
}
else if(down[83])
{
dx1=0;
dy1=4;
}
//console.log("speed++>"+sp);
timer=setInterval(draw,sp);
down[e.keyCode]=false;
}
function k_up(e)
{
up=e.keyCode;
//alert(sp);
if(sp<10)
{
sp=10;
clearInterval(timer);
timer=setInterval(draw,10);
}
//console.log("upp->>"+down);
if(left==true && up1==true)
{
//console.log("1");
sp=2;
clearInterval(timer);
timer=setInterval(draw,sp);
dx=-3;
dy=-4;
flag=true;
}
else if(left==true && down1==true)
{
//console.log("2");
sp=2;
clearInterval(timer);
timer=setInterval(draw,sp);
dx=-3;
dy=4;
flag=true;
}
else if(right==true && up1==true)
{
//console.log("3");
sp=2;
clearInterval(timer);
timer=setInterval(draw,sp);
dx=3;
dy=-4;
flag=true;
}
else if(right==true && down1==true)
{
//console.log("4");
sp=2;
clearInterval(timer);
timer=setInterval(draw,sp);
dx=3;
dy=4;
flag=true;
}
if(left==true)
{
if(flag==false){
dy=0;
dx=-3;
}
}
else if(up1==true)
{
if(flag==false){
dx=0;
dy=-4;
}
}
else if(right==true)
{
if(flag==false){
dy=0;
dx=3;
}
}
else if(down1==true)
{
if(flag==false){
dx=0;
dy=4;
}
}
if (up==37)
{
left=false;
}
else if (up==38)
{
up1=false;
}
else if (up==39)
{
right=false;
}
else if (up==40)
{
down1=false;
}
}
function circle(x,y,r) {
ctx.beginPath();
ctx.arc(x, y, r, 0, Math.PI*2, true);
ctx.closePath();
ctx.fill();
}
function rect(x,y,w,h) {
ctx.beginPath();
ctx.rect(x,y,w,h);
ctx.closePath();
ctx.fill();
}
function clear() {
ctx.clearRect(0, 0, 307, 211);
}
function init() {
//ctx = $("#canvas").getContext("2d");
ctx = document.getElementById('canvas').getContext("2d");
//WIDTH = $("#canvas").width()
//HEIGHT = $("#canvas").height()
//canvas.addEventListener("click", getPosition, false);
return setInterval(draw, 10);
}
/*
function getPosition(event)
{
// var canvas = document.getElementById("canvas");
// var x = event.x;
//var y = event.y;
// x -= canvas.offsetLeft;
// y -= canvas.offsetTop;
//alert("x: " + x + " y: " + y);
}
*/
function draw() {
clear();
circle(x, y, 10);
circle(x1, y1, 10);
if (x + dx > WIDTH || x + dx < 0)
dx = -dx;
if (y + dy > HEIGHT || y + dy < 0)
dy = -dy;
x += dx;
y += dy;
console.log("x->"+x)
if (x==10){
dx = -dx;
x += dx;
y += dy;
}
if (y==10){
dy = -dy;
x += dx;
y += dy;
}
if (x1 + dx1 > WIDTH || x1 + dx1 < 0)
dx1 = -dx1;
if (y1 + dy1 > HEIGHT || y1 + dy1 < 0)
dy1 = -dy1;
x1 += dx1;
y1 += dy1;
console.log("x1->"+x1)
if (x1==10){
dx1 = -dx1;
x1 += dx1;
y1 += dy1;
}
if (y1==10){
dy1 = -dy1;
x1 += dx1;
y1 += dy1;
}
}
</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