Brick Breaker guide
Build a Brick Breaker Game in JavaScript with Canvas
This tutorial builds a small paddle-and-ball game with plain JavaScript and the browser Canvas API. It is deliberately independent of Phaser: one HTML file draws the playfield, updates the ball, detects brick hits, tracks lives and score, and lets the player restart. The example is a teaching baseline, not a copy of the BreakBreaker.online game.
What the example includes
The complete sample is a single HTML file with a canvas, text score and lives, an accessible status message, keyboard and pointer movement, launch and restart buttons, wall and paddle rebounds, brick collision, and game-over and win states. Save it as brick-breaker.html and open it in a modern browser. No package or image asset is required.
The Canvas API supplies a drawing surface, not game rules. JavaScript owns the game state and updates it on animation frames.
Complete single-file JavaScript Canvas example
Copy the whole document below into a new file. The canvas has a fixed logical size but scales to the available width; pointer coordinates are converted back to that logical coordinate space.
Show the complete HTML, CSS, and JavaScript
<!doctype html>
<html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Canvas Brick Breaker</title>
<style>body{margin:0;padding:1rem;background:#101827;color:#fff;font:16px system-ui}main{width:min(100%,32rem);margin:auto}canvas{display:block;width:100%;height:auto;background:#080d20;touch-action:none}.row{display:flex;gap:1rem;flex-wrap:wrap;margin:.75rem 0}button{padding:.6rem 1rem;font:inherit}</style></head>
<body><main><h1>Canvas Brick Breaker</h1><p>Move with arrows or A/D; move the pointer over the canvas; press Space, click, or tap to launch.</p>
<div class="row"><span id="score">Score: 0</span><span id="lives">Lives: 3</span><span id="status" role="status" aria-live="polite">Ready</span></div>
<canvas id="game" width="480" height="520" tabindex="0" aria-label="Brick Breaker playfield. Arrow keys or A and D move the paddle; Space launches."></canvas>
<div class="row"><button id="launch">Launch</button><button id="restart">Restart game</button></div></main>
<script>
(() => {
const c=document.getElementById('game'),x=c.getContext('2d'),W=c.width,H=c.height;
const scoreText=document.getElementById('score'), livesText=document.getElementById('lives'), status=document.getElementById('status');
const p={x:198,y:486,w:84,h:12,speed:6}, b={x:240,y:470,r:7,vx:3,vy:-4};
const keys={left:false,right:false}; let score=0,lives=3,launched=false,ended=false,bricks=[];
function show(message){scoreText.textContent='Score: '+score;livesText.textContent='Lives: '+lives;status.textContent=message;}
function makeBricks(){bricks=[];const cols=8,rows=5,gap=5,edge=24,bw=(W-edge*2-gap*(cols-1))/cols;
for(let r=0;r<rows;r++)for(let col=0;col<cols;col++)bricks.push({x:edge+col*(bw+gap),y:48+r*23,w:bw,h:17,alive:true,color:['#22d3ee','#38bdf8','#818cf8','#c084fc','#f472b6'][r]});}
function resetBall(){b.x=p.x+p.w/2;b.y=p.y-b.r-1;b.vx=3;b.vy=-4;launched=false;}
function reset(){score=0;lives=3;ended=false;p.x=W/2-p.w/2;makeBricks();resetBall();show('Ready to launch');}
function start(){if(ended)return;launched=true;show('Playing');c.focus();}
function point(e){const r=c.getBoundingClientRect();return(e.clientX-r.left)*W/r.width;}
c.addEventListener('pointermove',e=>{p.x=Math.max(0,Math.min(W-p.w,point(e)-p.w/2));if(!launched)resetBall();});
c.addEventListener('pointerdown',start);document.getElementById('launch').addEventListener('click',start);document.getElementById('restart').addEventListener('click',reset);
window.addEventListener('keydown',e=>{if(['ArrowLeft','ArrowRight',' '].includes(e.key))e.preventDefault();if(e.key==='ArrowLeft'||e.key.toLowerCase()==='a')keys.left=true;if(e.key==='ArrowRight'||e.key.toLowerCase()==='d')keys.right=true;if(e.key===' ')start();});
window.addEventListener('keyup',e=>{if(e.key==='ArrowLeft'||e.key.toLowerCase()==='a')keys.left=false;if(e.key==='ArrowRight'||e.key.toLowerCase()==='d')keys.right=false;});
function hit(q,r){const nx=Math.max(r.x,Math.min(q.x,r.x+r.w)),ny=Math.max(r.y,Math.min(q.y,r.y+r.h)),dx=q.x-nx,dy=q.y-ny;return dx*dx+dy*dy<q.r*q.r;}
function update(dt){if(ended)return;const s=Math.min(dt,32)/16.667;if(keys.left)p.x-=p.speed*s;if(keys.right)p.x+=p.speed*s;p.x=Math.max(0,Math.min(W-p.w,p.x));if(!launched){resetBall();return;}
b.x+=b.vx*s;b.y+=b.vy*s;if(b.x-b.r<=0||b.x+b.r>=W)b.vx*=-1;if(b.y-b.r<=0)b.vy=Math.abs(b.vy);
if(b.vy>0&&hit(b,p)){const off=(b.x-(p.x+p.w/2))/(p.w/2);b.vx=off*4;b.vy=-Math.max(2.5,Math.sqrt(25-b.vx*b.vx));b.y=p.y-b.r-1;}
for(const q of bricks)if(q.alive&&b.vy<0&&hit(b,q)){q.alive=false;b.vy*=-1;score+=10;show('Playing');break;}
if(b.y-b.r>H){lives--;if(lives<=0){ended=true;show('Game over');}else{resetBall();show('Life lost. Press Space or tap to relaunch');}}
if(!bricks.some(q=>q.alive)){ended=true;show('All bricks cleared. You win!');}}
function draw(){x.clearRect(0,0,W,H);for(const q of bricks)if(q.alive){x.fillStyle=q.color;x.fillRect(q.x,q.y,q.w,q.h);}x.fillStyle='#f8fafc';x.fillRect(p.x,p.y,p.w,p.h);x.beginPath();x.arc(b.x,b.y,b.r,0,Math.PI*2);x.fillStyle='#fbbf24';x.fill();if(!launched&&!ended){x.fillStyle='#cbd5e1';x.font='15px system-ui';x.textAlign='center';x.fillText('Press Space or tap to launch',W/2,H-70);}}
let last=0;function frame(now){update(now-last||16.667);draw();last=now;requestAnimationFrame(frame);}reset();requestAnimationFrame(frame);
})();
</script></body></html>How the important pieces work
Separate game state from drawing
The ball, paddle, score, lives, and brick array form the state. The update function moves the ball and handles collisions; draw clears and paints the current state. Keeping these jobs separate makes the code easier to change.
Check circle-to-rectangle contact
The overlap helper finds the closest point on a rectangle to the ball center and checks whether that point is inside the ball’s radius. For a small teaching example, a brick hit reverses vertical movement and removes the block. A larger game may need a more exact side-of-impact calculation to handle corners.
Reset the full state
A missed ball consumes a life and places a new ball at the paddle. When lives reach zero, the game stops updating. Restart restores score, lives, bricks, ball, and end state together.
Ideas for extending the game
- Give some bricks more than one hit point and change their appearance when damaged.
- Add a pause state that stops simulation updates while keeping the playfield visible.
- Store a high score only after explaining local browser storage and how clearing site data affects it.
- Use a fixed timestep if you need more consistent physics across devices.
For comparison, our actual Brick Breaker game has five levels and selectable difficulty. Its controls are described in the player guide; the code sample above is an independent tutorial example.
Frequently asked questions
Does this example use a game library?
No. It uses JavaScript and the browser Canvas 2D API.
Is it the same code as the website game?
No. This is a separate educational example and does not reproduce the site game’s source.
Why use requestAnimationFrame?
It schedules drawing with browser rendering. The sample scales movement using elapsed time and caps large frame gaps to avoid sudden jumps after a pause.
Play our independent Brick Breaker game
Want a hands-on paddle-and-ball round? Open our game on the homepage. This independent site game is not an official product from any company mentioned here.