Javascript examples for Canvas:Mouse
Html5 canvas zoom with mouse wheel
<html> <head> <meta name="viewport" content="width=device-width, initial-scale=1"> <script type="text/javascript" src="https://code.jquery.com/jquery-1.6.2.js"></script> <style id="compiled-css" type="text/css"> canvas { border : 2px solid black; } </style> <script type="text/javascript"> $(window).load(function(){// w ww . j a va 2s . c om var canvas = document.getElementById("canvas"); var context = canvas.getContext("2d"); var scale = 1; var currentzoom = 1; var originx = 0; var originy = 0; function draw(){ context.fillStyle = "white"; context.fillRect(originx,originy,canvas.width/scale,canvas.height/scale); context.fillStyle = "black"; context.fillRect(50,50,canvas.width/2,canvas.height/2); } setInterval(draw,100); var mousex = 0, mousey = 0; canvas.onmousewheel = function (event){ var wheel = event.wheelDelta/120;//n or -n var zoom = 0; if(wheel < 0) { zoom = 1/2; if(currentzoom == 1) return; } else { mousex = event.clientX - canvas.offsetLeft; mousey = event.clientY - canvas.offsetTop; zoom = 2; if(currentzoom == 32) return; } currentzoom *= zoom; context.translate( originx, originy ); context.scale(zoom,zoom); context.translate( -( mousex / scale + originx - mousex / ( scale * zoom ) ), -( mousey / scale + originy - mousey / ( scale * zoom ) ) ); originx = ( mousex / scale + originx - mousex / ( scale * zoom ) ); originy = ( mousey / scale + originy - mousey / ( scale * zoom ) ); scale *= zoom; } }); </script> </head> <body> <canvas id="canvas" height="500" width="900"></canvas> </body> </html>