Skip to content

Instantly share code, notes, and snippets.

@KennyRedman
Created June 4, 2014 18:28
Show Gist options
  • Save KennyRedman/50d636b7eb43a01bb61c to your computer and use it in GitHub Desktop.
Save KennyRedman/50d636b7eb43a01bb61c to your computer and use it in GitHub Desktop.
CanvasZoom - Mouse wheel scrolling
<canvas id="canvas" width="1000" height="800"></canvas>
<script type="text/javascript">
var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");
var scale = 1;
var originx = 0;
var originy = 0;
function draw(){
context.fillStyle = "white";
context.fillRect(originx,originy,1000/scale,800/scale);
context.fillStyle = "black";
context.fillRect(50,50,100,100);
}
setInterval(draw,100);
canvas.onmousewheel = function (event){
var mousex = event.clientX - canvas.offsetLeft;
var mousey = event.clientY - canvas.offsetTop;
var wheel = event.wheelDelta/120;//n or -n
//according to Chris comment
var zoom = Math.pow(1 + Math.abs(wheel)/2 , wheel > 0 ? 1 : -1);
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>
@moharanascimento
Copy link

Thanks man, it helps me!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment