简体   繁体   English

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

[英]draw points on canvas using coordinates from database

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. 我正在尝试使用javascript在画布上绘制点,但是首先,我需要使用php从数据库中调用x和y坐标并将它们存储在多维数组中,然后再使用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方面的专家,但是此代码有效:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM