我必须在画布上单击四个点并获取鼠标单击坐标。我面临两个问题:
我不能仅使用Canvas使用offsetLeft和offsetTop来设置感兴趣的区域。
单击四次后,我将所有四个点的x,y坐标重置为0,以便可以重绘新坐标。但是我必须再单击一次,没有任何响应,然后才能进行第二次4次点击循环。
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>parallelogram</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<canvas id="canvas" width="800" height="600" style="border:solid 1px;margin:0;padding:0;"></canvas>
</body>
</html>
<script type="text/javascript">
//Declare all the variables
var first = {x: null-this.offsetLeft, y: null-this.offsetTop};
var second = {x: null-this.offsetLeft, y: null-this.offsetTop};
var third = {x: null-this.offsetLeft, y: null-this.offsetTop};
var fourth = {x: null-this.offsetLeft, y: null-this.offsetTop};
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
var pointsNum = 0;
var plogram = new Array();
//Code that draws a point on the canvas
var drawpoint = function (x, y) {
ctx.clearRect(0, 0, 0, 0);
ctx.beginPath();
ctx.lineWidth=3;
ctx.strokeStyle = '#f4d03f';
ctx.arc(x, y, 3.5, 0, Math.PI * 2, false);
ctx.stroke();
}
function clickDraw(e) {
pointsNum++;
if (pointsNum <= 3) {
drawpoint(e.pageX, e.pageY);
} else {
pointsNum = 0;
first.x = first.y = second.x = second.y = third.x = third.y = fourth.x = fourth.y = null
}
}
canvas.addEventListener("click", function (e) {
clickDraw(e);
}, false);
</script>
我在使用拉点功能时尝试设置偏移极限
drawpoint(e.pageX-this.offsetLeft, e.pageY-this.offsetTop);
因此,圆圈不会被绘制。我也将pageX和pageY更改为clientX和clientY。