Skip to content

Instantly share code, notes, and snippets.

@esson
Last active December 23, 2015 03:59
Show Gist options
  • Save esson/6577407 to your computer and use it in GitHub Desktop.
Save esson/6577407 to your computer and use it in GitHub Desktop.
Moves all x and y coordinates so that anti-aliasing will be kept to a minimum. This solves the problem where single pixel lines becomes 'blurry' by making sure that they are drawn at right position.
// Canvas Rendering Fix
//
if (window.CanvasRenderingContext2D) {
var arc = CanvasRenderingContext2D.prototype.arc,
arcTo = CanvasRenderingContext2D.prototype.arcTo,
bezierCurveTo = CanvasRenderingContext2D.prototype.bezierCurveTo,
clearRect = CanvasRenderingContext2D.prototype.clearRect,
fillRect = CanvasRenderingContext2D.prototype.fillRect,
lineTo = CanvasRenderingContext2D.prototype.lineTo,
moveTo = CanvasRenderingContext2D.prototype.moveTo,
rect = CanvasRenderingContext2D.prototype.rect,
strokeRect = CanvasRenderingContext2D.prototype.strokeRect;
function f(value) {
return Math.round(value) + 0.5;
}
CanvasRenderingContext2D.prototype.arc = function (x, y, radius, startAngle, endAngle, anticlockwise) {
return arc.call(this, f(x), f(y), radius, startAngle, endAngle, anticlockwise);
};
CanvasRenderingContext2D.prototype.arcTo = function (x1, y1, x2, y2, radius) {
return arcTo.call(this, f(x1), f(y1), f(x2), f(y2), radius);
};
CanvasRenderingContext2D.prototype.bezierCurveTo = function (cp1x, cp1y, cp2x, cp2y, x, y) {
return bezierCurveTo.call(this, f(cp1x), f(cp1y), f(cp2x), f(cp2y), f(x), f(y));
};
CanvasRenderingContext2D.prototype.clearRect = function (x, y, w, h) {
return clearRect.call(this, f(x), f(y), w, h);
};
CanvasRenderingContext2D.prototype.fillRect = function (x, y, w, h) {
return fillRect.call(this, f(x), f(y), w, h);
};
CanvasRenderingContext2D.prototype.lineTo = function (x, y) {
return lineTo.call(this, f(x), f(y));
};
CanvasRenderingContext2D.prototype.moveTo = function (x, y) {
return moveTo.call(this, f(x), f(y));
};
CanvasRenderingContext2D.prototype.rect = function (x, y, w, h) {
return rect.call(this, f(x), f(y), w, h);
};
CanvasRenderingContext2D.prototype.strokeRect = function (x, y, w, h) {
return strokeRect.call(this, f(x), f(y), w, h);
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment