簡體   English   中英

默認情況下在多個畫布上禁用imageSmoothingEnabled

[英]disabling imageSmoothingEnabled by default on multiple canvases

我正在創建一個基於瀏覽器的游戲,該游戲使用分層的畫布和Sprite圖像,並且出於視覺和性能方面的原因,我想默認禁用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...

有沒有更優雅的方法? 在實際創建每個畫布上下文之前,是否可以將上下文的API更改為默認值false?

是的,您有一個更簡潔的方法:由於您始終可以通過在畫布上使用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 ;

可以在“您的” getContext中執行任何操作。 我使用它在上下文中復制畫布的寬度和高度,以使它們在沒有DOM訪問的情況下可用。

您可以將它們放入類似的方法中:

function imageSmoothingEnabled(ctx, state) {
    ctx.mozImageSmoothingEnabled = state;
    ctx.oImageSmoothingEnabled = state;
    ctx.webkitImageSmoothingEnabled = state;
    ctx.imageSmoothingEnabled = state;
}

然后調用每個上下文:

imageSmoothingEnabled(context1, false);
imageSmoothingEnabled(context2, false);
imageSmoothingEnabled(context3, false);

由於這些是屬性,您不能簡單地更改其默認值。 這里的方法非常干凈-通過首先檢查屬性的存在可以使其更干凈:

if (typeof ctx.webkitImageSmoothingEnabled !== 'undefined')
    ctx.webkitImageSmoothingEnabled = state;

等等

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM