Created
November 23, 2013 06:24
-
-
Save mappu/7611483 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html> | |
<head> | |
<title>bezier demo</title> | |
<script type="text/javascript"> | |
// globals | |
var c = null; | |
var ctx = null; | |
var lastx = 0, | |
lasty = 0, | |
lastcx = 0, | |
lastcy = 0, | |
pointnum = 0; | |
var BEZIER_NUM_POINTS = 10; | |
var draw_mode = 0; | |
var DRAW_MODE_LINEAR = 0; | |
var DRAW_MODE_BEZIER2 = 1; | |
function renderline(x0, y0, x1, y1) { | |
ctx.moveTo(x0, y0); | |
ctx.lineTo(x1, y1); | |
} | |
function rendercurve(x0, y0, x1, y1, x2, y2) { | |
var bezier2 = function(a, b, c, t) { | |
return ( (1-t)*( (1-t)*a + t*b ) + t*( (1-t)*b + c*t ) ); // wikipedia | |
}; | |
ctx.moveTo(x0, y0); | |
for (var i = 0; i < 1; i += (1/BEZIER_NUM_POINTS)) { | |
var xpos = bezier2(x0, x1, x2, i); | |
var ypos = bezier2(y0, y1, y2, i); | |
ctx.lineTo(xpos, ypos); | |
ctx.moveTo(xpos, ypos); | |
} | |
} | |
function rendercurve__fast(x0, y0, x1, y1, x2, y2) { | |
ctx.moveTo(x0, y0); | |
ctx.quadraticCurveTo(x1, y1, x2, y2); | |
} | |
// | |
function connect(x, y) { | |
ctx.beginPath(); | |
ctx.lineWidth="1"; | |
ctx.strokeStyle="black"; | |
switch (draw_mode) { | |
case DRAW_MODE_LINEAR: { | |
renderline(lastx, lasty, x, y); | |
lastcx = lastx; | |
lastcy = lasty; | |
} break; | |
case DRAW_MODE_BEZIER2: { | |
// get current direction vector | |
var dx = lastx - lastcx, dy = lasty - lastcy; | |
// dampen | |
dx = dx / 2; | |
dy = dy / 2; | |
var cx = lastx + dx, cy = lasty + dy; | |
//rendercurve(lastx, lasty, cx, cy, x, y); | |
rendercurve__fast(lastx, lasty, cx, cy, x, y); | |
lastcx = cx; | |
lastcy = cy; | |
} break; | |
} | |
ctx.stroke(); | |
lastx = x; | |
lasty = y; | |
pointnum++; | |
} | |
function addpoint(e) { | |
var x = e.offsetX, y = e.offsetY; | |
if (pointnum === 0) { | |
// do nothing | |
} else if (pointnum === 1) { | |
draw_mode = DRAW_MODE_LINEAR; | |
connect(x, y); | |
} else { | |
draw_mode = DRAW_MODE_BEZIER2; | |
connect(x, y); | |
} | |
lastx = x; | |
lasty = y; | |
pointnum++; | |
} | |
// | |
function init() { | |
c = document.getElementById('c'); | |
c.width = 500; | |
c.height = 500; | |
ctx = c.getContext('2d'); | |
c.addEventListener('click', addpoint); | |
} | |
window.addEventListener('load', init); | |
</script> | |
<style type="text/css"> | |
#c { | |
width:500px; | |
height:500px; | |
border:1px solid black; | |
} | |
</style> | |
</head> | |
<body> | |
<canvas id="c"></canvas> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment