Skip to content

Instantly share code, notes, and snippets.

@akx
Created May 24, 2016 15:40
Show Gist options
  • Select an option

  • Save akx/1298e75527adf07629377f0c737faf29 to your computer and use it in GitHub Desktop.

Select an option

Save akx/1298e75527adf07629377f0c737faf29 to your computer and use it in GitHub Desktop.
Chamfered Quads
<!DOCTYPE html>
<html lang="en">
<body>
<script>
var canvas = document.createElement('canvas');
canvas.width = canvas.height = 800;
var ctx = canvas.getContext('2d');
document.body.appendChild(canvas);
function lerpPoint(pa, pb, alpha) {
var beta = 1.0 - alpha;
return {
x: pa.x * beta + pb.x * alpha,
y: pa.y * beta + pb.y * alpha
};
}
function lineLength(x1, y1, x2, y2) {
var dx2 = (x2 - x1) * (x2 - x1);
var dy2 = (y2 - y1) * (y2 - y1);
return Math.sqrt(dx2 + dy2);
}
function ptDistance(a, b) {
return lineLength(a.x, a.y, b.x, b.y);
}
function chamferedQuad(pA, pB, pC, pD, radA, radB, radC, radD) {
ctx.beginPath();
var lAB = ptDistance(pA, pB);
var lBC = ptDistance(pB, pC);
var lCD = ptDistance(pC, pD);
var lAD = ptDistance(pA, pD);
var a = lerpPoint(pA, pB, radA / lAB);
var b = lerpPoint(pB, pA, radB / lAB);
var c = lerpPoint(pB, pC, radB / lBC);
var d = lerpPoint(pC, pB, radC / lBC);
var e = lerpPoint(pC, pD, radC / lCD);
var f = lerpPoint(pD, pC, radD / lCD);
var g = lerpPoint(pD, pA, radD / lAD);
var h = lerpPoint(pA, pD, radA / lAD);
ctx.moveTo(a.x, a.y);
ctx.lineTo(b.x, b.y); // line a b
ctx.quadraticCurveTo(pB.x, pB.y, c.x, c.y); // curve b B c
ctx.lineTo(d.x, d.y); // line c d
ctx.quadraticCurveTo(pC.x, pC.y, e.x, e.y); // curve d C e
ctx.lineTo(f.x, f.y); // line e f
ctx.quadraticCurveTo(pD.x, pD.y, g.x, g.y); // curve f D g
ctx.lineTo(h.x, h.y); // line g h
ctx.quadraticCurveTo(pA.x, pA.y, a.x, a.y); // curve h A a
ctx.stroke();
}
chamferedQuad(
{x: 10, y: 10},
{x: 150, y: 10},
{x: 150, y: 150},
{x: 10, y: 100},
30,
0,
50,
0
);
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment