Skip to content

Instantly share code, notes, and snippets.

@ernstki
Forked from anonymous/jsbin.qoxalize.html
Last active August 29, 2015 14:04
Show Gist options
  • Save ernstki/5db38ae05bb5b73434ef to your computer and use it in GitHub Desktop.
Save ernstki/5db38ae05bb5b73434ef to your computer and use it in GitHub Desktop.
JavaScript source to create quadratic curves between successive points drawn with the mouse
<!DOCTYPE html>
<html>
<head>
<script src="//code.jquery.com/jquery-2.1.0.min.js"></script>
<script class="jsbin" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<meta charset=utf-8 />
<title>quadraticCurveTo given three points</title>
<style>
body { background:#000; margin:0px; padding:0px; overflow:hidden; }
</style>
</head>
<body>
Used <a href="http://stackoverflow.com/a/3789278">this answer</a> from
<a href="http://stackoverflow.com/questions/3783419/smooth-user-drawn-lines-in-canvas">Smooth user drawn lines in canvas</a>
on SO as a starting point.
<canvas id="canvas"></canvas>
</body>
</html>
$(function() {
var canvas = $('canvas');
var ctx = canvas[0].getContext('2d');
var width = window.innerWidth;
var height = window.innerHeight;
canvas.height = height;
canvas.width = width;
canvas.css('border', '1px solid white;');
var pts = [];
function drawPoint(evt) {
var pt = {
x: parseInt(evt.pageX - canvas.offset().left),
y: parseInt(evt.pageY - canvas.offset().top)
};
circle(pt.x, pt.y, 2);
pts.push(pt);
if (pts.length == 3) {
ctx.beginPath();
ctx.moveTo(pts[0].x, pts[0].y);
ctx.quadraticCurveTo(pts[1].x, pts[1].y, pts[2].x, pts[2].y);
ctx.strokeStyle = '#ccc';
ctx.stroke();
pts.shift(); pts.shift();
}
} // drawPoint(evt)
function circle(cx, cy, r) {
ctx.beginPath();
ctx.arc(cx, cy, r, 0, 2*Math.PI, false);
ctx.strokeStyle = '#ffffff';
ctx.fillStyle = 'white';
ctx.fill();
ctx.stroke();
}
function rgb() {
color = 'rgb(';
for(var i = 0; i< 3; i++) {
color += Math.floor(Math.random() * 255)+',';
}
return color.replace(/\,$/,')');
}
$('canvas').mousedown(drawPoint);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment