Canvas - How to adjust mouse position based on Scale value

Posted on 2014-08-18
Last Modified: 2014-08-18
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.


<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 -
Question by:JElster
    1 Comment
    LVL 3

    Accepted Solution

    context.fillRect((posx/2), (posy/2), 4, 4);

    //This is for 200% scale as it is coded.

    this would be helpful. perhaps.


    Write Comment

    Please enter a first name

    Please enter a last name

    We will never share this with anyone.

    Featured Post

    Training Course: Android App Development

    This course will involve creating widgets, customize list view, grid view, spinners, etc. Creating applications using audio, video, and SQLite database. Ending with publication on Google Play.

    Popularity Can Be Measured Sometimes we deal with questions of popularity, and we need a way to collect opinions from our clients.  This article shows a simple teaching example of how we might elect a favorite color by letting our clients vote for …
    Have you tried to learn about Unicode, UTF-8, and multibyte text encoding and all the articles are just too "academic" or too technical? This article aims to make the whole topic easy for just about anyone to understand.
    In this tutorial viewers will learn how to code links for mobile sites that, once clicked, send a call or text to a specified number. For a telephone link (once clicked, calls a number), begin with a normal "<a href=" link tag. For the href, specify…
    The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…

    737 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    19 Experts available now in Live!

    Get 1:1 Help Now