如何在画布上使用鼠标移动功能?

时间:2015-04-23 20:00:20

标签: javascript canvas

如果我在Javascript中编写了一个名为clearCircle的函数,那么当鼠标悬停在画布上时,我怎样才能使clearCircle用鼠标移动? 我已经尝试了画布的onmouseover事件,但这似乎没什么帮助。

  clearCircle(context,/*x=*/520,/*y=*/600,/*radius=*/60);

function clearCircle(context,x,y,radius) {
  context.save();
  context.beginPath();
  context.arc(x, y, radius, 0, 2*Math.PI, true);
  context.clip();
  context.clearRect(x-radius,y-radius,radius*2,radius*2);
  context.restore();
}

1 个答案:

答案 0 :(得分:0)

如评论中所示,您必须通过鼠标移动时的响应来重绘圆圈。您可以通过创建处理画布的mousemove事件的函数来进行响应。

这是带注释的代码和演示:

// canvas related variables
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var cw=canvas.width;
var ch=canvas.height;
ctx.lineWidth=3;

// handle scrolling (which affects mouse coordinates)
function setBB(){
  BB=canvas.getBoundingClientRect();
  BBoffsetX=BB.left;
  BBoffsetY=BB.top;
}
var BB,BBoffsetX,BBoffsetY;
setBB();
window.onscroll=function(e){ setBB(); }

// cache PI*2 since it's used often
var PI2=Math.PI*2;

// define the center X,Y, radius, & colors of the circle
var circle={cx:100,cy:100,radius:25,fill:'skyblue',stroke:'white'};

// draw the circle initially on the canvas
draw();

// function to clear/fill the canvas background
// and draw the circle in its current position as 
// defined in the circle{} object
function draw(){
  // if you're going to fill the canvas with black then
  // clearRect is not needed...just do fillRect with black
  ctx.clearRect(0,0,cw,ch);
  ctx.fillStyle='black';
  ctx.fillRect(0,0,cw,ch);
  ctx.beginPath();
  ctx.arc(circle.cx,circle.cy,circle.radius,0,PI2);
  ctx.closePath();
  ctx.fillStyle=circle.fill;
  ctx.fill();
  ctx.strokeStyle=circle.stroke;
  ctx.stroke()
}

// listen for mousemove events and //
// handle with function 'handleMousemove'
canvas.onmousemove=handleMousemove;

// this function is called everytime the browser
// fires the mousemove event
function handleMousemove(e){

  // tell the browser we're handling this event
  e.preventDefault();
  e.stopPropagation();

  // get the current mouse position
  var mouseX=parseInt(e.clientX-BBoffsetX);
  var mouseY=parseInt(e.clientY-BBoffsetY);

  // set the circle{} center X,Y equal to the mouse position
  circle.cx=mouseX;
  circle.cy=mouseY;

  // redraw the canvas with the circle at its
  // newly defined position
  draw();
}
body{ background-color: ivory; }
canvas{border:1px solid red;}
<h4>Move the mouse and the circle will follow</h4>
<canvas id="canvas" width=300 height=300></canvas>

相关问题