user3011902
user3011902

Reputation:

Javascript Canvas Skew Image Vertically

Is it possible to skew an image on a canvas to make it appear as a reflection of another image?

Here is an illustration:

I am not an Artist

I need to flip and skew the image to get the desired effect, but I have not been able to get it to look like that. How can this be achieved?

I have found this example:

http://jsfiddle.net/jpnrzc9y/

ctx.save();
ctx.transform(1,0,0.3,-1,0,0);
ctx.drawImage(tree1,74,-117,20,40);
ctx.restore();

They seem to set the transform based on some random values.

But I cannot make sense of it. The values seem very random to me. Im trying to create a dynamic function that allows me to determine the amount of skew and that works for all images.

Upvotes: 3

Views: 1662

Answers (1)

markE
markE

Reputation: 105015

enter image description here

You can use context.scale to flip an image vertically:

// flip the canvas vertically
context.scale(1,-1);

Here are the steps to create a skewed reflection of an image:

  1. Move (move==translate) the 0,0 origin to the desired x,y: ctx.translate(x,y);

  2. Draw the original image image: ctx.drawImage(img,0,0);

  3. Move to the bottom of the original image: ctx.translate(0,img.height);

  4. Scale to vertically flip the image: ctx.scale(1,-1);

  5. Apply a skew: ctx.transform(1,0,skewAngle,1,0,0);

  6. Shrink the reflected image (just for aesthetics): ctx.scale(1,0.50);

  7. Make the reflected image 50% opacity: ctx.globalAlpha=0.50;

  8. Draw the reflected image: ctx.drawImage(img,0,-img.height);

  9. Clean up by setting all transforms to default: ctx.setTransform(1,0,0,1,0,0);

Here's example code and a demo:

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

var img=new Image();
img.onload=start;
img.src="https://dl.dropboxusercontent.com/u/139992952/multple/character1.png";
function start(){
  // 60x110
  skewedReflection(img,25,25)
}

function skewedReflection(img,x,y){
  // calc the 45 degree skew angle needed by ctx.transform
  var skewAngle=-Math.tan(Math.PI/4);
  // move the 0,0 origin to x,y
  ctx.translate(x,y);
  // draw the original image image 
  ctx.drawImage(img,0,0);
  // move to the bottom of the original image
  ctx.translate(0,img.height);
  // use scale to flip the image
  ctx.scale(1,-1);
  // apply a skew
  ctx.transform(1,0,skewAngle,1,0,0);
  // shrink the reflected image
  ctx.scale(1,0.50);
  // make the reflected image 50% opacity
  ctx.globalAlpha=0.50;
  // draw the reflected image
  ctx.drawImage(img,0,-img.height);
  // clean up by setting all transforms to default
  ctx.setTransform(1,0,0,1,0,0);
}
body{ background-color: ivory; }
#canvas{border:1px solid red; margin:0 auto; }
<canvas id="canvas" width=300 height=300></canvas>

Upvotes: 3

Related Questions