Yes, you have a cleaner approach : since you will always get a context by using getContext('2d')
on a canvas, you can inject getContext
, so that it does any setup of your like before returning the context.
The following piece of code successfully sets the smoothing to false for all your contexts :
(it should, quite obviously, be run before any call to getContext).
// save old getContext
var oldgetContext = HTMLCanvasElement.prototype.getContext ;
// get a context, set it to smoothed if it was a 2d context, and return it.
function getSmoothContext(contextType) {
var resCtx = oldgetContext.apply(this, arguments);
if (contextType == '2d') {
setToFalse(resCtx, 'imageSmoothingEnabled');
setToFalse(resCtx, 'mozImageSmoothingEnabled');
setToFalse(resCtx, 'oImageSmoothingEnabled');
setToFalse(resCtx, 'webkitImageSmoothingEnabled');
}
return resCtx ;
}
function setToFalse(obj, prop) { if ( obj[prop] !== undefined ) obj[prop] = false; }
// inject new smoothed getContext
HTMLCanvasElement.prototype.getContext = getSmoothContext ;
Rq that you can do anything in 'your' getContext. I use it to copy canvas's width, height on the context to have them at hand with no DOM access, among other things.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…