I have this code:
Storage.prototype.setObj = function(key, obj) {
return this.setItem(key, JSON.stringify(obj))
}
Storage.prototype.getObj = function(key) {
return JSON.parse(this.getItem(key))
}
function onReady() {
if (localStorage["piecesArray"]) {
piecesArray = new Array();
piecesArray.length = 0;
piecesArray = localStorage.getObj("piecesArray");
} else {
piecesArray = new Array();
}
can = document.getElementById('myCanvas');
ctx = can.getContext('2d');
img = new Image();
img.onload = onImage1Load;
img.src = "http://www.niagaraparks.com/images/wallpaper/niagarafalls_640x480.jpg";
}
And I want to save the game state in localStorage, and after refreshing the page I want to refresh the game state.
What am I doing wrong?
So, there's two problems I noticed in your fiddle.
First, you have a function you're calling that isn't defined, so you're not running the setObj function.
if (drawHighlight) highlightRect(drawX, drawY);
// liczymy kliknięcia
clickCounter(); // This function doesn't exist
localStorage.setObj("piecesArray", piecesArray);
I added in a dummy clickCounter function for you that doesn't do anything.
Additionally, you were loading up the piecesArray from local storage, but then just overwriting it anyway. Once your image loads, you need to check to see if you already have a piecesArray. I did that like this:
function onImage1Load() {
var r;
if (piecesArray.length === 0) {
for (var i = 0; i < 4; i++) {
for (var j = 0; j < 3; j++) {
r = new Rectangle(i * blockSize, j * blockSize, i * blockSize + blockSize, j * blockSize + blockSize);
piecesArray.push(r);
}
}
scrambleArray(piecesArray, 30);
}
drawImage();
}
Working Fiddle
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With