var ctx = c.getContext("2d");
var x1 = 0, y1 = 0, r = 90;
var brush = createBrush(r, "#000");
document.querySelector("button").onclick = function() {
ctx.beginPath();
ctx.clearRect(0,0,c.width,c.height);
};
// mouse move handler using rAF.
c.onmousemove = function(e) {
requestAnimationFrame(function() {
var x2 = e.clientX|0, y2=e.clientY|0;
aliasedLine(ctx, x1, y1, x2, y2, r);
x1 = x2;
y1 = y2;
})
};
function aliasedLine(ctx, x1, y1, x2, y2, radius) {
// calc angle
var diffX = x2 - x1,
diffY = y2 - y1,
angle = Math.atan2(diffY, diffX),
// two edge lines offset per angle
lx1 = x1 - radius * Math.sin(angle),
ly1 = y1 + radius * Math.cos(angle),
lx2 = x2 - radius * Math.sin(angle),
ly2 = y2 + radius * Math.cos(angle),
rx1 = x1 + radius * Math.sin(angle),
ry1 = y1 - radius * Math.cos(angle),
rx2 = x2 + radius * Math.sin(angle),
ry2 = y2 - radius * Math.cos(angle);
// main line
ctx.beginPath();
drawLine(ctx, x1, y1, x2, y2, radius);
ctx.stroke();
// aliased edges
ctx.beginPath();
fastLine(ctx, lx1|0, ly1|0, lx2|0, ly2|0);
fastLine(ctx, rx1|0, ry1|0, rx2|0, ry2|0);
ctx.fill();
// caps
ctx.drawImage(brush, x1 - radius, y1 - radius)
ctx.drawImage(brush, x2 - radius, y2 - radius)
}
function createBrush(radius, color) {
var ctx = document.createElement("canvas").getContext("2d");
ctx.canvas.width = ctx.canvas.height = 1 + radius<<1;
ctx.fillStyle = color;
aliasedCircle(ctx, radius, radius, radius);
ctx.fill();
return ctx.canvas
}
function aliasedCircle(ctx, xc, yc, r) { // NOTE: for fill only!
var x = r, y = 0, cd = 0;
// middle line
ctx.rect(xc - x, yc, r<<1, 1);
while (x > y) {
cd -= (--x) - (++y);
if (cd < 0) cd += x++;
ctx.rect(xc - y, yc - x, y<<1, 1); // upper 1/4
ctx.rect(xc - x, yc - y, x<<1, 1); // upper 2/4
ctx.rect(xc - x, yc + y, x<<1, 1); // lower 3/4
ctx.rect(xc - y, yc + x, y<<1, 1); // lower 4/4
}
}
function drawLine(ctx, x1, y1, x2, y2, radius) {
ctx.moveTo(x1, y1);
ctx.lineTo(x2, y2);
ctx.lineWidth = radius<<1;
}
function fastLine(ctx, x1, y1, x2, y2) {
var dlt, mul,
sl = y2 - y1,
ll = x2 - x1,
yl = false,
lls = ll >> 31,
sls = sl >> 31,
i;
if ((sl ^ sls) - sls > (ll ^ lls) - lls) {
sl ^= ll;
ll ^= sl;
sl ^= ll;
yl = true
}
dlt = ll < 0 ? -1 : 1;
mul = (ll === 0) ? sl : sl / ll;
if (yl) {
x1 += 0.5;
for (i = 0; i !== ll; i += dlt)
ctx.rect((x1 + i * mul)|0, y1 + i, 1, 1)
}
else {
y1 += 0.5;
for (i = 0; i !== ll; i += dlt)
ctx.rect(x1 + i, (y1 + i * mul)|0, 1, 1)
}
}
#c {background:#aaa}
<canvas id=c width=1200 height=800></canvas>
<br><button>Clear</button>