简单的碰撞小测试
var cvs = document.getElementById('box');
var ctx = cvs.getContext('2d');
var x=0, y=0,h=true,k=true;
setInterval(function(){
ctx.clearRect(0,0,cvs.width,cvs.height);
if(h){
x++;
if(x>=(cvs.width-50)){
h=false;
}
}else{
x--;
if(x<0){
h=true;
}
}
if(k){
y++;
if(y>=(cvs.height-50)){
k=false;
}
}else{
y--;
if(y<0){
k=true;
}
}
ctx.beginPath();
ctx.fillStyle='blue';
ctx.fillRect(x,y,50,50)
},5)
*{
margin: 0;
padding: 0;
}
#box{
display: block;
border: 1px solid red;
margin: 20px auto;
}
刮刮卡效果 小demo
JavaScript部分
var cvs = document.getElementById('box');
var ctx = cvs.getContext('2d');
var con = document.getElementById('con');
ctx.beginPath();
ctx.fillStyle='#ccc';
ctx.fillRect(0,0,cvs.width,cvs.height);
ctx.closePath();
var arr = ['一等奖','劳斯莱斯幻影','1个亿','海景别墅','一栋大房子']
var i =Math.floor(Math.random()*arr.length)
con.innerHTML=arr[i];
cvs.onmousedown=function(){
document.onmousemove=function(e){
ctx.clearRect(e.clientX-cvs.offsetLeft,e.clientY-cvs.offsetTop,20,20,)
}
document.onmouseup=function(){
document.onmousemove=null;
}
}
css部分
*{
margin: 0;
padding: 0;
}
#box{
border: 1px solid red;
position: absolute;
z-index: 999;
}
#con{
width: 200px;
height: 100px;
position: absolute;
line-height: 100px;
text-align: center;
font-size: 26px;
letter-spacing: 3px;
}
html部分
<canvas id="box" width="200" height="100"></canvas>
<div id="con">一等奖</div>
画板 canvas 小demo
JavaScript部分
var cvs = document.getElementById('box');
var ctx = cvs.getContext('2d');
var btn1 = document.getElementById('btn1');
var btn2 = document.getElementById('btn2');
var btn3 = document.getElementById('btn3');
btn1.onclick = function(){
cvs.onmousedown = function(e){
ctx.beginPath();
ctx.moveTo(e.clientX-cvs.offsetLeft,e.clientY-cvs.offsetTop)
document.onmousemove = function(e){
ctx.lineTo(e.clientX-cvs.offsetLeft,e.clientY-cvs.offsetTop);
ctx.strokeStyle= 'green';
ctx.lineWidth=2;
ctx.stroke();
}
document.onmouseup = function(){
document.onmousemove= null;
document.onmousedown= null;
}
}
}
/*橡皮擦*/
btn2.onclick = function(){
cvs.onmousedown = function(e){
document.onmousemove = function(e){
/*获取鼠标坐标 然后还要给橡皮擦定义宽高 大小*/
ctx.clearRect(e.clientX-cvs.offsetLeft,e.clientY-cvs.offsetTop,20,20)
}
document.onmouseup = function(){
/*清除移动*/
document.onmousedown = null;
document.onmousemove = null;
}
}
}
btn3.onclick = function(){
ctx.clearRect(0,0,cvs.width,cvs.height)
}
css部分
*{
margin: 0;
padding: 0;
}
#box{
display: block;
border: none;
margin: 30px auto;
border-radius:10px;
box-shadow: 8px 8px 15px ;
}
#box1{
height: 50px;
width: 100%;
display: flex;
align-content: center;
justify-content: center;
}
button{
height: 40px;
width: 100px;
border: none;
border-radius: 5px;
box-shadow: 3px 3px 8px;
margin: 0 10px;
background: green;
color: #FFFFFF;
font-size: 18px;
font-family: "宋体";
}
html部分
<canvas id="box" width="600" height="400"></canvas>
<div id="box1">
<button id="btn1">画画</button>
<button id="btn2">橡皮擦</button>
<button id="btn3">重画</button>
</div>
研究canvas做的一些小demo 快速入门