I need to draw a square with Canvas in an image. This image comes from the database, where it has different dimensions. I am able to draw the square in the center of the image, but if the image is wider, the Canvas is out of proportion. Is it possible, 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 make 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>