简体   繁体   中英

Scale HTML5 canvas context to fit image vertically

I am developing a canvas web application which displays an image and trying to prevent the user from panning and zooming such that they cannot see beyond the height of the image of the image. How can I scale the canvas context so that it fits the vertical height of the image relative to the vertical height of the canvas? I am not trying to scale the image as I have seen many solutions to that, I need the canvas context to scale/translate for the image.

Preventing the panning outside of the height (above and below) is trivial, however I am clueless regarding setting the correct scale to prevent the user from zooming too far.

image.onload = () => {
    ctx.translate(-image.width/4, -image.height/4); 
    animate();
}

Here, I translate my context to where I would like it in my image and then begin drawing, this is ideally where the correct transform would go.

Figured out the answer myself, it's a simple case of knowing that the canvas.height = scale * image.height , one can just rearrange this equation to scale = canvas.height/image.height .

It is, of course, important to note that this only works when the current scale transform is 1, otherwise the scale will need to be relative to your current scale transform.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM