How to render random backgrounds with HTML5 Scratch Card

645 Views Asked by At

I am using HTML5 Scratch Card plugin and dont know how I can render random backgrounds with javascript.Here is the code

window.onload = function() {
            createScratchCard({
                'container':document.getElementById('circle'),
                'background':'assets/images/demo2-circle-background.png',
                'foreground':'assets/images/demo2-circle-foreground.png',
                'percent':100,
                'coin':'assets/images/coin2.png',
                'thickness':18,
            });
        }

So with this default structure how I can render random 2, 3 images and show one every time, show randomly>

1

There are 1 best solutions below

7
On BEST ANSWER

You could set all your file's names into an array and pick one randomly each time.

To make sure your user won't get the same value every time they come to your page, the only solution is to save it somewhere on their side. For this you could use cookies, or as chosen in the above example localStorage :

window.onload = function() {
  // declare your file names
  var theFiles = ["foo.png", "bar.png", "baz.png"];
  // get the saved number we got
  var previous = localStorage.getItem('rolledDices');
  if(previous){
     // parse them and remove them from our array
     var p = previous.split(' ');
     if(p.length-1<theFiles.length){
       p.forEach(function(i){if(i!=='')theFiles.splice(theFiles.indexOf(i),1)})
       }
     // clear the storage if we got all of them
     else{
        previous='';
        }
     }
  // get a new random value from our array
  var randomFn = theFiles[Math.floor(Math.random()*theFiles.length)];
  // add it to the list of saved ones
  localStorage.setItem('rolledDices', (previous||'')+' '+randomFn);

  createScratchCard({
    'container':document.getElementById('circle'),
    'background':'assets/images/'+randomFn,
    'foreground':'assets/images/demo2-circle-foreground.png',
    'percent':100,
    'coin':'assets/images/coin2.png',
    'thickness':18,
    });
  }