更改HTML画布的分辨率

时间:2016-06-17 02:43:32

标签: javascript html css canvas

我正在尝试更改HTML画布的分辨率。 (不是宽度和高度)。画布应保持与屏幕相同的宽度和高度,但渲染分辨率应该是可更改的。我可以通过在浏览器中使用缩放功能来复制我想要的内容,但我想知道是否有一种编程方式来执行此操作。以下是我的尝试:

function resize() {
    screenWidth = mathRound(window.innerWidth);
    screenHeight = mathRound(window.innerHeight);
    calculateUIScale();
    var scaleFillNative = Math.max(screenWidth / maxScreenWidth, screenHeight / maxScreenHeight);
    c.width = screenWidth;
    c.height = screenHeight;
    graph.setTransform(scaleFillNative, 0, 0, scaleFillNative, ((screenWidth - (maxScreenWidth * scaleFillNative)) / 2), ((screenHeight - (maxScreenHeight * scaleFillNative)) / 2));
    graph.imageSmoothingEnabled = false;
    graph.webkitImageSmoothingEnabled = false;
    graph.mozImageSmoothingEnabled = false;
}

这使画布适合屏幕。我想知道你是否可以以某种方式缩放画布元素以模拟不同的分辨率。

我试过这样做:

c.width = 40;
c.style.width = 400;

但画布现在真的很小。

2 个答案:

答案 0 :(得分:4)

提供了所有CSS尺寸requires an unit specified if a non-zero value

  

长度值的格式(在此表示   规范)是(有或没有小数点)   紧接着是单元标识符(例如,px,em等)。后   零长度,单位标识符是可选的。

所以只需在数字后添加一个单位,这里以字符串形式:

template<typename TElement>
class grades {
private:
   vector<TElement> v;
public:
    grades operator+(const TElement& a) const {
        grades ret(*this);
        ret.v.push_back(a);
        return ret;
    }
    friend grades operator+(const TElement& a,const grades& g) {
        return g+a;
    }
};
int main() {
   grades<int> myg;
   myg = 10 + myg; // this operation i want
   myg = myg + 9; //this work
   return 0;

}

或动态:

c.width = 40;
c.style.width = "400px";  // add pixel unit

c.style.width = (c.width * 10) + "px";
var ctx = c.getContext("2d");

c.width = 40;
c.height = 12;
c.style.width = (c.width * 8) + "px";
c.style.height = (c.height * 8) + "px";

ctx.lineWidth = 2;
ctx.strokeRect(0,0,c.width,c.height);

答案 1 :(得分:2)

如果要缩放页面的整个内容,请尝试将其添加到html元素的CSS中,或者只是整个主体:

* {
transform: scale(1.5);
}

jQuery也可以工作:

$(this).css({
    '-webkit-transform': 'scale(1.5)',
    '-o-transform': 'scale(1.5)',
    '-moz-transform': 'scale(1.5)',
    '-ms-transform': 'scale(1.5)',
    'transform': 'scale(1.5)'
});

我希望这会有所帮助。

http://codepen.io/jiemushi/pen/Vjjgaj