html5 zoom-in,html - How can we zoom in and out of the graph in html5 and javascript? - Stack Overfl...

In order to do this, you'll have to have an offset and a zoom scale. Then, whenever you draw, you'll have to transform your drawing appropriately. Canvas makes this easy:

ctx.save();

ctx.translate(offset.x, offset.y);

ctx.scale(scale, scale);

// do your drawing

ctx.restore();

Then you add handlers for the appropriate mouse events. For the mouse wheel, this will be the wheel event. Whenever you receive such an event, you'll want to calculate a new scale. This could be done for example using:

// Assuming 'ticks' is some standardized unit of measurement.

// You'll probably want to scale it differently based on event.deltaMode.

var newScale = scale * Math.pow(1.5, ticks);

Then you'll want to figure out the untransformed position.

// Assuming mousePos.x and mousePos.y are the position, relative to the canvas,

// of the mouse event. To untransform, first undo the offset and then undo the

// scale.

var untransformed = {

x: (mousePos.x - offset.x) / scale,

y: (mousePos.y - offset.y) / scale

};

Then, perform some magic, determined through experimentation:

offset.x += transformed.x * (scale - newScale);

offset.y += transformed.y * (scale - newScale);

Then apply the scale change:

scale = newScale;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值