Zoom Canvas to Mouse Cursor

后端 未结 4 1943
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-11-22 15:03

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

4条回答
  •  盖世英雄少女心
    2020-11-22 15:42

    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);
    

    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.

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

提交回复
热议问题