canvas+javascript初级应用
来源于html5+javascript动画基础这本书。重原理轻代码,个人感觉比较适合了解了js基本,但是又无法独立写东西的同学食用。css部分就没上了。。。因为我也没怎么写样式,只是单纯以实现效果为主。
<body>
<h1>Big-Brothers<p id="txt"></p></h1>
<canvas id="canvas" width="1000px" height="600px"></canvas>
<p id="txt1"></p>
<p id="txt2"></p>
<p id="txt3"></p>
<script>
var body=document.getElementsByTagName("body"),
canvas=document.getElementById("canvas"),
ctx=canvas.getContext("2d");
var Arrow=function(){
this.x=0;
this.y=0;
this.color="gray";
this.rotation=0;
}
Arrow.prototype.drawArrow=function(ctx){
ctx.save();
ctx.translate(this.x,this.y);
ctx.rotate(this.rotation);
ctx.beginPath();
ctx.fillStyle=this.color;
ctx.lineWidth=2;
ctx.moveTo(-50,-25);
ctx.lineTo(0,-25);
ctx.lineTo(0,-50);
ctx.lineTo(50,0);
ctx.lineTo(0,50);
ctx.lineTo(0,25);
ctx.lineTo(-50,25);
ctx.closePath();
ctx.fill();//填充
ctx.stroke();//画线
ctx.restore();
}
// arrow.drawArrow(ctx);
//鼠标捕捉函数,el代表的区域,在哪个区域对鼠标进行捕捉
//var Mouse=function(){
// this.x=0;
// this.y=0;
//}
var catchMouse=function(el){
var mouse={
x:0,y:0
}
//浏览器检测
el.addEventListener('mousemove',function(event){
var x,y;
//浏览器检测
if(event.pageX||event.pageY){
x=event.pageX;
y=event.pageY;
}else{
//获取鼠标到窗口边缘的位置
x=event.clientX+document.body.scrollLeft+document.documentElement.scrollLeft;
y=event.clientY+document.body.scrollTop+document.documentElement.scrollTop;
}
document.getElementById("txt1").innerHTML=x+":"+y;
//获取el元素边框到窗口边缘的位置,鼠标位置减去el位置,就为鼠标到el边缘的位置
x=x-el.offsetLeft;
y=y-el.offsetTop;
document.getElementById("txt2").innerHTML=el.offsetLeft+":"+el.offsetTop;
mouse.x=x;
mouse.y=y;
document.getElementById("txt").innerHTML=mouse.x+":"+mouse.y;
},false);
return mouse;
}
//当鼠标进入canvas区域之后,就对鼠标位置进行捕捉
//canvas.addEventListener('mousemove',function(){
// document.getElementById("txt").innerHTML=mouse.x+":"+mouse.y;
//})
//动画绘制
//建立一个arrow对象
var arrow=new Arrow();
arrow.x=canvas.width/2;
arrow.y=canvas.height/2;
mouse=catchMouse(canvas);
//var mouse=new Mouse();
//alert(mouse.x+":"+mouse.y);
var drawFrame=function(){
//浏览器检测
/*if(!window.requestAnimationFrame){
window.requestAnimationFrame=(window.mozRequestAnimationFrame()||window.webkitRequestAnimationFrame
||window.oRequestAnimationFrame||window.msRequestAnimationFrame
||function(callback){
return window.setTimeout(callback,1000/60);
})
}*/
//window.requestAnimationFrame=(drawFrame);//自身调用
ctx.clearRect(0,0,canvas.width,canvas.height);
//mouse=catchMouse(canvas);
//alert(mouse.x+":"+mouse.y);
var dx=mouse.x-arrow.x,
dy=mouse.y-arrow.y;
//alert(mouse.x+":"+mouse.y)
arrow.rotation=Math.atan2(dy,dx);//三角函数计算此时鼠标与箭头之间的弧度值,即箭头旋转的弧度
document.getElementById("txt3").innerHTML=arrow.rotation;
arrow.drawArrow(ctx);
ctx.beginPath();
ctx.strokeStyle="gray"
ctx.moveTo(mouse.x,mouse.y);
ctx.lineTo(arrow.x,arrow.y);
ctx.stroke();
};
canvas.addEventListener('mousemove',drawFrame);
</script>