html5画布中的鼠标交互。画线

时间:2014-03-16 19:05:13

标签: javascript html5 canvas

只处理HTML5画布。 我需要完成一些鼠标交互。像画一个矩形或一条线。 具体来说,我需要做的是在mousemove调用期间绘制动态线。它的意思是。 mousemove 1从x1,y1到x2,y2绘制一条线 mousemove 2删除上一行。设置x1 = x2和y1 = ys并重复上一个过程,直到我抓住mouseup来合并该行。

从我在windows api编程的时代开始,我记得xoring这些线路运行正常。 在jscript canvas上是否有类似的方法?

另外:将鼠标从mousedown捕获到mouseup会很棒。那可能吗?。 如果无法完成,只需在mouseout上终止进程。

请帮忙吗?

2 个答案:

答案 0 :(得分:3)

基本演示(可能需要推文):http://jsfiddle.net/m1erickson/H7vRw/

enter image description here

您可以请求浏览器将鼠标事件(mousedown,mouseup,mousemove)发送到将处理这些事件的函数。

// add an html canvas element

<canvas id="canvas" width=300 height=200></canvas>

// ask the browser to send mouse events to handler functions
// for example, mousedown events will be sent to the handleMouseDown function
// this example uses jQuery for browser compatibility

$("#canvas").mousedown(function(e){handleMouseDown(e);});
$("#canvas").mousemove(function(e){handleMouseMove(e);});
$("#canvas").mouseup(function(e){handleMouseUp(e);});
$("#canvas").mouseout(function(e){handleMouseUp(e);});

在mousedown处理程序中:

  • 获得鼠标位置。
  • 设置一个标志,指示拖动已经开始
  • 保存鼠标位置(它将是该行的起点)

Mousedown代码:

function handleMouseDown(e){

  // let the browser know we will handle this event

  e.preventDefault();   

  // get the mouse position

  var mouseX=parseInt(e.clientX-offsetX);
  var mouseY=parseInt(e.clientY-offsetY);

  // set an isDown flag to indicate dragging has started

  isDown=true;

  // save the starting mouse position 
  // (it will be the beginning point of the line);

  startX=mouseX;
  startY=mouseY;

}

在mousemove处理程序代码中:

  • 获取鼠标位置
  • 清除画布并从保存的起始位置绘制一条线到此鼠标位置

mousemove code:

function handleMouseMove(e){

  // if we're not dragging, ignore this mousemove

  if(!isDown){ return; }

  // let the browser know we will handle this event

  e.preventDefault();   

  // get the mouse position

  var mouseX=parseInt(e.clientX-offsetX);
  var mouseY=parseInt(e.clientY-offsetY);

  // draw the current line
  ctx.clearRect(0,0,canvas.width,canvas.height);
  ctx.beginPath();
  ctx.moveTo(startX,startY);
  ctx.lineTo(mouseX,mouseY);
  ctx.stroke()

}

在mouseup处理程序中:

  • 自拖动完成后清除拖动标记。

mouseup code:

function handleMouseUp(e){

  // let the browser know we will handle this event

  e.preventDefault();   

  // clear the dragging flag since the drag is donw

  isDown=false;

}

答案 1 :(得分:2)

检查这个fiddle,不完全是你需要的,但希望从...开始是有帮助的。

var el = document.getElementById('canvasId');
var ctx = el.getContext('2d');
var isDrawing;
el.onmousedown = function(e) {
  isDrawing = true;
  ctx.moveTo(e.clientX, e.clientY);
};
el.onmousemove = function(e) {
  if (isDrawing) {
  ctx.lineTo(e.clientX, e.clientY);
  ctx.stroke();
  }
};
el.onmouseup = function() {
  ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
  isDrawing = false;
};