这是我的代码: 我从aws mysql服务器获得坐标并试图解析它并在画布上绘制点。 我现在正在做的是绘制所有点,但我想逐个绘制点,以便创建一个有人移动的效果,我想要清除前一点,以便画布上只有1个点。怎么做?
我认为的一种方法是每次都清除画布,然后图像也会被清除。所以一次又一次地加载图像会不会很好。
<!DOCTYPE html>
<html>
<body>
<img id="scream" src="imgbwb.jpg" alt="The Scream" width="960" height="576" style="display: none;">
<h1 id="demo">Plot the dots </h1>
<canvas id="myCanvas" width="1000" height="600" style="border:1px solid #d3d3d3;"> Your browser does not support the HTML5 canvas tag.</canvas>
<br>
<h1> Data which i am plotting </h1>
<br>
<?php
$con=mysqli_connect("xxx.xx.us-west-2.rds.amazonaws.com","admin","xxx","xx");
if (mysqli_connect_errno($con)) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"Select data from trailData order by id desc limit 10");
if ($result->num_rows > 0) {
$x=array();
$y=array();
while($row = $result->fetch_assoc()) {
$temp=$row["data"];
$myArray = explode('*', $temp);
//print_r($myArray);
for($i=0;$i<count($myArray)-2;$i+=2)
{
$a=$myArray[$i];
$b=$myArray[$i+1];
array_push($x,$a);
array_push($y,$b);
}
}
echo "<h3>X co-ordinates</h3>";
print_r($x);
echo "<br>";
echo "<h3>Y co-ordinates</h3>";
print_r($y);
}
else
{echo "0";}
?>
<!-- Script starts from here -->
<script type="text/javascript">
//Simple header text change function on click
document.getElementById("demo").onclick = function() {myFunction()};
function myFunction() {
document.getElementById("demo").innerHTML = "Don't click me you putang ina mo!";
}
// Actual canvas code
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
var img = document.getElementById("scream");
ctx.drawImage(img,10,10);
ctx.fillStyle="#FF0000";
var xObj = <?php echo json_encode($x); ?>;
var yObj = <?php echo json_encode($y); ?>;
console.log(typeof(xObj));
console.log(xObj);
console.log(yObj);
var i,x,y;
for (i = 0; i < xObj.length; i++) {
x = xObj[i];
y = yObj[i];
//ctx.fillRect(x,y,10,10);
var centerX = x
var centerY = y
var radius = 10;
ctx.beginPath();
ctx.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
ctx.fillStyle = 'green';
ctx.fill();
ctx.lineWidth = 2;
ctx.strokeStyle = '#003300';
ctx.stroke();
setTimeout(function(){/* Look mah! No name! */},2000);
}
//ctx.fillRect(780,580,10,10);
</script>
</body>
</html>
答案 0 :(得分:1)
您可以通过清除画布并重新绘制点来获得移动效果。但您可以使用CSS将图像设置为画布的背景(而不是在画布上绘制)以避免重新绘制图像。