Aaron George
Aaron George

Reputation: 138

JS | Slicing a polygon that has an image clipped to it, into two polygons

I'm drawing a polygon to the canvas, which has an image clipped inside of it.

On touch start and end, I'm slicing that polygon into two polygons and rotating them and pushing them away from each other. Similar functionality to Fruit Ninja.

My issue is drawing the image to the new polygons, so make it look like you have sliced the image in half and it's now rotating away.

Does anyone have any advice. I don't necessarily need code, I just need to understand how it's done so I can program it.

Thanks heaps.

Upvotes: 1

Views: 141

Answers (1)

markE
markE

Reputation: 105015

Infinite designs are possible, but for example...

  • Use translate to set the rotation point outside the polygon.
  • rotate to a positive angle and draw the left half of the poly.
  • Reset the transformations.
  • Use translate to set the rotation point outside the polygon.
  • rotate to a negative angle and draw the right half of the poly.
  • Reset the transformations.

Demo:

var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var cw=canvas.width;
var ch=canvas.height;

var cx=50;
var cy=20;
var r=20;
var angle=0;
ctx.fillStyle='salmon';
ctx.strokeStyle='forestgreen';
ctx.lineWidth=3;
requestAnimationFrame(animate);

function draw(angle){
  ctx.clearRect(0,0,cw,ch);

  // left side
  ctx.translate(cx,cy+40);
  ctx.rotate(angle);
  ctx.beginPath();
  ctx.arc(cx,cy,r,Math.PI/2,Math.PI*3/2);
  ctx.fill();
  ctx.stroke();
  ctx.setTransform(1,0,0,1,0,0);

  // right side
  ctx.translate(cx,cy+40);
  ctx.rotate(-angle);
  ctx.beginPath();
  ctx.arc(cx,cy,r,Math.PI*3/2,Math.PI/2);
  ctx.fill();
  ctx.stroke();
  ctx.setTransform(1,0,0,1,0,0);
}

function animate(){
  draw(angle);
  angle+=Math.PI/720;
  if(angle<Math.PI/4){ requestAnimationFrame(animate); }
}
body{ background-color: ivory; }
#canvas{border:1px solid red; margin:0 auto; }
<canvas id="canvas" width=200 height=200></canvas>

Upvotes: 2

Related Questions