gpt4 book ai didi

javascript - 鼠标在 HTML 5 响应式 Canvas 中的位置

转载 作者:太空狗 更新时间:2023-10-29 15:05:01 28 4
gpt4 key购买 nike

我搜索了其他问题,但没有一个适合我的情况。

我有一个 Canvas 元素:

<canvas id="linear-synoptic-map" width="1053px" height="1000px" ng-click="linearSynopticCtrl.canvasClicked($event)" ng-mousemove="linearSynopticCtrl.mouseMovedOverCanvas($event)">
</canvas>

我得到了这个函数的位置:

linearSynopticCtrl.getPositionFromEvent = function (event) {
var rect = linearSynopticCtrl.canvas.getBoundingClientRect();
var x = event.x - rect.left;
var y = event.y - rect.top;
return new Point(x,y);
};

问题是 Canvas 需要响应,所以我添加了以下 css 规则:

canvas#linear-synoptic-map {
width: 100%;
}

当发生调整大小时(当 Canvas 尺寸缩小超过定义或放大超过定义:1053x1000)时,正确的鼠标位置和函数返回的位置之间开始出现间隙。

我也试过用这种方法获得职位:

linearSynopticCtrl.getPositionFromEvent = function (event) {
var x = event.x - linearSynopticCtrl.canvas.offsetLeft;
var y = event.y - linearSynopticCtrl.canvas.offsetTop;
return new Point(x,y);
};

但我得到的结果要差得多。

有谁知道如何解决这个问题?

最佳答案

鼠标坐标永远不会缩放。

因此,您必须缩放鼠标坐标以使其反射(reflect)缩放后的 Canvas 。

这是使 Canvas 响应并获得缩放的鼠标坐标的一种方法:

// handle responsively resizing the canvas   
var scale=1.00;
var originalWindowWidth=window.innerWidth;
var originalCanvasWidth=document.getElementById('canvas').width;
function debounce(func, wait, immediate) {
var timeout;
return function() {
var context = this, args = arguments;
var later = function() {
timeout = null;
if (!immediate) func.apply(context, args);
};
var callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow) func.apply(context, args);
};
};
var resizeCanvas = debounce(function() {
scale=window.innerWidth/originalWindowWidth;
$('#canvas').css('width',originalCanvasWidth*scale);
}, 250);
window.addEventListener('resize', resizeCanvas);

// now, do normal app stuff

var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");

$("#canvas").mousemove(function(e){handleMouseMove(e);});

ctx.fillRect(50,50,100,100);
ctx.fillText('Rect drawn at [50,50]',50,35);

function handleMouseMove(e){

var rect = canvas.getBoundingClientRect();
var x = parseInt((event.x - rect.left)/scale);
var y = parseInt((event.y - rect.top)/scale);

$('#mouse').text(x+'/'+y);

}
body{ background-color: ivory; }
#canvas{border:1px solid red;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<h4>Mouse will report rect corner at<br>[50,50] even after resizing window</h4>
<h4 id=mouse>mouse</h4>
<canvas id="canvas" width=300 height=300></canvas>

关于javascript - 鼠标在 HTML 5 响应式 Canvas 中的位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28628964/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com