我想在画布上绘制的对象的左上角显示。

删除按钮的左侧和顶部位置等于object.left + object.width,顶部等于object.top

旋转对象后,删除按钮的lefttop等于对象的原始位置。

有人可以解释我如何获取右上角的“真实” XY坐标吗?

这是我的jsfiddle:
http://jsfiddle.net/5KKQ2/304/

   delBtn.style.display = 'block';
    delBtn.style.left = activeEl.left + (activeEl.width * activeEl.scaleX / 2) - 25 + 'px';
    delBtn.style.top = activeEl.top - (activeEl.height * activeEl.scaleX / 2) - 15 + 'px';

最佳答案

一点三角法将为您提供旋转的左上角点

假设矩形围绕其中心点旋转

function rotatedTopLeft(x,y,width,height,rotationAngle){

    // get the center of the rectangle (==rotation point)
    var cx=x+width/2;
    var cy=y+height/2;

    // calc the angle of the unrotated TL corner vs the center point
    var dx=x-cx;
    var dy=y-cy;
    var originalTopLeftAngle=Math.atan2(dy,dx);

    // Add the unrotatedTL + rotationAngle to get total rotation
    var rotatedTopLeftAngle=originalTopLeftAngle+rotationAngle;

    // calc the radius of the rectangle (==diagonalLength/2)
    var radius=Math.sqrt(width*width+height*height)/2;

    // calc the rotated top & left corner
    var rx=cx+radius*Math.cos(rotatedTopLeftAngle);
    var ry=cy+radius*Math.sin(rotatedTopLeftAngle);

    // return the results
    return({left:rx,top:ry});
}


这是示例代码和演示:



var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var cw=canvas.width;
var ch=canvas.height;

var PI=Math.PI;
var PI2=PI*2;

var x=125;
var y=132;
var width=50;
var height=36;

var rotationAngle=PI/6;

ctx.translate(x+width/2,y+height/2);
ctx.rotate(rotationAngle);

ctx.fillStyle='red';
ctx.strokeStyle='black';
ctx.lineWidth=5;
ctx.fillRect(-width/2,-height/2,width,height);
ctx.strokeRect(-width/2,-height/2,width,height);

ctx.rotate(-rotationAngle);
ctx.translate(-(x+width/2),-(y+height/2));

var rotatedTopLeft=rotatedTopLeft(x,y,width,height,rotationAngle);

dot(rotatedTopLeft.left,rotatedTopLeft.top,5,'gold');


function rotatedTopLeft(x,y,width,height,rotationAngle){

  // get the center of the rectangle (==rotation point)
  var cx=x+width/2;
  var cy=y+height/2;

  // calc the angle of the unrotated TL corner vs the center point
  var dx=x-cx;
  var dy=y-cy;
  var originalTopLeftAngle=Math.atan2(dy,dx);

  // Add the unrotatedTL + rotationAngle to get total rotation
  var rotatedTopLeftAngle=originalTopLeftAngle+rotationAngle;

  // calc the radius of the rectangle (==diagonalLength/2)
  var radius=Math.sqrt(width*width+height*height)/2;

  // calc the rotated top & left corner
  var rx=cx+radius*Math.cos(rotatedTopLeftAngle);
  var ry=cy+radius*Math.sin(rotatedTopLeftAngle);

  // return the results
  return({left:rx,top:ry});
}

function dot(x,y,radius,fill){
  ctx.beginPath();
  ctx.arc(x,y,radius,0,PI2);
  ctx.closePath();
  ctx.fillStyle=fill;
  ctx.fill();
}

body{ background-color: ivory; }
#canvas{border:1px solid red;}

<h4>Gold dot is at the rotated top-left corner</h4>
<canvas id="canvas" width=300 height=300></canvas>

09-25 19:13