我正在开发一个有HTML5画布的界面,我需要在选择位置时反转X和Y坐标。我认为从选定的X位置减去画布的宽度,并从选定的Y位置减去画布的高度会反转坐标,但它会做一些非常奇怪的事情。
单击画布左上角时记录的X和Y坐标是X:324,Y:483
但理论上它们应该是X:650,Y:587
,当您点击右下角时,当理论上它们应该是X:-325,Y:-103
时,记录的坐标为X:0,Y:0
。作为旁注,我知道点击时出现的点是使用倒置坐标,这很好。
任何帮助都会受到赞赏,特别是如果我做了一些可怕的错误。谢谢!
JS:
window.fires.directive('fieldDirective', ['ScoutService', '$interval', function(ScoutService, $interval) {
var $scope = this;
$scope.sServ = ScoutService;
$interval(function(){
$scope.col = ScoutService.getAllianceColor();
},1);
return {
restrict: "A",
link: function(scope, element) {
element.bind('mousedown', function(event) {
var canvas = document.getElementById('field');
var context = canvas.getContext('2d');
if(event.offsetX !== undefined) {
$scope.xPos = 650 - event.offsetX;
$scope.yPos = 587 - event.offsetY;
$scope.sServ.sendLobCoords(xPos, yPos);
} else {
$scope.xPos = 650 - event.layerX - event.currentTarget.offsetLeft;
$scope.yPos = 587 - event.layerY - event.currentTarget.offsetTop;
$scope.sServ.sendLobCoords(xPos, yPos);
}
console.log('red'+$scope.xPos + ' ' + $scope.yPos);
canvas.width = canvas.width;
context.arc($scope.xPos, $scope.yPos, 12, 0, Math.PI*2);
context.fillStyle = '#FFFF00';
context.fill();
context.lineWidth = 3;
context.strokeStyle = '#B2B200';
context.stroke();
context.closePath();
});
}
};
}]);
HTML:
<canvas field-directive id="field" ng-class="{'field-red': sCtrl.fieldColor === 'red', 'field-blue': sCtrl.fieldColor === 'blue'}" width="650" height="587">Your browser does not support the HTML5 Canvas Element. Please use a supported browser such as Google Chrome 4.0+ or FireFox 2.0+.</canvas>
答案 0 :(得分:2)
修改示例:
element.bind('mousedown', function(event) {
var canvas = document.getElementById('field');
var context = canvas.getContext('2d');
// get element position
var rect = canvas.getBoundingClientRect();
// get inversed coordinates: enable code after comment if abs. pos.
var ix = canvas.width - (event.clientX - rect.left); // + rect.left
var iy = canvas.height - (event.clientY - rect.top); // + rect.top
...update $scope here etc...
});
var canvas = document.getElementById('field');
canvas.addEventListener('mousemove', function(event) {
var canvas = document.getElementById('field');
var context = canvas.getContext('2d');
// get element position
var rect = canvas.getBoundingClientRect();
// get inversed coordinates: enable code after comment if abs. pos.
var ix = canvas.width - (event.clientX - rect.left); // + rect.left
var iy = canvas.height - (event.clientY - rect.top); // + rect.top
// draw something
context.clearRect(0, 0, 500, 180);
context.fillRect(ix - 2, iy - 2, 4, 4);
});
canvas {border: 1px solid #007}
<canvas id="field" width=500 height=180></canvas>
答案 1 :(得分:0)
我认为问题出现了,因为offsetX和offsetY与点击的项目相关联。在这种情况下,无论什么&#34;元素&#34;是。如果click事件直接绑定到画布上,我认为您的代码可以正常工作。
尝试将事件绑定到画布本身,或者使用元素的位置和点击行为以及画布的位置来进行校正数学运算。