Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Position error and correction recommendation #27

Open
newpro opened this issue Feb 1, 2017 · 4 comments
Open

Position error and correction recommendation #27

newpro opened this issue Feb 1, 2017 · 4 comments

Comments

@newpro
Copy link

newpro commented Feb 1, 2017

Hey guys!

I believe there is an error in event position getter.

The following code does not consider position of canvas DOM parent :

 _position(event) {
    return {
      x: event.pageX - this.canvas.offsetLeft,
      y: event.pageY - this.canvas.offsetTop,
    };
  }

Since offsetLeft/Top only consider relative position to parent, so if parent is not at 0,0, the function return wrong coordinates.

Recommend change to:

 _position(event) {
    var rect = this.canvas.getBoundingClientRect();
    return {
      x: event.clientX - rect.left,
      y: event.clientY - rect.top
    };
  }
@jeanlucaslima
Copy link
Member

Thanks, @newpro, looking at it for the next version of the library.

@BoldBigflank
Copy link

Here's another potential problem and proposed solution: When you set the canvas' max-width to 100% you can get a full canvas shrunk down to a size smaller than normal. To account for this, figure out the ratio between the canvas's width and its displayed width like so:

Sketchpad.prototype._cursorPosition = function(event) {
  var ratio = $(this.canvas)[0].width / $(this.canvas).width();
  var rect = this.canvas.getBoundingClientRect();
  return {
    x: (event.clientX - rect.left) * ratio,
    y: (event.clientY - rect.top) * ratio,
  };
};

@brittonk
Copy link

This solved my issue with this plugin. Thanks BoldBigflank

Sketchpad.prototype._cursorPosition = function(event) {
var ratio = $(this.canvas)[0].width / $(this.canvas).width();
var rect = this.canvas.getBoundingClientRect();
return {
x: (event.clientX - rect.left) * ratio,
y: (event.clientY - rect.top) * ratio,
};
};

@72L
Copy link

72L commented May 16, 2020

Thanks BoldBigflank. This helped on mobile, when the screen size was smaller than the initial canvas size.

I added a ratio in the y direction as well:

Sketchpad.prototype._cursorPosition = function (event) {
    let $canvas = $(this.canvas),
        xratio = this.canvas.width / $canvas.width(),
        yratio = this.canvas.height / $canvas.height(),
        rect = this.canvas.getBoundingClientRect();
    return {
        x: (event.clientX - rect.left) * xratio,
        y: (event.clientY - rect.top) * yratio,
    };
};

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

5 participants