canvas { background:whitesmoke}
div { width:100px; height:100px; margin-top:100px; border:1px solid black }
JavaScript
// Bind canvas to listeners
var canvas = document.getElementById('canvas');
canvas.addEventListener('mousedown', mouseDown, false);
canvas.addEventListener('mousemove', mouseMove, false);
canvas.addEventListener('mouseup', mouseUp, false);
var ctx = canvas.getContext('2d');
ctx.lineWidth = 5;
ctx.lineJoin = 'round';
ctx.lineCap = 'round';
var started = false;
var lastx = 0;
var lasty = 0;
// create an in-memory canvas
var memCanvas = document.createElement('canvas');
memCanvas.width = 300;
memCanvas.height = 300;
var memCtx = memCanvas.getContext('2d');
var points = [];
function mouseDown(e) {
var m = getMouse(e, canvas);
points.push({
x: m.x,
y: m.y
});
started = true;
};
function mouseMove(e) {
if (started) {
ctx.clearRect(0, 0, 300, 300);
// put back the saved content
ctx.drawImage(memCanvas, 0, 0);
var m = getMouse(e, canvas);
points.push({
x: m.x,
y: m.y
});
drawPoints(ctx, points);
}
};
function mouseUp(e) {
if (started) {
started = false;
// When the pen is done, save the resulting context
// to the in-memory canvas
memCtx.clearRect(0, 0, 300, 300);
memCtx.drawImage(canvas, 0, 0);
points = [];
}
};
// clear both canvases!
function clear() {
context.clearRect(0, 0, 300, 300);
memCtx.clearRect(0, 0, 300, 300);
};
function drawPoints(ctx, points) {
// draw a basic circle instead
if (points.length < 6) {
var b = points[0];
ctx.beginPath(), ctx.arc(b.x, b.y, ctx.lineWidth / 2, 0, Math.PI * 2, !0), ctx.closePath(), ctx.fill();
return
}
ctx.beginPath(), ctx.moveTo(points[0].x, points[0].y);
// draw a bunch of quadratics, using the average of two points as the control point
for (i = 1; i < points.length - 2; i++) {
var c = (points[i].x + points[i + 1].x) / 2,
...
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.