【问题标题】:disabling imageSmoothingEnabled by default on multiple canvases在多个画布上默认禁用 imageSmoothingEnabled
【发布时间】:2014-02-25 23:24:16
【问题描述】:

我正在创建一个使用分层画布和精灵图像的基于浏览器的游戏,出于视觉和性能原因,我想默认禁用 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?

【问题讨论】:

    标签: javascript canvas html5-canvas


    【解决方案1】:

    是的,您有一个更简洁的方法:因为您将始终通过在画布上使用 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 ;
    

    Rq 你可以在“你的”getContext 中做任何事情。我使用它在上下文中复制画布的宽度、高度,以便在没有 DOM 访问的情况下将它们放在手边。

    【讨论】:

    • 自定义getContext的巧妙方法,我一定会以新的方式使用此方法。谢谢。
    【解决方案2】:

    您可以将它们放入如下方法中:

    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;
    

    等等

    【讨论】:

      猜你喜欢
      • 2021-03-12
      • 2011-12-09
      • 2021-09-19
      • 2021-10-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-01
      相关资源
      最近更新 更多