默认情况下,在多个画布上禁用imageSmoothingEnabled

Dan*_*neh 1 javascript canvas html5-canvas

我正在创建一个使用分层画布和精灵图像的基于浏览器的游戏,出于视觉和性能原因,我想默认禁用imageSmoothingEnabled.我的理解是imageSmoothingEnabled并非在所有浏览器中都可用,但有供应商前缀版本.我试图在我的所有画布(尽可能多的浏览器中)中找到一种优雅的方法来禁用此属性.到目前为止,这是我的方法:

context1.imageSmoothingEnabled = false;
context1.mozImageSmoothingEnabled = false;
context1.oImageSmoothingEnabled = false;
context1.webkitImageSmoothingEnabled = false;

context2.imageSmoothingEnabled = false;
context2.mozImageSmoothingEnabled = false;
context2.oImageSmoothingEnabled = false;
context2.webkitImageSmoothingEnabled = false;

context3.imageSmoothingEnabled = false;
context3.mozImageSmoothingEnabled = false;
context3.oImageSmoothingEnabled = false;
context3.webkitImageSmoothingEnabled = false;
//etc...
Run Code Online (Sandbox Code Playgroud)

有更优雅的方法吗?在实际创建每个画布上下文之前,是否可以将上下文的API更改为默认值为false?

Gam*_*ist 6

是的,你有一个更清洁的方法:因为你总是通过getContext('2d')在画布上使用来获得上下文,你可以注入getContext,以便它在返回上下文之前进行任何类似的设置.

以下代码成功地将所有上下文的平滑设置为false:

(很明显,它应该在任何对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 ;
Run Code Online (Sandbox Code Playgroud)

Rq你可以在'你的'getContext中做任何事情.我使用它来复制画布在上下文中的宽度,高度,以便在没有DOM访问的情况下使用它们等等.