使用jQuery调整画布大小

时间:2018-09-02 09:49:12

标签: javascript jquery css

我想调整画布的大小,以监听onresize & onload事件。

工作正常的代码是js和jQuery的混合体,如您所见:

如何将完整代码翻译成jQuery?

window.onload = window.onresize = function() {
  $("canvas")[0].width = $("canvas")[0].offsetWidth;
  $("canvas")[0].height = $("canvas")[0].offsetHeight;
} // this code is working pretty good

到目前为止我尝试过的工作不正常:

window.onload = window.onresize = function() {
  $("canvas").width($("canvas").offset().width);
  $("canvas").height($("canvas").offset().height);
} // this code is not working as expected

什么是可行的方法呢?

1 个答案:

答案 0 :(得分:1)

.offset()具有.top.left,而不是.width.height

您实际上正在寻找的.outerWidth与原始.offsetWidth的结果相同

window.onload = window.onresize = function() {
  $("canvas").width($("canvas").outerWidth());
  $("canvas").height($("canvas").outerHeight());
}

或更多jQerily

function resizeCanvas() {
  $("canvas").width($("canvas").outerWidth());
  $("canvas").height($("canvas").outerHeight());
}
$(function(){
  resizeCanvas()
  $(window).on("resize", resizeCanvas)
})

请注意,如果您是在一个画布上包含多个画布的页面上执行此操作,则将为页面上的所有画布元素赋予相同的大小(从匹配的第一个画布元素开始),而不是先到-仅使用[0]

如果您希望每个人都独立,则应该这样做:

function resizeCanvas() {
  $("canvas").each(function(){
    this.width(this.outerWidth())
    this.height(this.outerHeight())
  }
}
$(function(){
  resizeCanvas()
  $(window).on("resize", resizeCanvas)
})

这还将提高性能,因为查询"canvas"每次调用仅匹配一次。

重要:在任何情况下,您都应该将"resize"处理函数包装在一个反跳函数中,否则浏览器将无所事事,从而导致滞后。我建议像这样the one from underscore

$(function(){
  resizeCanvas()
  $(window).on("resize", _.debounce(resizeCanvas, 400))
})

PS:为什么要使用jQuery?

相关问题