In my project I have an image gallery and a canvas to display the image clicked from gallery. For many images, I am drawing rectangles and have the coordinates of the rectangles stored in MySQL. Using JavaScript and PHP, whenever the image from the gallery is clicked, based on the image name I am fetching the rectangle coordinates from MySQL.
The codes to fetch the values from MySQL as an array to JavaScript is as follows:
<?php
$connect = mysql_connect("localhost", "root", "");
mysql_select_db("mydb");
$clickedImg = $_POST['clickedImg'];
$query = mysql_query("select x,y,w,h from annotations where imagename = '$clickedImg'");
while ($row = mysql_fetch_assoc($query)){
print_r($row);
}
?>
Instead of print_r when I tried echo, it just returns a blank array. The fetched array when printed on console looks like this:
Array
(
[x] => 369
[y] => 327
[w] => 147
[h] => 112
)
Array
(
[x] => 228
[y] => 329
[w] => 129
[h] => 106
)
My original script to draw rectangles at fixed locations is as follows:
function draw(canvas, event){
ctx=c.getContext("2d");
ctx.fillStyle="#ff0000";
ctx.beginPath();
ctx.fillRect (250*Math.random()+1, 220*Math.random()+1, 40, 30);
ctx.closePath();
ctx.fill();
// Save canvas
saveCanvas(canvas);
}
This just prints rectanges at random locations. I want to use the values in the above mentioned array in the place of ctx.fillRect
.
I tried the following:
function draw(canvas, event){
ctx=c.getContext("2d");
ctx.fillStyle="#ff0000";
ctx.beginPath();
for (var i=0; i<=newrects.length;i++) {
var r = newrects[i];
alert(r);
ctx.fillRect (r.x, r.y, r.w, r.h);
}
ctx.closePath();
ctx.fill();
// Save canvas
saveCanvas(canvas);
}
I essentially want to draw the rectangles using the values in the Array. But the current for loop inside draw function is not reading the values. Hence, I am not sure if the format in which I receive the values from PHP is correct or not.
How can use the values from the array in the for loop of my draw function.