vendredi 21 mai 2021

How can I update the object location from the database and draw it on canvas?

Using javascript, I want to move the robot shapes that I draw on the canvas by taking the robot position simultaneously from the mysql database. For this, I used the requestAnimationFrame () function and typed a function called redraw () and deleted the shapes I had drawn in it and redrawed them, just like the following link: https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API/Tutorial/Basic_animations But when I do it like this, although I see the change of location while doing get request inside my redraw () function and retrieving the locations from the database, I think because too many redraws are called, the page contracts and the page is not refreshed. How can I solve this problem and why is it caused? here is js part of the code :

 function init(){   
    canvas = document.getElementById('nav2dmap');
    stage = new createjs.Stage(document.getElementById('nav2dmap'));
    var image = new Image();
    image.src = "http://localhost:7427/map.png";
    window.requestAnimationFrame(redraw);
 }


var redraw = function(){         
    var image = new Image();
    image.src = "http://localhost:7427/map.png";
    var bitmap = new createjs.Bitmap(image);
    bitmap.scaleX = canvas.getBoundingClientRect().width / bitmap.image.width;
    bitmap.scaleY = canvas.getBoundingClientRect().height  / bitmap.image.height;
    stage.addChild(bitmap);
    stage.update();
    
for(let i = 0; i < stations.length; i++){
    radius = 7;
    let color = 'skyblue';
    if(selected_station == i) color = 'red'; // selected station color will be red else skyblue
        drawPolygon(color, ctx, dontScaleX(parseFloat(stations[i].x)),
            dontScaleY(parseFloat(stations[i].y)), radius, parseFloat(stations[i].oz), 3); 
}


for(let i=0; i<robotDatas.length; i++){
    let color = 'lime';
    if(robotDatas[i].selected)  
       drawPolygon(color, ctx, dontScaleX(parseFloat(robotDatas[i].x)),
            dontScaleX(parseFloat(robotDatas[i].x)),8, dontScaleY(parseFloat(robotDatas[i].y)), 4);            
}


axios.get('http://localhost:7427/api/robots', {
})
.then(function(response) {
    console.log("RT --->  get req");
    for(let i=0; i<robotDatas.length; i++){
        robotDatas[i].x  = response.data[i].location_x,
        robotDatas[i].y  = response.data[i].location_y, 
        robotDatas[i].oz = response.data[i].location_th 
    } 
})
.catch(function(error) {
    if(error.response.status == 404) {
        alert("No robot(s) were found");
    }
    else if(error.response.status == 500) {
        alert("Database Error");
    }
    alert(error.response.data);
});

window.requestAnimationFrame(redraw);
}



Aucun commentaire:

Enregistrer un commentaire