简体   繁体   中英

Canvas mouse coords after rotation

Im drawing lines from the center of a shape on mouse clicks. This works fine, until I perform a rotation on the div element holding the canvas element. Below is the basic Javascript. rotateWrapper gets called by a button elsewhere on the page

var p;
var rot = 0;
var canvas;
var ctx;

function rotateWrapper() {
  if (rot == 0) rot = 180;
  else rot = 0;
  $("#wCanvas").rotate({ animateTo:rot,duration:2500});
}

function draw() {
  ctx.save();
  ctx.moveTo(p[0], p[1]);
  ctx.lineTo(p[2], p[3]);

  ctx.closePath();
  ctx.stroke();
  ctx.restore();
}

$(document).ready(function () {
  canvas = $("#imgCanvas").get(0);
  ctx = canvas.getContext("2d");
  $("#imgCanvas").bind({
    mouseup: function(ev) {
      p[2] = ev.pageX;
      p[3] = ev.pageY;
    },
    mousedown: function(ev) {
      p = new Array(4);
      p[0] = $("#wCanvas").width() / 2;
      p[1] = $("#wCanvas").height() / 2;
    }
  });
}

Im sure Im missing something basic but this is driving me up the wall. Ive tried rotating the context in the draw method, both the amount of rot , as well as the inverse of it. Because Im rotating the container element Im thinking this has something to do with the CSS change interfering with things but not certain on that.

Any insights would be highly appreciated

"rotate" will rotate the canvas for elements drawn after the rotation. Without seeing how rotateWrapper and draw are called, it's difficult to tell how you should structure the code. But essentially, you should redraw after you want to apply the rotation. You probably want to store the rotation value, and call a central redraw routine that will apply the rotation first, then redraw.

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