在一个测试应用程序中,我有一个带有简单矩形的画布。每 100 毫秒调用一次draw方法。
正如您从代码中看到的那样,我正在使用鼠标滚轮来缩放所有内容。现在发生的事情是,一切都被缩放了,但是当矩形在 10px,10px 并且我将鼠标放在它上面时,矩形在缩放后不再位于鼠标下方。(这当然是正确的,因为所有单位都按比例放大。
但我想要的是,鼠标位置是“缩放动作的中心”,就像在谷歌地图中一样,所以缩放之前在鼠标下的内容,在之后也在鼠标下。我做了一些翻译尝试,但我不知道该怎么做。
提前致谢。
这是我的代码:
<script type="text/javascript">
var scroll = 0;
var scale = 1.0;
/** This is high-level function.
* It must react to delta being more/less than zero.
*/
function handle(delta) {
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
scroll = delta;
if(scroll > 0)
{
scale += 0.2;
}
if(scroll < 0)
{
scale -= 0.2;
}
}
/** Event handler for mouse wheel event.
*/
function wheel(event){
var delta = 0;
if (!event) /* For IE. */
event = window.event;
if (event.wheelDelta) { /* IE/Opera. */
delta = event.wheelDelta/120;
} else if (event.detail) { /** Mozilla case. */
/** In Mozilla, sign of delta is different than in IE.
* Also, delta is multiple of 3.
*/
delta = -event.detail/3;
}
/** If delta is nonzero, handle it.
* Basically, delta is now positive if wheel was scrolled up,
* and negative, if wheel was scrolled down.
*/
if (delta)
handle(delta);
/** Prevent default actions caused by mouse wheel.
* That might be ugly, but we handle scrolls somehow
* anyway, so don't bother here..
*/
if (event.preventDefault)
event.preventDefault();
event.returnValue = false;
}
/** Initialization code.
* If you use your own event management code, change it as required.
*/
if (window.addEventListener)
/** DOMMouseScroll is for mozilla. */
window.addEventListener('DOMMouseScroll', wheel, false);
/** IE/Opera. */
window.onmousewheel = document.onmousewheel = wheel;
var drawX = 0;
var drawY = 0;
var overX = 0;
var overY = 0;
function startCanvas()
{
var myCanvas = document.getElementById("myCanvas");
var ctx = myCanvas.getContext("2d");
ctx.canvas.width = window.innerWidth;
ctx.canvas.height = window.innerHeight;
setInterval(draw,100);
}
function draw()
{
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
ctx.clearRect(0,0,window.innerWidth,window.innerHeight);
ctx.save();
ctx.scale(scale,scale);
ctx.fillRect(drawX,drawY,20,20);
//ctx.translate(-scale,-scale);
ctx.restore();
ctx.font="20pt Arial";
ctx.fillText(scale+":"+drawX,0,150);
}
function canvasClick(event)
{
console.log(event.layerX+"/"+scale);
drawX = event.layerX/scale;
drawY = event.layerY/scale;
}
function canvasOver(event)
{
console.log("over");
overX = event.layerX;
overY = event.layerY;
}
</script>