Create Polygon from Opaque Entries in Raster Data

by Brian Blakely

HTML

<canvas width="300" height="300"></canvas>

CSS

canvas {
    outline: 2px solid green;
    background: grey;
}

JavaScript

var cvs = document.querySelector('canvas'),
    ctx = cvs.getContext('2d');

ctx.lineWidth = 1;
ctx.strokeStyle = 'black';

var cx = cvs.width/2,
    cy = cvs.height/2,
    w = cvs.width*0.45,
    h = cvs.height*0.65,
    v = w/2,
    n = h/2;

ctx.beginPath();
ctx.rect(cx-v, cy-n, w, h);
ctx.ellipse(cx, cy, v*Math.sqrt(2), n*Math.sqrt(2), 0, 0, 2*Math.PI);
ctx.stroke();
ctx.closePath();
var img = document.createElement('img');
img.onload = function() {
    ctx.drawImage(img,cx-v, cy-n, w, h);
    
    ctx.strokeStyle = 'blue';
    
    v=v*Math.sqrt(2);
    n=n*Math.sqrt(2);
    
    var x=0,
        y=0,
        r=0
        deg=3,
        i=0,
        ir=0;
    
    for(
        ;i<360
        ;i+=deg
    ) {
        ir = i*(Math.PI/180);
        r =
            v*n
            /
            Math.sqrt(
                Math.pow(v*Math.sin(ir),2)
                + Math.pow(n*Math.cos(ir),2)
            );
        
        x =
            Math.cos(ir)*r + cx;
        
        y =
            Math.sin(ir)*r + cy;
        
        ctx.fillStyle = 'red';
        ctx.fillRect(x-2, y-2, 4, 4);
        
        ctx.fillStyle = 'blue';
        
        s =
            (y-cy)
            /
            (x-cx);
        
        if((x+0.5|0) === cx) {
            if(y < cy) {
                for(
                    ;y<=cy
                    ;y+=0.1
                ) {
                    ctx.fillRect(x, y, 1, 1);
                }
            } else if(y > cy) {
                for(
                    ;y>=cy
                    ;y-=0.1
                ) {
                    ctx.fillRect(x, y, 1, 1);
                }
            }
        } else if(x < cx) {
            for(
                ;x<=cx
                ;x+=0.1
            ) {
                y = s*(x-cx)+cy;
                
                ctx.fillRect(x, y, 1, 1);
            }
        } else if(x > cx) {
            for(
                ;x>=cx
                ;x-=0.1
            ) {
                y =...