我想通过监听 onresize & onload
事件来调整 Canvas 的大小。
运行良好的代码是 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
什么是可行的方法?
最佳答案
.offset()
有 .top
和 .left
,没有 .width
和 .高度
您实际上是在寻找 .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)
})
请注意,如果您在具有多个 Canvas 的页面上执行此操作,您将为页面上的所有 Canvas 元素提供相同的大小(从第一个匹配的 Canvas 元素开始),而不是先到先得-首先仅使用 [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?
关于javascript - 使用 jQuery 调整 Canvas 大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52135782/