JSFiddle - React, Tailwind, and code Playground
by vixing
HTML
<canvas id="board" width="601" height="401"></canvas>
CSS
canvas, img{
border: solid green 1px;
}
JavaScript
var ca = document.getElementById("board");
var c = ca.getContext("2d");
var cW = ca.width;
var cH = ca.height;
var grid = 40;
var x = 0;
for (var i = -1;i < Math.floor(cW/grid); i += 1){
c.beginPath();
c.rect(x+0.5,0.5,grid,grid);
c.stroke();
x += grid;
};
x = grid;
var how = Math.floor(cH/grid);
for (i = 1;i <= how; i *= 2){
c.beginPath();
c.drawImage(ca,0,x);
x *= 2;
}
var tempCa = document.createElement("canvas");
tempCa.width = cW;
tempCa.height = cH;
tempCa.ctx = tempCa.getContext("2d");
tempCa.ctx.drawImage(ca,0,0);
c.clearRect(0,0,cW,cH);
keystoneAndDisplayImage(c,tempCa,0,0,cH,2);
var url = "http://i.imgur.com/pTK2zGh.png";
var newImg = document.createElement("img");
newImg.src = url;
document.body.appendChild(newImg);
function keystoneAndDisplayImage(ctx, img, x, y, pixelHeight, scalingFactor) {
var h = img.height,
w = img.width,
numSlices = Math.abs(pixelHeight),
sliceHeight = h / numSlices,
polarity = (pixelHeight > 0) ? 1 : -1,
heightScale = Math.abs(pixelHeight) / h,
widthScale = (1 - scalingFactor) / numSlices;
for(var n = 0; n < numSlices; n++) {
var sy = sliceHeight * n,
sx = 0,
sHeight = sliceHeight,
sWidth = w;
var dy = y + (sliceHeight * n * heightScale * polarity),
dx = x + ((w * widthScale * n) / 2),
dHeight = sliceHeight * heightScale,
dWidth = w * (1 - (widthScale * n));
ctx.drawImage(img, sx, sy, sWidth, sHeight,
dx, dy, dWidth, dHeight);
}
}