HTML5 Canvas: Zooming

后端 未结 6 860
天命终不由人
天命终不由人 2020-11-27 11:59

Is there any easy way how to zoom in and back out in canvas (JavaScript)? Basically I have a 400x400px canvas and I\'d like to be able to zoom in with \'mousedown\' (2x) and

6条回答
  •  醉梦人生
    2020-11-27 12:47

    If you have a source image or canvas element and your 400x400 canvas you want to draw into you can use the drawImage method to achieve zooming.

    So for example, the full view might be like this

    ctx.drawImage(img, 0, 0, img.width, img.height, 0, 0, canvas.width, canvas.height);

    And a zoomed view might be like this

    ctx.drawImage(img, img.width / 4, img.height / 4, img.width / 2, img.height / 2, 0, 0, canvas.width, canvas.height);

    The first parameter to drawImage is the image element or canvas element to draw, the next 4 are the x, y, width and height to sample from the source and the last 4 parameters are the x, y, width and height of the region to draw in the canvas. It will then handle the scaling for you.

    You would just need to pick the width and height for the source sample based on the zoom level and the x and y based on where the mouse is clicked minus half the calculated width and height (but you will need to ensure the rectangle isn't out of bounds).

提交回复
热议问题