简体   繁体   中英

Drawing on zoomed HTML5 canvas

I have two overlaying canvas elements, one for displaying an image, and the other one for drawing lines with different colors and thickness over this image. I'm using the Panzoom library for jQuery for zooming the image and it works well. But when drawing over the zoomed canvas, the line points don't match the mouse click event's point.

Is there any simple solution of this problem?

Not zooming the canvas used for drawing will be a problem because I use this canvas later as a filter for other transformations of the original image, so they have to be of the same size.

Maybe it's better not to use a library at all and write the code from scratch, but that seems like a lot of work and I'm not experienced enough, so I'm not sure if I can make it.

So I need some guidelines, so I'd know in which way to think and how to begin.

I posted a similar answer on another post, so I'll try to reuse it and modify it a bit to receive the click events, and yes, I wrote it from scratch. It wasn't that much work, but that because I've written this project many times already.

This is a peice of a project that I wrote when working for a company that wanted charting applications. What I assume that you looking for is the mouse coordinates in relation to the zoomed image.

I would suggest that the mouse coordinates that you use are actually a percentage system. Your image, when zoomed, is a percentage of the images original size. You can reflect the mouse position over that canvas as a percentage across the zoomed image: ie: x=20%, y=12%. Say your image is normally 100px wide and 100px tall, yet zoomed to 200% making your image 200px by 200px, and your canvas is -20% left and -20% top, clicking the mouse at (0, 0) on the canvas would be at (20%, 20%) on the zoomed image, making your mouse coordinates on the zoomed image (40, 40).

Here is the project

Here is the project fullscreen

And Here's a snippet:

this.yPos = evt.y;
this.xPos = evt.x;

this.xPercPos = ((this.xPos - Main.canvas.gLeftStart) / (Main.canvas.originW * Main.canvas.zoomX)) * 100;

this.yPercPos = ((this.yPos - Main.canvas.gTopStart) / (Main.canvas.originH * Main.canvas.zoomY)) * 100;

Main.xLabel.innerHTML = Main.xLabel.stndrdText + this.xPercPos.toFixed(3) + '%';
Main.yLabel.innerHTML = Main.yLabel.stndrdText + this.yPercPos.toFixed(3) + '%';

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