Search code examples
javascripthtml5-canvas

How to get TopLeft, TopRight, BottomLeft, BottomRight, and CentreTop position of Canvas Rect


Basically, I am trying to get the TopLeft, TopRight, BottomLeft, BottomRight, and TopMiddle positions for my rect that has been added to the canvas. Please show me in such a way that it applies to any size change that may occur to the rect. Not for the current specific size.

HTML:

<canvas id="myCanvas" width="300" height="150" style="border:1px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.</canvas>

<script>
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.beginPath();
ctx.rect(20, 20, 150, 100);
ctx.stroke();
</script> 

Solution

  • What you need can be calculated using Element.getBoundingClientRect() and the drawing information of rect relative to the canvas.

    var c = document.getElementById("myCanvas");
    var ctx = c.getContext("2d");
    ctx.beginPath();
    
    var rectLeft = 20;
    var rectTop = 20;
    var rectRight = 150;
    var rectBottom = 100;
    
    ctx.rect(rectLeft, rectTop, rectRight, rectBottom);
    ctx.stroke();
    
    var boundingRect = c.getBoundingClientRect();
    
    //TopLeft, TopRight, BottomLeft, BottomRight, and TopMiddle
    console.log("TopLeft", `(${boundingRect.top + rectTop},${boundingRect.left + rectLeft})`)
    console.log("TopRight", `(${boundingRect.top + rectTop},${boundingRect.left + rectRight})`)
    console.log("BottomLeft", `(${boundingRect.top + rectBottom},${boundingRect.left + rectLeft})`)
    console.log("BottomRight", `(${boundingRect.top + rectBottom},${boundingRect.left + rectRight})`)
    console.log("TopMiddle", `(${boundingRect.top + rectTop},${boundingRect.left + (rectLeft + rectRight)/2})`)
    //console.log(boundingRect)
    <canvas id="myCanvas" width="300" height="150" style="border:1px solid #d3d3d3;">
    Your browser does not support the HTML5 canvas tag.</canvas>