在绘图应用程序中绘制时显示鼠标事件数组 - HTML

时间:2017-11-20 04:00:56

标签: javascript jquery arrays html5-canvas

我试图在画布中获取鼠标的数组坐标,但是当我尝试它时,它不会显示线条/绘图。无论如何要让阵列显示它们?



       

var drawMouse = function() {
	var clicked = 0;

	
	var start = function(e) {
		var pointX = [];
		var pointY = [];
		clicked = 1;
		ctx.beginPath();
		x = e.pageX;
		y = e.pageY-44;
		ctx.moveTo(x,y);
	};
	var move = function(e) {
		if(clicked){
			x = e.pageX;
			y = e.pageY-44;
			ctx.lineTo(x,y);
			ctx.stroke();
			pointX.push(x);
			pointY.push(y);
			
		}	
	};
	
	var stop = function(e) {
		clicked = 0;
		
		var coords = document.getElementById("coords");
		for (var i = 0; l = pointX.lenght; i<l; i++){
		coords.innerHTML += pointX[i]+ "-" + pointY[i]+ "<br/>";
		}
	};

    document.getElementById("canvas").addEventListener("mousedown", start, false);
	document.getElementById("canvas").addEventListener("mousemove", move, false);
	document.addEventListener("mouseup", stop, false);
};
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:0)

var clicked = 0;
var pointX = [];
var pointY = [];
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext('2d');
var start = function(e) {
  clicked = 1;
  ctx.beginPath();
  x = e.clientX - canvas.offsetLeft;
  y = e.clientY - canvas.offsetTop;
  ctx.moveTo(x, y);
};
var move = function(e) {
  if (clicked) {
    x = e.clientX - canvas.offsetLeft;
    y = e.clientY - canvas.offsetTop;
    ctx.lineTo(x, y);
    ctx.stroke();
    pointX.push(x);
    pointY.push(y);

  }
};

var stop = function(e) {
  clicked = 0;
  var coords = document.getElementById("coords");
  for (var i = 0, l = pointX.length; i < l; i++) {
    coords.innerHTML += pointX[i] + "-" + pointY[i] + "<br/>";
  }
};

document.getElementById("canvas").addEventListener("mousedown", start, false);
document.getElementById("canvas").addEventListener("mousemove", move, false);
document.addEventListener("mouseup", stop, false);
canvas{
 border : 2px solid black;
}
<canvas id='canvas' width=300 height=300></canvas>
<p id='coords'></p>

您有拼写错误for (var i = 0; l = pointX.lenght; i<l; i++),您需要更改为for (var i = 0, l = pointX.length; i<l; i++)和用于在画布中绘制的鼠标指针偏移量。