<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Break the Bricks</title>
<style>
#layer_background{
z-index:0;
background-color:#CACACA;
};
#layer_ui{
z-index:1;
};
#box{
width: 400px;
height: 500px;
position: relative;
border: 2px solid black;
}
canvas { position: absolute; }
</style>
</head>
<body>
<div id="box">
<canvas id="layer_background" width="400px" height="500px"></canvas>
<canvas id="layer_ui" width="400px" height="500px"></canvas>
</div>
</body>
<script>
var canvas_background = document.getElementById('layer_background');
var ctx_background = canvas_background.getContext('2d');
var canvas = document.getElementById('layer_ui');
var ctx = canvas.getContext('2d');
//绘制滑动块
var slidingBlock = {
x:180,
y:400,
width:40,
height:5,
color:"yellow",
draw:function(){
ctx.fillStyle = this.color;
ctx.fillRect(this.x-this.width/2,this.y,this.width,this.height);
}
};
slidingBlock.draw();
drawDeadLine();
//绘制底线
function drawDeadLine(){
ctx_background.strokeStyle = "red";
ctx_background.beginPath();
ctx_background.moveTo(0,slidingBlock.y+slidingBlock.height);
ctx_background.lineTo(canvas.width,slidingBlock.y+slidingBlock.height);
ctx_background.stroke();
}
var blocks = {
row :10, //行
column : 20, //列
blockHeight : 10, //小方块高度
draw:function(skipNumber){
var blockWidth = canvas_background.width/this.column;
for(var i = 0;i<this.column;i++){
for(var j = 0;j<this.row;j++){
if(i*j!=skipNumber){
var x = i*blockWidth;//小方块x的起点
var y = j*this.blockHeight; //小方块y的起点
ctx_background.strokeStyle = "green";
ctx_background.strokeRect(x, y, blockWidth, this.blockHeight);
}
}
}
}
}
blocks.draw(-1);
//绘制移动球
var ball = {
x:200,
y:300,
vx:2,
vy:2,
radius:5,
color:"red",
draw:function(){
ctx.beginPath();
ctx.arc(this.x,this.y,this.radius,0,Math.PI*2,false);
ctx.closePath();
ctx.fillStyle = this.color;
ctx.fill();
},
};
ball.draw();
window.requestAnimationFrame(moveBall);
//自动移动球
function moveBall(){
clear();
ball.draw();
slidingBlock.draw();
ball.x-=ball.vx;
ball.y-=ball.vy;
if(ball.x<0 || ball.x>canvas.width){
ball.vx=-ball.vx;
};
if(ball.y<0 || ball.y>slidingBlock.y-ball.radius){
ball.vy=-ball.vy;
};
var ball_x_index = (ball.y)/(blocks.blockHeight);
var ball_y_index = (ball.x)/(canvas_background.width/blocks.column);
blocks.draw(Math.floor(ball_x_index*ball_y_index));
window.requestAnimationFrame(moveBall);
}
function clear(){
canvas.height = canvas.height;
}
//鼠标移动滑块
canvas.addEventListener('mousemove',function(e){
clear();
slidingBlock.x = e.clientX;
slidingBlock.draw();
});
</script>
</html>