(function() { Perspective = function(ctxd, image) { // check the arguments if( ! ctxd || ! ctxd.strokeStyle ) { return; } if( ! image || ! image.width || ! image.height ) { return; } // prepare a for the image var cvso = document.createElement('canvas'); cvso.width = parseInt(image.width); cvso.height = parseInt(image.height); var ctxo = cvso.getContext('2d'); ctxo.drawImage(image, 0, 0, cvso.width, cvso.height); // prepare a for the transformed image var cvst = document.createElement('canvas'); cvst.width = ctxd.canvas.width; cvst.height = ctxd.canvas.height; var ctxt = cvst.getContext('2d'); // parameters this.p = { ctxd: ctxd, cvso: cvso, ctxo: ctxo, ctxt: ctxt } }; /* ------------------------------------------------------------------- * prototypes * ----------------------------------------------------------------- */ var proto = Perspective.prototype; /* ------------------------------------------------------------------- * public methods * ----------------------------------------------------------------- */ proto.draw = function(points) { var d0x = points[0][0]; var d0y = points[0][1]; var d1x = points[1][0]; var d1y = points[1][1]; var d2x = points[2][0]; var d2y = points[2][1]; var d3x = points[3][0]; var d3y = points[3][1]; // compute the dimension of each side var dims = [ Math.sqrt( Math.pow(d0x-d1x, 2) + Math.pow(d0y-d1y, 2) ), // top side Math.sqrt( Math.pow(d1x-d2x, 2) + Math.pow(d1y-d2y, 2) ), // right side Math.sqrt( Math.pow(d2x-d3x, 2) + Math.pow(d2y-d3y, 2) ), // bottom side Math.sqrt( Math.pow(d3x-d0x, 2) + Math.pow(d3y-d0y, 2) ) // left side ]; // var ow = this.p.cvso.width; var oh = this.p.cvso.height; // specify the index of which dimension is longest var base_index = 0; var max_scale_rate = 0; var zero_num = 0; for( var i=0; i<4; i++ ) { var rate = 0; if( i % 2 ) { rate = dims[i] / ow; } else { rate = dims[i] / oh; } if( rate > max_scale_rate ) { base_index = i; max_scale_rate = rate; } if( dims[i] == 0 ) { zero_num ++; } } if(zero_num > 1) { return; } // var step = 2; var cover_step = step * 5; // var ctxo = this.p.ctxo; var ctxt = this.p.ctxt; ctxt.clearRect(0, 0, ctxt.canvas.width, ctxt.canvas.height); if(base_index % 2 == 0) { // top or bottom side var ctxl = this.create_canvas_context(ow, cover_step); ctxl.globalCompositeOperation = "copy"; var cvsl = ctxl.canvas; for( var y=0; y