DEV Community

Discussion on: Creating Bounding box for different code generated shapes

 
svijaykoushik profile image
Vijay Koushik, S. 👨🏽‍💻

Hi @maxarias ,
I draw a triangle similar to this code:

function draw() {
  var canvas = document.getElementById('canvas');
  if (canvas.getContext) {
    var ctx = canvas.getContext('2d');

    ctx.beginPath();
    ctx.moveTo(75, 50);//Vertex 1
    ctx.lineTo(100, 75);// Vertex 2
    ctx.lineTo(100, 25);// Vertex 3
    ctx.fill();
  }
}

Here it is easy to apply your method of finding the largest and smallest x, y co-ordinates to compute the bounding box. But, In case of a heart shape, cubic Bezier curves are used as in this code:

function draw() {
  var canvas = document.getElementById('canvas');
  if (canvas.getContext) {
    var ctx = canvas.getContext('2d');

    // Cubic curves example
    ctx.beginPath();
    ctx.moveTo(75, 40);
    ctx.bezierCurveTo(75, 37, 70, 25, 50, 25);
    ctx.bezierCurveTo(20, 25, 20, 62.5, 20, 62.5);
    ctx.bezierCurveTo(20, 80, 40, 102, 75, 120);
    ctx.bezierCurveTo(110, 102, 130, 80, 130, 62.5);
    ctx.bezierCurveTo(130, 62.5, 130, 25, 100, 25);
    ctx.bezierCurveTo(85, 25, 75, 37, 75, 40);
    ctx.fill();
  }
}

I don't know how to find out the highest and lowest x,y values to compute the bounding box. I've started reading the site suggested by @nottesla in their reply. It would be helpful to get your suggestion to this problem.