Skip to content

Instantly share code, notes, and snippets.

@threedaymonk
Created July 12, 2009 00:31
Show Gist options
  • Save threedaymonk/145453 to your computer and use it in GitHub Desktop.
Save threedaymonk/145453 to your computer and use it in GitHub Desktop.
Simple quadratic interpolation in JavaScript/Canvas
<!DOCTYPE HTML>
<html>
<head>
<title>あ</title>
</head>
<body>
<canvas id="c" width="300" height="300"></canvas>
<script>
function lineN(context, data) {
context.beginPath();
context.moveTo(data[0][0], data[0][1]);
for (var i = 1; i < data.length; i++) {
context.lineTo(data[i][0], data[i][1]);
}
context.stroke();
context.closePath();
}
function lineNSmooth(context, data) {
var smoothed = [[data[0][0], data[0][1]]];
for (var i = 0; i < (data.length - 1); i++) {
var x0 = data[i][0];
var y0 = data[i][1];
var x2 = data[i+1][0];
var y2 = data[i+1][1];
var x1 = x0 + (x2 - x0) / 2;
var y1 = y0 + (y2 - y0) / 2;
smoothed.push([x1, y1]);
smoothed.push([x2, y2]);
}
context.beginPath();
context.moveTo(smoothed[0][0], smoothed[0][1]);
context.lineTo(smoothed[1][0], smoothed[1][1]);
for (var i = 2; i < (smoothed.length - 2); i += 2) {
context.quadraticCurveTo(smoothed[i][0], smoothed[i][1], smoothed[i+1][0], smoothed[i+1][1]);
}
context.lineTo(smoothed[smoothed.length-1][0], smoothed[smoothed.length-1][1]);
context.stroke();
context.closePath();
}
var context = document.getElementById("c").getContext("2d");
var letters = {
"a": [[[ 54, 58], [249, 68]],
[[147, 10], [145, 201], [182, 252]],
[[224, 103], [149, 230], [ 82, 240], [ 53, 204], [ 86, 149], [182, 139], [240, 172], [248, 224], [228, 250]]],
"i": [[[ 56, 63], [ 43, 213], [ 67, 259], [ 94, 243]],
[[213, 66], [231, 171], [208, 217]]],
"u": [[[102, 35], [187, 45]],
[[ 73, 121], [167, 105], [206, 139], [198, 211], [135, 275]]],
"e": [[[140, 19], [162, 38]],
[[ 62, 105], [208, 100], [ 51, 263], [128, 205], [188, 268], [260, 252]]],
"o": [[[ 64, 94], [240, 98]],
[[148, 35], [159, 129], [140, 199], [105, 247], [ 64, 228], [101, 161], [192, 161], [222, 223], [189, 257]],
[[223, 49], [253, 89]]]
};
var points = letters["a"];
context.strokeStyle = "#000";
context.lineWidth = 24;
for (var i = 0; i < points.length; i++) {
lineNSmooth(context, points[i]);
}
context.strokeStyle = "#f00";
context.lineWidth = 2;
for (var i = 0; i < points.length; i++) {
lineN(context, points[i]);
}
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment