缩放画布到鼠标光标
我正在编写HTML5<画布>项目,包括使用滚轮放大和缩小图像。
我想向google地图放大光标,但我完全失去了如何计算运动。
I'm programming a HTML5 < canvas > project that involves zooming in and out of images using the scroll wheel. I want to zoom towards the cursor like google maps does but I'm completely lost on how to calculate the movements.
我有:image x和y(左上角);图像宽度和高度;
What I have: image x and y (top-left corner); image width and height; cursor x and y relative to the center of the canvas.
总之,你想要 translate ()$ c>放大或缩小,然后
translate()$ c>
返回与鼠标偏移量相反。请注意,您需要将光标位置从屏幕空间转换为已转换的canvas上下文。
In short, you want to translate()
the canvas context by your offset, scale()
it to zoom in or out, and then translate()
back by the opposite of the mouse offset. Note that you need to transform the cursor position from screen space into the transformed canvas context.
ctx.translate(pt.x,pt.y);
ctx.scale(factor,factor);
ctx.translate(-pt.x,-pt.y);
演示: http://phrogz.net/tmp/canvas_zoom_to_cursor.html
我放了一个完整工作示例,以便检查,支持拖动,单击放大,Shift-click出来或向上/向下滚动。
Demo: http://phrogz.net/tmp/canvas_zoom_to_cursor.html
I've put up a full working example on my website for you to examine, supporting dragging, click to zoom in, shift-click to out, or scroll wheel up/down.
唯一的(当前)问题是 Safari与Chrome或Firefox相比,缩放速度太快。