troubleshooting Question

Canvas - How to adjust mouse position based on Scale value

Avatar of JElster
JElsterFlag for United States of America asked on
HTML
1 Comment1 Solution504 ViewsLast Modified:
How can I adjust the mouse position based on the scale (zoom) value of a canvas.

See the following.  See how mouse position is OFF.

http://jsfiddle.net/JElster/bueawkc2/


thx


<div id="images"></div>
<canvas  style="margin:0;padding:0;position:relative;left:150px;top:50px;" id="imgCanvas" width="500" height="500"></canvas>

var canvas = document.getElementById("imgCanvas");
var context = canvas.getContext("2d");

context.scale(2,2);   // Zoom 200 %

function draw(e) {
    var pos = getMousePos(canvas, e);
    posx = pos.x;
    posy = pos.y;
    context.fillStyle = "#0000ff";
    context.fillRect(posx, posy, 4, 4);
}
window.addEventListener('mousemove', draw, false);

function getMousePos(canvas, evt) {
    var rect = canvas.getBoundingClientRect();
    return {
      x: evt.clientX - rect.left,
      y: evt.clientY - rect.top
    };
}
ASKER CERTIFIED SOLUTION
viseera

Our community of experts have been thoroughly vetted for their expertise and industry experience.

Join our community to see this answer!
Unlock 1 Answer and 1 Comment.
Start Free Trial
Learn from the best

Network and collaborate with thousands of CTOs, CISOs, and IT Pros rooting for you and your success.

Andrew Hancock - VMware vExpert
See if this solution works for you by signing up for a 7 day free trial.
Unlock 1 Answer and 1 Comment.
Try for 7 days

”The time we save is the biggest benefit of E-E to our team. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange.

-Mike Kapnisakis, Warner Bros