单击按钮存储后如何存储X和Y坐标

时间:2019-03-25 12:14:07

标签: javascript ionic-framework

我试图在画布上单击后存储x和y坐标,我可以设置标记位置,我可以在该位置显示x和y坐标以及标记图片,但是现在我想存储这些坐标,以便当您重新加载Web浏览器时,标记位置仍将位于他第一次放置它的位置。

完整的代码..

var context = (this.canvas.nativeElement as HTMLCanvasElement).getContext("2d")

//Map sprite
var mapSprite = new Image();
mapSprite.src = "http://antyradar.info/wp-content/uploads/commercial-tumilty-design-commercial-floor-plans.jpg";

var Marker = function () {
this.Sprite = new Image();
this.Sprite.src = "https://www.lasvegas-waterdelivery.com/wp-content/uploads/2016/07/5gal-cropped.png"
this.Width = 12;
this.Height = 20;
this.XPos = 0;
this.YPos = 0;
}

  var Markers = new Array();
  var rect = (this.canvas.nativeElement as HTMLCanvasElement).getBoundingClientRect();

  var mouseClicked = function (mouse) {
  // Get current mouse coords
  var mouseXPos = (mouse.x - rect.left);
  var mouseYPos = (mouse.y - rect.top);



  console.log("x: " + mouseXPos);
  console.log("y: " + mouseYPos)
  console.log("Marker added");

  // Move the marker when placed to a better location
  var marker = new Marker();
  marker.XPos = mouseXPos - (marker.Width * 37.7);
  marker.YPos = mouseYPos - (marker.Height * 7);

  Markers.push(marker);

  for (var i = 0; i < Markers.length; i++) {
    if(i > 1){
      Markers.splice(marker);
    }
  }


  sessionStorage.setItem('Marker', JSON.stringify(marker));
  let store = sessionStorage.getItem('Marker');

  console.log(store);

  var remember = function(){
    return store;
  }
}

// Add mouse click event listener to canvas
/* (this.canvas.nativeElement as HTMLCanvasElement).addEventListener("mousedown", mouseClicked, false); */

var firstLoad = function () {
  context.font = "15px Georgia";
  context.textAlign = "center";
}

firstLoad();

var main = function () {
  draw();
};

var width = (this.canvas.nativeElement as HTMLCanvasElement).width
var height = (this.canvas.nativeElement as HTMLCanvasElement).height
var draw = function () {
  // Clear Canvas
  context.fillStyle = "#000";
  context.fillRect(0, 0, width, height);

  // Draw map
  // Sprite, X location, Y location, Image width, Image height
  // You can leave the image height and width off, if you do it will draw the image at default size
  context.drawImage(mapSprite, 0, 0, 700, 700);

  // Draw markers
  for (var i = 0; i < Markers.length; i++) {
    var tempMarker = Markers[i];
    // Draw marker
    context.drawImage(tempMarker.Sprite, tempMarker.XPos, tempMarker.YPos, tempMarker.Width, tempMarker.Height);
  }
};

setInterval(main, (1000 / 10)); // Refresh 60 times a second

}

2 个答案:

答案 0 :(得分:0)

您可以使用Window.sessionStorage存储坐标。

sessionStorage.setItem('Marker', JSON.stringify(marker));

答案 1 :(得分:0)

如果这是ionic 3,则也应在提供者中将信息存储在提供程序中,也应使其在页面之间/刷新时保持一致,或对ionic 4使用服务(https://www.youtube.com/watch?v=MUvDM55PN9k-教程)。要在关闭和打开应用程序后保留信息,您可以使用离子文件插件https://ionicframework.com/docs/native/file或其他此类本机存储。