Reputation: 947
I'm attempting to have a canvas print circles one by one at coordinates provided in a database. Currently it works by printing all the circles at the 'same time', so the next part is to have them print one by one so the user can watch. It's a little messy with the JavaScript embedded in the php while loop. I imagine a more efficient way to pass the data to javascript would be to use JSON, but this is just a quick thing I've thrown together to see what's possible.
I tried setting a timeout around the code that draws the circle, but all this did was delay the process by the set time before drawing all the circles together as opposed to delaying each time it went round the loop. I also tried php code sleep(1)
within the loop which had a similar outcome.
Is this related to JavaScript being client side and php server side?
<?php
// Create connection
$conn = mysqli_connect($servername, $username, $password, $db);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
echo "<br/>";
echo "<br/>";
?>
</head>
<body>
<canvas id="myCanvas" width="300" height="150" style="border:1px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.</canvas>
<?php
$sql = "SELECT xcoord, ycoord FROM population LIMIT 10";
$result = mysqli_query($conn, $sql);
while($row = mysqli_fetch_array($result)) {
$xcoord = $row['xcoord'];
$ycoord = $row['ycoord'];
?>
<script>
var x = "<?php echo $xcoord; ?>";
var y = "<?php echo $ycoord; ?>";
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.beginPath();
ctx.arc(x, y, 5,0, 2*Math.PI);
ctx.fillStyle = "red";
ctx.fill();
ctx.stroke();
</script>
<?php
}
mysqli_close($conn);
?>
Upvotes: 0
Views: 238
Reputation: 5607
I would highly encourage you to just send all of the data to the JS layer, and then having the execution delays handled by the UI side, but if you're interested in knowing why your sleep
is not quite working - the explanation is here:
By default, most PHP configurations will store the entire page in a buffer, only sending it to the browser when the PHP script is completely finished. You can usually circumvent this behavior by forcing the output buffer to "flush" to the client whenever you want to send data to it immediately with ob_flush.
Upvotes: 2