perspective2
perspective try 2
by tepp yogi
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/numeric/1.2.6/numeric.min.js"></script>
<body>
<img id="sourceImg" src="https://s32.postimg.org/60hns28p1/chess.jpg" />
<canvas id="sourceCanvas" ></canvas>
<canvas id="destinationCanvas" ></canvas>
</body>
CSS
img { visibility: hidden; display: none; }
canvas { width: 45%; height: 100%; borders: solid; }
#destinationCanvas { visibility: hidden; }
JavaScript
var srcImg, width, height, srcCvs, srcC, srcRect, dstCvs, dstC, widthToHeight;
var nbClicks = 0, coordinates = Array( 8 );
srcImg = document.getElementById( 'sourceImg' );
widthToHeight = srcImg.width / srcImg.height;
srcCvs = document.getElementById( 'sourceCanvas' );
srcC = srcCvs.getContext( '2d' );
dstCvs = document.getElementById( 'destinationCanvas' );
dstC = dstCvs.getContext( '2d' );
width = srcCvs.width = dstCvs.width = srcCvs.clientWidth;
height = srcCvs.height = dstCvs.height = srcCvs.clientWidth / widthToHeight;
srcRect = srcCvs.getBoundingClientRect();
srcC.strokeStyle = '#0f0';
srcC.drawImage( srcImg, 0, 0, width, height );
srcCvs.addEventListener( 'click', doClick, false );
function doClick( event ) {
if ( nbClicks < 4 ) {
coordinates[ nbClicks * 2 ] = ( event.clientX - srcRect.left ) * width / srcRect.width;
coordinates[ nbClicks * 2 + 1 ] = ( event.clientY - srcRect.top ) * height / srcRect.height;
srcC.strokeRect( coordinates[ nbClicks * 2 ] - 10, coordinates[ nbClicks * 2 + 1 ] - 10, 20, 20 );
}
if ( ++nbClicks == 4 ) {
dstC.beginPath();
dstC.moveTo( coordinates[ 0], coordinates[ 1 ] );
for( i = 1; i < 4; i ++ ) {
dstC.lineTo( coordinates[ i*2 ], coordinates[ i*2 + 1 ] );
}
dstC.closePath();
dstC.clip();
dstCvs.style.visibility = 'visible';
dstC.drawImage( srcImg, 0, 0, width, height );
var left = 0, top = 0, w = width, h = width;
srcC.strokeStyle = '#f00';
srcC.strokeRect( left - 10, top - 10, 20, 20 );
srcC.strokeRect( left + w - 10, top - 10, 20, 20 );
srcC.strokeRect( left + w - 10, top + h - 10, 20, 20 );
srcC.strokeRect( left - 10, top + h - 10, 20, 20 );
alert( 'Clipped image is now drawn, going to apply transform after this alert. On the left canvas, the positions of the mapped points are drawn in red.' );
var t = getTransform( left, top, w, h );
dstCvs.style.transform = t;
}
};
function adj(m) { // Compute the adjugate of m
return [
...