tiles

HTML

<canvas width='480' height='300' id='cv'>

JavaScript

// parameters 
var tileSize = 20; // size of the pattern tiles
var maxPolygonSize = 400; // maximum size (width or height) of a polygon

// example
var polyShape = [160, 100,
180, 90,
220, 85,
280, 120,
300, 160,
280, 200,
240, 250,
210, 255,
180, 230,
150, 200,
140, 160];
//
var polyWarmRect = [0, 0, 0, 0];

// 
var cv = document.getElementById('cv');
var ctx = cv.getContext('2d');

// build once the canvas used for low-res drawings
var lowResCanvasSize = Math.floor(maxPolygonSize / tileSize) + 1;
var lowResCv = document.createElement('canvas');
lowResCv.height = lowResCanvasSize;
lowResCv.width = lowResCanvasSize;
var lowResCtx = lowResCv.getContext('2d');

// draws [poly] with the [patterns]
function fillPolyWithPattern(ctx, poly, patterns) {
    var i = 0;
    var patternIndex = 0;
    var randomBase = Math.floor(poly[0] + poly[1]);
    // find bounding rect of this poly
    findPolygonRect(poly, polyRect);
    // draw the poly at a lower resolution
    // on the lowRes canvas
    lowResCtx.clearRect(0, 0, lowResCanvasSize, lowResCanvasSize);
    lowResCtx.save();
    lowResCtx.scale(1 / tileSize, 1 / tileSize);
    lowResCtx.translate(-polyRect[0], -polyRect[1]);
    lowResCtx.fillStyle = '#F00';
    fillPolygon(lowResCtx, poly);
    lowResCtx.restore();
    // get the data for the lowRes canvas
    var maxXTile = Math.floor(polyRect[2] / tileSize) + 1;
    var maxYTile = Math.floor(polyRect[3] / tileSize) + 1;
    var data = lowResCtx.getImageData(0, 0, maxXTile, maxYTile).data;
    // draw the polygon with the tiles
    var xy = 0,
        yt = 0;
    ctx.save();
    ctx.translate(polyRect[0], polyRect[1]);
    for (xt = 0; xt < maxXTile; xt++) {
        for (yt = 0; yt < maxYTile; yt++) {
            var pxIndex = xt + yt * maxXTile;
            if (data[((pxIndex) << 2)]) {
                // randomize the tile that will be used
                var thisRandomNumber = getRandomNumber(randomBase, xt, yt);

                patternIndex = thisRandomNumber %...