简体   繁体   中英

How to pass data retrieved from mysql into a javascript for ploting dots on canvas

I need to plot multiple dots over a canvas with data retrieved from mysql. I just cant find out how to pass that data from one to another.

I select the coordinates like this:

<?php
$idnumber=htmlspecialchars($_SESSION['idnumber']);
if ($mark = $pdo->prepare("SELECT x, y FROM numbers WHERE id = ? ")) { 
        $mark ->execute(array($idnumber));
        $data = $mark->fetchAll();
}
?>

And then I have this layout where I need to apply the multiple dots using the coordinates fetched. Like this:

 <img id="markers" width="1002px" height="631px" src="images/markers.jpg" hidden="hidden"/>
<script>
window.onload = function() {
    var canvas = document.getElementById("myCanvas");
    var ctx = canvas.getContext("2d");
    var img = document.getElementById("markers");
    var x = // (no idea how)
    var y = // (no idea how)
   ctx.drawImage(img, 0, 0);
   ctx.beginPath();
   ctx.arc(x, y, 4, 0, 2 * Math.PI); //where x and y should hold the coordinates. With some kind of loop so It will plot all the dots available on the database for that specific id. 
   ctx.fill();
};
</script>
<canvas id="myCanvas" width="1002px" height="631px"></canvas>

The easiest way to do this in PHP would be using json_encode() .

You can simply write on your index.php:

<?php
  $idnumber=htmlspecialchars($_SESSION['idnumber']);

  if ($mark = $pdo->prepare("SELECT x, y FROM numbers WHERE id = ? ")) { 
    $mark ->execute(array($idnumber));
    $data = $mark->fetchAll();
  }
?>
<!-- [...] -->
<script>
  var data = <?=json_encode($data)?>;
</script>
<!-- [...] -->

And then data should contain all the values you need. But this is not a very clean way to do it (In my opinion).

Cleaner would be using AJAX.

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.

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