Can you calculate the diagonal on canvas?

Asked

Viewed 182 times

5

I need to draw a square with Canvas in an image. This image comes from the database, where it has different dimensions. I’m able to draw the square in the center of the image, but if the image is wider, the canvas goes out of proportion. It has as instead of taking the height and width of the image, take its diagonal or inches so that the square does not go out of proportion?

Here is the code used to do Canvas:

<script type="text/javascript">
    function init(i) {
        var img = document.getElementById("foto" + i);
        var cs = getComputedStyle(img);
        var width = parseInt(cs.getPropertyValue('width'));
        var height = parseInt(cs.getPropertyValue('height'));
        $('#contentCanvas' + i).html('<canvas id="myCanvas' + i + '" width="' + width + '" height="' + height + '" >');
        drawImg(img, cs, width, height, i);
    }
    function drawImg(img, cs, width, height, i) {
        var myCanvas = 'myCanvas' + i;
        var canvas = document.getElementById(myCanvas);
        var c = document.getElementById(myCanvas);
        var ctx = c.getContext("2d");
        var context = canvas.getContext('2d');
        ctx.drawImage(img, 0, 0, width, height);
        drawRetangle(context, width, height);
    }
    function drawRetangle(context, width, height) {
        position_x = parseInt(width) / 2;
        position_y = parseInt(height) / 2;

        position_x = parseInt(position_x) - 20;
        position_y = parseInt(position_y) - 17;

        context.beginPath();
        context.rect(position_x, position_y, 39, 34);
        context.lineWidth = 1;
        context.strokeStyle = '#00FF00';
        context.stroke();
    }
</script>
  • Yes. Hipotenusa Formula. Hˆ2 = Cˆ2 + Cˆ2

1 answer

2


If you have the height and width, you can calculate the diagonal from this.

It can be solved using the Pythagorean theorem as follows: Diagonal² = height² + width²;

In js:

var diagonal = Math.sqrt(Math.pow(height, 2) + Math.pow(width,2), 2);

I hope I’ve helped.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.