将画布缩放到鼠标光标

将画布缩放到鼠标光标

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

问题描述

我正在编写 HTML5 <canvas > 涉及使用滚轮放大和缩小图像的项目.我想像谷歌地图一样放大光标,但我完全不知道如何计算运动.

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.

我所拥有的:图像 x 和 y(左上角);图像宽度和高度;相对于画布中心的光标 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()画布上下文,scale()它放大或缩小,然后 translate() 返回鼠标偏移的相反位置.请注意,您需要将光标位置从屏幕空间转换为转换后的画布上下文.

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 键单击缩小或向上/向下滚动滚轮.

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 相比.

The only (current) issue is that Safari zooms too fast compared to Chrome or Firefox.

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

08-12 07:47