鼠标移动刻度线,刻度标识
这两天项目需要一个优先级刻度线,并且带鼠标拖动 值变换。度娘了下,发现没有符合要求的,想想自己写了一个,放在这,万一以后还用的着呢!
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>滑动刻度线</title> </head> <body onload="init()"> <div> <canvas id="scaleLine" width=450 height=60 style="border:1px solid grey;"></canvas> </div> <script> var myCanvas = document.getElementById("scaleLine"), ctx = myCanvas.getContext("2d"); var w = 420, h = 60, x, y, ax, ay; //画刻度线,刻度值 function draw() { ctx.clearRect(0, 0, 450, h); var max = parseInt(9), min = parseInt(1); var ratio = (max - min) / 400; //0.02 var tickSize = 50, tickCnt = 9; var unit = tickSize * ratio; //1 ctx.beginPath(); ctx.moveTo(20, 30); ctx.lineTo(w, 30); for (var i = 0; i < tickCnt; i++) { ctx.moveTo(20 + tickSize * i, 35); ctx.lineTo(20 + tickSize * i, 25); ctx.textAlign = 'center'; ctx.fillText((min + unit * i), 20 + tickSize * i, 20); ctx.fillStyle = 'green'; } ctx.stroke(); ctx.closePath(); } //画标识圆圈 function drawArc(x, y) { ctx.beginPath(); ctx.lineWidth = 2; ctx.arc(x, y, 5, 0 * Math.PI, 2 * Math.PI); ctx.fillStyle = "red" ctx.fill(); ctx.stroke(); ctx.closePath(); }; //事件绑定,鼠标按下 myCanvas.onmousedown = function (e) { //事件绑定,鼠标移动 myCanvas.onmousemove = function (e) { x = e.offsetX; y = e.offsetY; if (x < 20) { //限定X方向移动位置,只能在刻度线上移动 ax = 20 } else if (x > 420) { ax = 420 } (x < 420 && x > 20) ? x = e.offsetX : x = ax; y = 30; //Y方向坐标值限定,只能在刻度线上移动 //先清除之前图像,然后重新绘制 ctx.clearRect(0, 0, w, h); draw(); drawArc(x, y); }; //事件绑定,鼠标松开。同时清除myCanvas绑定事件 myCanvas.onmouseup = function () { myCanvas.onmousemove = null; myCanvas.onmouseup = null; }; } //页面加载完成,初始化方法 function init() { draw() drawArc(20, 30); } </script> </body> </html>
效果图很简单!