Pure Javascript Tile map collision detection - javascript

I am making a tile based game with a traditional method(two for loops) and i am trying to write collision detection but nothing works. I want the blue square to stay in the screen and be on top of the tiles after you hit start. I have encountered a virus looking for a solution. Please help me stack overflow community.
The code:
const context = document.getElementById("canvas").getContext('2d');
const person = new rectangle(100,100,20,20,'blue');
setInterval(update_all,10);
var next_block_x = 0;
var next_block_y = 0;
var block_size = 50;
var moving = false;
const tile_map = [
[0,0,0,0,0,0],
[0,0,0,0,0,0],
[1,0,0,0,0,0],
[1,1,0,0,0,0],
[1,1,1,0,0,0],
[1,1,1,1,1,1]
];
function rectangle(x,y,w,h,col){
this.x = x;
this.y = y;
this.w = w;
this.h = h;
this.col = col;
this.update = function(){
context.fillStyle = this.col;
context.fillRect(this.x,this.y,this.w,this.h);
context.stroke();
}
}
function block(x,y,col){
this.x = x;
this.y = y;
this.col = col;
context.fillStyle = this.col;
context.fillRect(this.x,this.y,block_size,block_size);
context.stroke();
}
function update_tile_map(){
for(i=0;i<tile_map.length;i++){
for(var j=0;j<tile_map[i].length;j++){
if(tile_map[i][j] == 1){
new block(next_block_x,next_block_y,'red');
}
next_block_x += block_size;
}
next_block_x = 0;
next_block_y += block_size
}
next_block_x = 0;
next_block_y = 0;
}
function clear(){
context.clearRect(0,0,300,300);
}
function start(){
moving = true;
}
function stop(){
moving = false;
}
function update_all(){
clear();
update_tile_map();
person.update();
if(moving != false){
person.y ++;
}
}
#canvas{
background-color:lightgrey;
border: 4px solid grey;
}
<button onclick='start()'>START</button>
<button onclick='stop()'>STOP</button>
<canvas id="canvas" width='300' height='300'></canvas>

You could add an if statement to check if the block has hit the wall:
if (person.y<300) person.y ++; else person.y = 0
const context = document.getElementById("canvas").getContext('2d');
const person = new rectangle(100,100,20,20,'blue');
setInterval(update_all,10);
var block_size = 50;
var moving = false;
const tile_map = [
[1,1,1,1,1,1],
[1,0,0,0,0,1],
[1,0,0,0,0,1],
[1,0,0,0,0,1],
[1,0,0,0,0,1],
[1,1,1,1,1,1]
];
function rectangle(x,y,w,h,col){
this.x = x;
this.y = y;
this.w = w;
this.h = h;
this.col = col;
this.update = function(){
context.fillStyle = this.col;
context.fillRect(this.x,this.y,this.w,this.h);
context.stroke();
}
}
function clear(){
context.clearRect(0,0,300,300);
}
function start(){
moving = true;
}
function stop(){
moving = false;
}
function update_all(){
clear();
person.update();
if(moving != false){
if (person.y<300) person.y ++; else person.y = 0
}
}
#canvas{
background-color:lightgrey;
border: 4px solid grey;
}
<button onclick='start()'>START</button>
<button onclick='stop()'>STOP</button>
<canvas id="canvas" width='300' height='300'></canvas>

Related

Game components won't draw after adding if/else statement

My game components won't draw onto the canvas after adding if/else statement.
The statement only checks if the game piece hit the game obstacle.
I tried changing attributes and rewrite some functions but it seems the problem hasn't been fixed.
Whenever I remove the if/else function, the components draw.
Here is part of the code that holds that if/else function:
if(gamePieceBorder.crashGame(gameObstacle) || gamePieceRed.crashGame(gameObstacle))
{
gameArea.stop();
}
else
{
obstacle.update();
gamePieceBorder.pos();
gamePieceBorder.move();
gamePieceBorder.update();
gamePieceRed.pos();
gamePieceRed.move();
gamePieceRed.update();
gameArea.clear();
}
For me not pasting an entire code, here is the pastebin link to the code: https://pastebin.com/HuiR7r7D
How can I get the components to draw? If someone fixes the code, what was the issue? I am not an expert at javascript but only a beginner.
There are several problems:
window.EventListener should be window.addEventListener
keyup and keydown should have no upper case letters
gameObstacle in that if is undefined (should be obstacle probably)
clear method should be called before drawing, not after it
Here is the corrected script: https://pastebin.com/bXpQ2qvB
//-----------------------------------------Variables
var gamePieceRed;
var gamePieceBorder;
var gameObstacle;
//-----------------------------------------
//-----------------------------------------Main game function
function startGame()
{
gamePieceRed = new component(22, 22, "rgb(255, 132, 156)", 10, 120);
gamePieceBorder = new component(24, 24, "black", 9, 119);
obstacle = new component(10, 200, "rgb(64, 0 ,12)", 300, 120)
gameArea.start();
}
//-----------------------------------------
//-----------------------------------------Creating game area and applying controls
var gameArea =
{
canvas : document.createElement("canvas"), start : function()
{
this.canvas.width = 510;
this.canvas.height = 280;
this.context = this.canvas.getContext("2d");
document.body.insertBefore(this.canvas, document.body.childNodes[0]);
this.interval = setInterval(gameUpdate, 20);
window.addEventListener("keydown", function (e)
{
gameArea.keys = (gameArea.keys || []);
gameArea.keys[e.keyCode] = true;
}, true)
window.addEventListener("keyup", function (e)
{
gameArea.keys[e.keyCode] = false;
}, true)
},
clear : function()
{
this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
},
stop : function()
{
clearInterval(this.interval);
},
keyboard: function() {
if (this.keys) {
if (this.keys[37]) {gamePieceBorder.speedX = gamePieceRed.speedX = -2;}
else if (this.keys[39]) {gamePieceBorder.speedX = gamePieceRed.speedX = 2;}
else {gamePieceBorder.speedX = gamePieceRed.speedX = 0;}
if (this.keys[38]) {gamePieceBorder.speedY = gamePieceRed.speedY = -2;}
else if (this.keys[40]) {gamePieceBorder.speedY = gamePieceRed.speedY = 2;}
else {gamePieceBorder.speedY = gamePieceRed.speedY = 0;}
}
}
}
//-----------------------------------------
//-----------------------------------------Game component
function component(width, height, color, x, y)
{
this.width = width;
this.height = height;
this.x = x;
this.y = y;
this.speedX = 0;
this.speedY = 0;
this.update = function()
{
ctx = gameArea.context;
ctx.fillStyle = color;
ctx.fillRect(this.x, this.y, this.width, this.height)
}
this.move = function()
{
this.x += this.speedX;
this.y += this.speedY;
}
this.crashGame = function(obj)
{
var left = this.x;
var right = this.x + (this.width);
var top = this.y;
var bottom = this.y + (this.height);
var otherLeft = obj.x;
var otherRight = obj.x + (obj.width);
var otherTop = obj.y;
var otherBottom = obj.y + (obj.height);
var crash = true;
if (bottom < otherTop || top > otherBottom || right < otherLeft || left > otherRight)
{
crash = false;
}
return crash;
}
}
//-----------------------------------------
//-----------------------------------------Game area updater
function gameUpdate()
{
if(gamePieceBorder.crashGame(obstacle) || gamePieceRed.crashGame(obstacle))
{
gameArea.stop();
}
else
{
gameArea.clear();
obstacle.update();
gameArea.keyboard();
gamePieceBorder.move();
gamePieceBorder.update();
gamePieceRed.move();
gamePieceRed.update();
}
}
//-----------------------------------------
<html>
<style>
canvas
{
border: 1px solid #d3d3d3;
background-image: url("https://ak0.picdn.net/shutterstock/videos/22492090/thumb/1.jpg");
}
</style>
<body onload = "startGame()">
</body>
</html>

Game with moving circle through obstacle in Javascript doesn't work

I created a game using Javascript. It is a game where a circle which can be controlled by the mouse, has to navigate through moving obstacles similar to a maze. When the circle hits an obstacle, the game should stop.
When i tried the same game but with one obstacle, it worked. But after adding more lines of code to create more obstacles, the circle and the obstacle doesn't appear in the output. Also, the crashWith function isn't being called when the circle hits the obstacle.
Here is the code:
<!DOCTYPE html>
<html>
<style>
canvas {
border:1px solid #000000;
background-image: url("https://data.whicdn.com/images/223851992/large.jpg");
}
</style>
<body onload="begin()">
<script>
var gamePiece;
var gameObstacle = [];
function begin(){
gameArea.start();
gamePiece = new piece(10, "white", 20, 135);
}
var gameArea = {
canvas : document.createElement("canvas"),
start : function(){
this.canvas.width = 480;
this.canvas.height = 270;
this.canvas.style.cursor= 'none';
this.context = this.canvas.getContext("2d");
document.body.insertBefore( this.canvas, document.body.childNodes[0]);
this.frameNo = 0;
this.interval = setInterval(updateGame , 10); //for each frame
window.addEventListener('mousemove', function(n){
gameArea.x = n.pageX;
gameArea.y = n.pageY;
});
},
clear : function(){
this.context.clearRect(0,0, this.canvas.width, this.canvas.height);
},
stop : function(){
clearInterval(this.interval);
}
}
function eachInterval(e){
if((gameArea.frameNo / e) % 1 == 0)
return true;
else
return false;
}
//for circle
function piece (radius, color, x, y){
this.radius = radius;
this.speedx = 0;
this.speedy =0;
this.x = x;
this.y = y;
this.update = function(){
pieceContext = gameArea.context;
pieceContext.beginPath();
pieceContext.arc( this.x, this.y, this.radius, 0, 2 * Math.PI);
pieceContext.fillStyle = color;
pieceContext.fill();
}
this.newPlace = function(){
this.x += this.speedx;
this.y += this.speedy;
}
}
//for obstacle
function obstacle (width, height, color, x, y){
this.width = width;
this.height = height;
this.speedx = 0;
this.speedy =0;
this.x = x;
this.y = y;
this.update = function(){
obstacleContext = gameArea.context;
obstacleContext.fillStyle = color;
obstacleContext.fillRect(this.x, this.y, this.width, this.height);
}
this.newPlace = function(){
this.x += this.speedx;
this.y += this.speedy;
}
//check crash
this.crashWith = function(gamePiece){
var collide = true;
var otherleft = this.x;
var otherright = this.x + (this.width);
var othertop = this.y;
var otherbottom = this.y + (this.height);
var circleBottom = gamePiece.y + (gamePiece.radius);
var circleTop = gamePiece.y;
var circleLeft = gamePiece.x;
var circleRight = gamePiece.x + (gamePiece.radius);
if ((circleBottom < othertop) || (circleTop > otherbottom) || (circleRight < otherleft) || (circleLeft > otherright)) {
collide = false;
}
return collide;
}
}
function updateGame(){
var x,y;
for(i=0 ; i<gameObstacle.length ; i++){
if (gameObstacle[i].crashWith(gamePiece)){
gameArea.stop();
return;
}
}
gameArea.clear();
gameArea.frameNo +=1 ;
if(gameArea.frameNo == 1 || eachInterval(150)){
x = gameArea.canvas.width;
y = gameArea.canvas.height - 200;
gameObstacle.push(new obstacle(10, 200, "grey", x, y));
}
for(i=0 ; i<gameObstacle.length ; i++){
gameObstacle[i].x -= 1;
gameObstacle[i].update();
}
gameObstacle.x -= 1;
//giving co ordinates of cursor to game piece
gamePiece.x = gameArea.x;
gamePiece.y = gameArea.y;
gamePiece.update();
gamePiece.newPlace();
}
</script>
</body>
</html>

How to draw multiple array entities on canvas

I want to draw out all of the objects that I have in my zombielist. but I can't get it to work.
var FatZombieWikki = new Image();
FatZombieWikki.src = "FatZombieWikki.png";
var Zombie = function(x, y) {
this.x = x;
this.y = y;
this.Draw = function(ctx) {
ctx.drawImage(FatZombieWikki,200,ZombieY,50,50);
}
this.Update = function(){
if(ZombieY < 900) {
ZombieY += 0.5;
}
}
}
var z = new Zombie(100, 200,);
var zombieList = [];
for (var i = 0; i < 10; i++) {
zombieList.push(new Zombie(40 * i, 100));
}
call your draw function inside loop, after creating object.
DEMO
var ctx = document.getElementById('c').getContext('2d');
var FatZombieWikki = new Image();
FatZombieWikki.src = "//i.stack.imgur.com/ubK40.jpg";
FatZombieWikki.onload = function(){
var zombieList = [];
for (var i = 0; i < 10; i++) {
zombieList.push(new Zombie(40 * i, 30*i));
zombieList[i].draw(ctx);
}
}
var Zombie = function(x, y) {
this.x = x;
this.y = y;
this.draw = function(ctx) {
ctx.drawImage(FatZombieWikki,this.x,this.y,50,50);
}
}
canvas{
border:2px solid #000
}
<canvas id='c' width=500 height=400></canvas>
zombieList.forEach(zombie => zombie.Draw(ctx))

I want to draw one circle on a canvas from an array?

I want to be able to start with draw one circle on my canvas that I push onto an array. This is not working.
function Circle(x, y, r){
this.x = x;
this.y = y;
this.r = r;
}
// create an array
var anArray = [];
// make a circle instance
var aCircle = new Circle(100, 100, 20);
//add it to the array
anArray.push(aCircle);
function drawCircle() {
context.beginPath();
context.arc(anArry[0].x,anArry[0].y,anArry[0].r,0,Math.PI*2,true);
context.closePath();
context.fill();
Code:
<!DOCTYPE HTML>
<html>
<head>
<style>
canvas {
border: 5px solid #999;
background-color: #000000;
}
</style>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.min.js" type="text/javascript"></script>
</head>
<body>
<canvas id="myCanvas" width="450" height="610" style="border:3px solid #c3c3c3;">
</canvas>
<script>
var context;
var rightKey = false;
var leftKey = false;
var upKey = false;
var downKey = false;
var block_x;
var block_y;
var block_h = 15;
var block_w = 15;
var imageObj = new Image();
imageObj.src = 'spaceShip.jpg';
function Circle(x, y, r){
this.x = x;
this.y = y;
this.r = r;
}
// create an array
var anArray = [];
// make a circle instance
var aCircle = new Circle(100, 100, 20);
//add it to the array
anArray.push(aCircle);
function drawCircle() {
context.beginPath();
context.arc(anArry[0].x,anArry[0].y,anArry[0].r,0,Math.PI*2,true);
context.closePath();
context.fill();
/*
for(var i=0; i<numCircle; i++) {
canvasContext.fillStyle='#123321;'
drawCircle(anArry[0].x,anArry[0].y,anArry[0].r,canvasContext);
}
*/
}
function drawScore() {
context.fillStyle = "red";
context.font = "bold 16px Arial";
context.fillText("1000", 5, 15);
context.fillStyle = "red";
context.font = "bold 16px Arial";
context.fillText("14500", 200, 15);
}
function drawExtraLives() {
context.drawImage(imageObj, 45, 3);
context.drawImage(imageObj, 60, 3);
context.drawImage(imageObj, 75, 3);
}
function init() {
context = $('#myCanvas')[0].getContext('2d');
WIDTH = $('#myCanvas').width();
HEIGHT = $('#myCanvas').height();
block_x = WIDTH / 2 - 15;
block_y = HEIGHT / 2 - 15;
setInterval('draw()', 25);
}
function clearCanvas() {
context.clearRect(0,0,WIDTH,HEIGHT);
}
function rect(x,y,w,h) {
context.beginPath();
context.rect(x,y,w,h);
context.endPath();
}
function draw() {
clearCanvas();
if (rightKey)
block_x += 5;
else if (leftKey)
block_x -= 5;
if (upKey)
block_y -= 5;
else if (downKey)
block_y += 5;
if (block_x <= 0)
block_x = 0;
if ((block_x + block_w) >= WIDTH)
block_x = WIDTH - block_w;
if (block_y <= 530)
block_y = 532;
if ((block_y + block_h) >= HEIGHT)
block_y = HEIGHT - block_h;
//all items that have to be redrawn go here.
drawScore();
drawExtraLives();
//drawCircle();
drawGameBottomLine();
context.drawImage(imageObj, block_x,block_y);
//context.fillRect(block_x,block_y,block_w,block_h);
}
function onKeyDown(evt) {
if (evt.keyCode == 39) rightKey = true;
else if (evt.keyCode == 37) leftKey = true;
if (evt.keyCode == 38) upKey = true;
else if (evt.keyCode == 40) downKey = true;
}
function onKeyUp(evt) {
if (evt.keyCode == 39) rightKey = false;
else if (evt.keyCode == 37) leftKey = false;
if (evt.keyCode == 38) upKey = false;
else if (evt.keyCode == 40) downKey = false;
}
function drawGameBottomLine() {
context.beginPath();
context.moveTo(0,530);
context.lineTo(450,530);
context.strokeStyle = 'yellow';
context.stroke();
}
$(document).keydown(onKeyDown);
$(document).keyup(onKeyUp);
init(); //This method sets up the init for the whole game (all things that have to be redraw will be in the draw method.
</script>
</body>
</html>
All code here
<!DOCTYPE HTML>
<html>
<head>
<style>
canvas {
border: 5px solid #999;
background-color: #000000;
}
</style>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.min.js" type="text/javascript"></script>
</head>
<body>
<canvas id="myCanvas" width="450" height="610" style="border:3px solid #c3c3c3;">
</canvas>
<script>
var context;
var rightKey = false;
var leftKey = false;
var upKey = false;
var downKey = false;
var block_x;
var block_y;
var block_h = 15;
var block_w = 15;
var shipCnt = 4; //keeps track of the number of ships that the player has left
var levelCnt = 1; //keeps track of which level the player is on so that the correct colored mushroom is displayed
var PLAYERNUM = 'PLAYER 1';
var READY = 'READY!'; //Used to display on the start of every new life
var imageObj = new Image();
imageObj.src = 'spaceShip.jpg';
function Circle(x, y, r){
this.x = x;
this.y = y;
this.r = r;
}
// create an array
var anArray = [];
// make a circle instance
var aCircle = new Circle(100, 100, 20);
//add it to the array
anArray.push(aCircle);
function drawCircle() {
context.beginPath();
context.arc(anArray[0].x, anArray[0].y, anArray[0].r, 0, Math.PI*2, false);
context.fillStyle = 'yellow';
context.fill();
//context.closePath();
/*
for(var i=0; i<numCircle; i++) {
canvasContext.fillStyle='#123321;'
drawCircle(anArry[0].x,anArry[0].y,anArry[0].r,canvasContext);
}
*/
}
function drawScore() {
context.fillStyle = "red";
context.font = "bold 16px Arial";
context.fillText("1000", 5, 15);
context.fillStyle = "red";
context.font = "bold 16px Arial";
context.fillText("14500", 200, 15);
}
function drawExtraLives() {
context.drawImage(imageObj, 45, 3);
context.drawImage(imageObj, 60, 3);
context.drawImage(imageObj, 75, 3);
}
function drawPlayerOne() {
context.fillStyle = "yellow";
context.font = "bold 20px Arial";
context.fillText(PLAYERNUM, 175, 260);
}
function drawReady() {
context.fillStyle = "yellow";
context.font = "bold 20px Arial";
context.fillText(READY, 185, 280);
}
function init() {
context = $('#myCanvas')[0].getContext('2d');
WIDTH = $('#myCanvas').width();
HEIGHT = $('#myCanvas').height();
block_x = WIDTH / 2 - 15;
block_y = HEIGHT / 2 - 15;
setInterval('draw()', 25);
}
function clearCanvas() {
context.clearRect(0,0,WIDTH,HEIGHT);
}
function rect(x,y,w,h) {
context.beginPath();
context.rect(x,y,w,h);
context.endPath();
}
function onKeyDown(evt) {
if (evt.keyCode == 39) rightKey = true;
else if (evt.keyCode == 37) leftKey = true;
if (evt.keyCode == 38) upKey = true;
else if (evt.keyCode == 40) downKey = true;
}
function onKeyUp(evt) {
if (evt.keyCode == 39) rightKey = false;
else if (evt.keyCode == 37) leftKey = false;
if (evt.keyCode == 38) upKey = false;
else if (evt.keyCode == 40) downKey = false;
}
function drawGameBottomLine() {
context.beginPath();
context.moveTo(0,530);
context.lineTo(450,530);
context.strokeStyle = 'yellow';
context.stroke();
}
function draw() {
clearCanvas();
if (rightKey)
block_x += 5;
else if (leftKey)
block_x -= 5;
if (upKey)
block_y -= 5;
else if (downKey)
block_y += 5;
if (block_x <= 0)
block_x = 0;
if ((block_x + block_w) >= WIDTH)
block_x = WIDTH - block_w;
if (block_y <= 530)
block_y = 532;
if ((block_y + block_h) >= HEIGHT)
block_y = HEIGHT - block_h;
//all items that have to be redrawn go here.
drawScore();
drawExtraLives();
drawPlayerOne();
drawReady();
//drawCircle();
drawGameBottomLine();
context.drawImage(imageObj, block_x,block_y);
//context.fillRect(block_x,block_y,block_w,block_h);
}
$(document).keydown(onKeyDown);
$(document).keyup(onKeyUp);
init(); //This method sets up the init for the whole game (all things that have to be redraw will be in the draw method.
</script>
</body>
</html>
You have a syntax error in your drawCircle() method (anArry<>anArray), here is updated code which worked for me:
function drawCircle() {
context.beginPath();
context.arc(anArray[0].x, anArray[0].y, anArray[0].r, 0, Math.PI*2, false);
context.fillStyle = 'yellow';
context.fill();
//context.closePath();
/*
for(var i=0; i<numCircle; i++) {
canvasContext.fillStyle='#123321;'
drawCircle(anArry[0].x,anArry[0].y,anArry[0].r,canvasContext);
}
*/
}
also it is better to put your script into page <head> and call init() as <body onload="init()"> to be sure all resources are loaded when your script runs. (alternatively window.onload = init;)
Nice tutorials where you can edit & run examples is here: http://www.html5canvastutorials.com/tutorials/html5-canvas-circles/

How to create mouseover highlight box in html 5?

If I have a 600 by 400 grid, with 10 by 10 pixel squares like this:
/**
* draws grid to screen
*/
function drawgrid(context)
{
for(var x = 0.5; x < 600; x += 10)
{
context.moveTo(x, 0);
context.lineTo(x, 400);
}
for(var y = 0.5; y < 400; y += 10)
{
context.moveTo(0, y);
context.lineTo(600, y);
}
context.strokeStyle = "#eee";
context.stroke();
}
/**
* Creates a canvas element, loads images, adds events, and draws the canvas for the first time.
*/
function prepareCanvas()
{
var context = document.getElementById('canvas').getContext("2d");
drawgrid(context);
}
How would I mouseover the individual squares and highlight the square that the mouse is hovering over. Like make a red box highlighting the grid square the mouse is over.
See code below. Adjust coordinates for event
<body>
<canvas id=canvas height=400 width=600
onmousemove="over()" style="cursor:crosshair">
</canvas>
</body>
<script type="text/javascript">
<!--
var grid;
function prepareCanvasGrid()
{
var cnv = document.getElementById('canvas');
grid = new CanvasGrid(cnv.getContext("2d"),cnv.offsetLeft, cnv.offsetTop);
}
function CanvasGrid(context,x,y) {
this.sq = [];
this.dirty = [];
this.ctx = context;
this.x = x;
this.y = y;
this.init = function(){
for(var x = 0.5; x < 600; x += 50) {
for(var y = 0.5; y < 400; y += 50) {
var s = new square(x,y, context);
this.sq.push(s);
}
}
}
this.draw = function(){
this.ctx.clearRect(0,0,600,400);
for(var i=0; i < this.sq.length; i++)
this.sq[i].draw();
}
this.clean = function(){
for(var i=0; i < this.dirty.length; i++)
this.dirty[i].draw();
this.dirty = [];
}
this.over = function(ex,ey){
ex = ex - this.x;
ey = ey - this.y;
for(var i=0; i < this.sq.length; i++) {
if(this.sq[i].eleAtPoint(ex,ey)){
this.clean(); // clean up
this.dirty.push(this.sq[i]);
this.sq[i].over();
break;
}
}
}
this.init();
this.draw();
}
function square(x,y, ctx){
this.ctx = ctx;
this.x = x;
this.y = y;
this.h = 50;
this.w = 50;
this.draw = function(){
this.ctx.strokeStyle = "#eee";
this.ctx.strokeRect(this.x, this.y, this.w, this.w);
this.ctx.fillStyle = "#fff";
this.ctx.fillRect(this.x, this.y, this.w, this.w);
}
this.over = function() {
this.ctx.fillStyle = "red";
this.ctx.fillRect(this.x, this.y, this.w, this.w);
}
this.eleAtPoint = function(ex,ey){
if(ex < this.x + this.w && ex > this.x
&& ey > this.y && ey < this.y + this.h)
return true;
return false;
}
}
function over(){
var e = window.event;
grid.over(e.clientX ,e.clientY);
}
prepareCanvasGrid();
//-->
</script>
Updated code for better performance
Just to add to hungryMind's answer, if you don't want any boxes to remain highlighted when the mouse is no longer over the canvas, add these two things:
1) An else if
this.over = function(ex,ey){
ex = ex - this.x;
ey = ey - this.y;
for(var i=0; i < this.sq.length; i++) {
if(this.sq[i].eleAtPoint(ex,ey)){
this.clean(); // clean up
this.dirty.push(this.sq[i]);
this.sq[i].over();
break;
} else if (!this.sq[i].eleAtPoint(ex,ey)) {
this.sq[i].off();
}
}
}
2) A square off() method:
this.off = function() {
this.draw();
}

Categories

Resources