缩放画布到鼠标光标 [英] Zoom Canvas to Mouse Cursor

查看:334
本文介绍了缩放画布到鼠标光标的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写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 ()放大或缩小,然后 translate() 返回与鼠标偏移量相反。请注意,您需要将光标位置从屏幕空间转换为已转换的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相比,缩放速度太快

这篇关于缩放画布到鼠标光标的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆