使用数据库中的坐标在画布上绘制点

时间:2018-06-05 09:28:17

标签: javascript php arrays database loops

我尝试使用javascript在画布上绘制点但首先,我需要使用php从数据库调用我的x和y坐标,并在使用js绘制它们之前将它们存储在多维数组中。

这是我的代码,我的问题是我得到一张空白画布,换句话说,我的画布上没有画点

<?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();
 }

1 个答案:

答案 0 :(得分:0)

不是php专家,但此代码有效:

<?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>