随着鼠标的移动旋转箭头.
requestAnimationFrame
在 requestAnimationFrame 之前我们可以用 setInterval 来实现动画的循环:
- function drawFrame(){
- ball.x+=1;
- ball.draw(context);
- }
- window.setInterval(drawFrame,1000/60)
而 html5 中增加了 window.requestAnimationFrame, 它接收一个回调函数, 确保在重绘前执行该函数, 第二个参数可以指定一个 html 元素作为动画的执行区域. 可以这样调用:
- (function drawFrame(){
- window.requestAnimationFrame(drawFrame,canvas);
- //...
- }());
旋转:
旋转的根本在于求出鼠标位置相对于箭头中心坐标的角度:
求出 dy 的对角就能确定旋转的角度, 而 dy 和 dx 构成了 tan, 可以通过反正切函数得到, JavaScript 提供了两个反正切函数, 一个是 Math.atan, 一个是 Math.atan2, 区别如下.
atan 接收一个参数, 得到弧度, atan2 接收两个参数, 分别是对边 y 和底边 x.
于是得到代码:
- window.onload=function(){
- var canvas=document.getElementById('canvas'),
- context=canvas.getContext('2d'),
- mouse=utils.captureMouse(canvas),
- arrow=new Arrow();
- var arrow1=new Arrow();
- arrow.x=canvas.width/3;
- arrow.y=canvas.height/2;
- arrow1.x=canvas.width/1.5;
- arrow1.y=canvas.height/2;
- (function drawFrame(){
- window.requestAnimationFrame(drawFrame,canvas);
- context.clearRect(0, 0, canvas.width, canvas.height)
- var dx=mouse.x-arrow.x;
- dy=mouse.y-arrow.y;
- arrow.rotation=Math.atan2(dy,dx);
- arrow.draw(context);
- var dx1=mouse.x-arrow1.x;
- dy1=mouse.y-arrow1.y;
- arrow1.rotation=-Math.atan2(dy,dx);
- arrow1.draw(context);
- }());
- }
- captureMouse:
- window.utils.captureMouse = function (element) {
- var mouse = {x: 0, y: 0, event: null},
- body_scrollLeft = document.body.scrollLeft,
- element_scrollLeft = document.documentElement.scrollLeft,
- body_scrollTop = document.body.scrollTop,
- element_scrollTop = document.documentElement.scrollTop,
- offsetLeft = element.offsetLeft,
- offsetTop = element.offsetTop;
- element.addEventListener('mousemove', function (event) {
- var x, y;
- if (event.pageX || event.pageY) {
- x = event.pageX;
- y = event.pageY;
- } else {
- x = event.clientX + body_scrollLeft + element_scrollLeft;
- y = event.clientY + body_scrollTop + element_scrollTop;
- }
- x -= offsetLeft;
- y -= offsetTop;
- mouse.x = x;
- mouse.y = y;
- mouse.event = event;
- }, false);
- return mouse;
- };
- View Code
箭头:
- function Arrow () {
- this.x = 0;
- this.y = 0;
- this.color = "#ffff00";
- this.rotation = 0;
- }
- Arrow.prototype.draw = function (context) {
- context.save();
- context.translate(this.x, this.y);
- context.rotate(this.rotation);
- context.lineWidth = 2;
- context.fillStyle = this.color;
- context.beginPath();
- context.moveTo(-50, -25);
- context.lineTo(0, -25);
- context.lineTo(0, -50);
- context.lineTo(50, 0);
- context.lineTo(0, 50);
- context.lineTo(0, 25);
- context.lineTo(-50, 25);
- context.lineTo(-50, -25);
- context.closePath();// 完成轨迹
- context.fill();// 填充
- context.stroke();// 画出边线
- context.restore();// 使得 canvas 原点回到 save 之前
- };
- View Code
来源: https://www.cnblogs.com/stoneniqiu/p/9576385.html