user3181400
user3181400

Reputation: 1

HTML5 canvas break up image

My overall aim is to make a sliding puzzle piece game. Using the canvas, I have managed to split up the image into multiple pieces. In order to shuffle the pieces, I wrote the co-ordinates of the pieces into an array, shuffled the co-ordinates, and re-drew the image on the canvas. However, the puzzle ends up with some pieces being duplicated! I have no idea why?!

var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
var img=document.getElementById("map");




//img,sx,sy,swidth,sheight,x,y,width,height


function recreate_map(){

ctx.drawImage(img,0,0,133,100,0,0,133,100);
ctx.drawImage(img,133,0,133,100,133,0,133,100);
ctx.drawImage(img,266,0,133,100,266,0,133,100);

ctx.drawImage(img,0,100,133,100,0,100,133,100);
ctx.drawImage(img,133,100,133,100,133,100,133,100);
ctx.drawImage(img,266,100,133,100,266,100,133,100);

ctx.drawImage(img,0,200,133,100,0,200,133,100);
ctx.drawImage(img,133,200,133,100,133,200,133,100);
ctx.drawImage(img,266,200,133,100,266,200,133,100);
}


 function shuffle_array(arr){  
  var i = arr.length;

  while(--i>0){
    var n = Math.floor(Math.random()*(i));
    var temp = arr[n];
    arr[n] = arr[i];
    arr[i] = temp;
  } 

  return arr;
}



function shuffle_tiles(){
  var positions_x = [0,133,266,0,133,266,0,133,266];
  var positions_y = [0,0,0,100,100,100,200,200,200];

  shuffle_array(positions_x);
  shuffle_array(positions_y);



ctx.drawImage(img,0,0,133,100,positions_x[0],positions_y[0],133,100);
ctx.drawImage(img,133,0,133,100,positions_x[1],positions_y[1],133,100);
ctx.drawImage(img,266,0,133,100,positions_x[2],positions_y[2],133,100);
ctx.drawImage(img,0,100,133,100,positions_x[3],positions_y[3],133,100);
ctx.drawImage(img,133,100,133,100,positions_x[4],positions_y[4],133,100);
ctx.drawImage(img,266,100,133,100,positions_x[5],positions_y[5],133,100);
ctx.drawImage(img,0,200,133,100,positions_x[6],positions_y[6],133,100);
ctx.drawImage(img,133,200,133,100,positions_x[7],positions_y[7],133,100);
ctx.drawImage(img,266,200,133,100,positions_x[8],positions_y[8],133,100);  

}

If it helps, I'm using JS Bin, on Firefox. Thanks.

Upvotes: 0

Views: 610

Answers (1)

user1693593
user1693593

Reputation:

You need to clear the canvas for each redraw or else the previous content will remain.

Try this:

function recreate_map(){

    /// call this first
    ctx.clearRect(0, 0, c.width, c.height);

    ctx.drawImage(img,0,0,133,100,0,0,133,100);
    ...

Upvotes: 0

Related Questions