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);
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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…