canvas画箭头并跟随鼠标转动
代码如下:
<head> <meta charset="utf-8" /> <title></title> <!-- <script src="js/tools.js"></script> <script src="js/arrow.js"></script> --> <script> //将tools定义为window对象的属性,该属性的值是一个对象 window.tools = {}; //获取鼠标指针位置 window.tools.getMouse = function (element) { //定义一个mouse的对象 var mouse = { x: 0, y: 0 }; //为传入的元素添加mousemove事件 element.addEventListener("mousemove", function (e) { var x, y; //在IE中,event对象是作为window对象的一个属性存在 var e = e || window.event; //获取鼠标指针当前位置,并作兼容处理 //兼容Firefox、chrome、IE9及以上 if (e.pageX || e.pageY) { x = e.pageX; y = e.pageY; } //兼容IE8及以下,以及混杂模式下的Chrome和Safari else { x = e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft; y = e.clientY + document.body.scrollTop + document.documentElement.scrollTop; } //将当前的坐标值减去canvas元素的偏移位置,则x、y为鼠标指针在canvas中的相对坐标值 x -= element.offsetLeft; y -= element.offsetTop; mouse.x = x; mouse.y = y; }) //返回值为mouse对象 return mouse; } function Arrow(x,y,color,angle) { //箭头中心的横坐标,默认值为0 this.x = x || 0; //箭头中心的纵坐标,默认值为0 this.y = y || 0; //颜色,默认值为“#FF0099” this.color = color || "#FF0099"; //旋转角度,默认值为0 this.angle = angle || 0; } Arrow.prototype = { stroke: function (cxt) { cxt.save(); cxt.translate(this.x, this.y); cxt.rotate(this.angle); cxt.strokeStyle = this.color; cxt.beginPath(); cxt.moveTo(-20, -10); cxt.lineTo(0, -10); cxt.lineTo(0, -20); cxt.lineTo(20, 0); cxt.lineTo(0, 20); cxt.lineTo(0, 10); cxt.lineTo(-20, 10); cxt.closePath(); cxt.stroke(); cxt.restore(); }, fill: function (cxt) { cxt.save(); cxt.translate(this.x, this.y); cxt.rotate(this.angle); cxt.fillStyle = this.color; cxt.beginPath(); cxt.moveTo(-20, -10); cxt.lineTo(0, -10); cxt.lineTo(0, -20); cxt.lineTo(20, 0); cxt.lineTo(0, 20); cxt.lineTo(0, 10); cxt.lineTo(-20, 10); cxt.closePath(); cxt.fill(); cxt.restore(); } }; function $$(id) { return document.getElementById(id); } window.onload = function () { var cnv = $$("canvas"); var cxt = cnv.getContext("2d"); //实例化一个箭头,某中心坐标为画布中心坐标 var arrow = new Arrow(cnv.width / 2, cnv.height / 2); //获取鼠标指针坐标 var mouse = tools.getMouse(cnv); (function drawFrame() { window.requestAnimationFrame(drawFrame, cnv); cxt.clearRect(0, 0, cnv.width, cnv.height); var dx = mouse.x - cnv.width / 2; var dy = mouse.y - cnv.height / 2; //使用Math.atan2()函数计算出鼠标指针与箭头中心的夹角 arrow.angle = Math.atan2(dy, dx); arrow.fill(cxt); })(); } </script> </head> <body> <canvas id="canvas" width="200" height="150" style="border:1px solid silver;"></canvas> </body> </html>
查看更多关于canvas画箭头并跟随鼠标转动的详细内容...
声明:本文来自网络,不代表【好得很程序员自学网】立场,转载请注明出处:http://www.haodehen.cn/did31566