I'm trying to draw points on my canvas using javascript but first, I need to call my x and y coordinates from the database with php and store them in a multidimensional array before I draw them using js.
Here is my code and my problem is that I get a blank canvas or in other words, no points were being drawn on my canvas
<?php
$conn = mysqli_connect("localhost","root","","login");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$query = "SELECT * FROM sample";
if ($result = mysqli_query($conn,$query)) {
echo 'var points=[';
foreach( $result as $row ) {
echo "{x:${row['x']}, y:${row['y']}},";
}
echo "];\n";
mysqli_free_result($result);
}
mysqli_close($conn);
?>
for(var p in points) {
ctx.beginPath();
ctx.arc(p.x , p.y, 2, 0, 2 * Math.PI, false);
ctx.fill();
ctx.stroke();
ctx.closePath();
}
Not an expert in php, but this code works:
<?php
$conn = mysqli_connect("localhost","root","","login");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$query = "SELECT * FROM sample";
if ($result = mysqli_query($conn,$query)) {
// Fetch one and one row
$array=array();
while ($row=mysqli_fetch_array($result, MYSQL_ASSOC))
{
array_push($array,[$row['x'],$row['y']]);
}
}
mysqli_free_result($result);
mysqli_close($conn);
?>
<script>
var canvas=document.getElementById('mon_canvas');
var ctx=canvas.getContext('2d');
var points =<?php echo json_encode($array) ?>;
alert(points);
for(var i=0;i<points.length;i++) {
ctx.beginPath();
ctx.arc(points[i][0] , points[i][1], 2, 0, 2 * Math.PI, false);
ctx.fill();
ctx.stroke();
ctx.closePath();
}
</script>
</body>
</html>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.