简体   繁体   中英

Canvas resizing using jQuery

I'd like to resize an canvas listening to the onresize & onload -events.

The code that is working quit fine is a mixture between js & jQuery as you can see here:

How can I translate the full code into jQuery?

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

What I've tried so far is not working fine:

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

What would be a working approach instead?

.offset() has .top and .left , not .width and .height

You're actually looking for .outerWidth which gives the same result as the native .offsetWidth

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

or more jQerily

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

Be aware, that if you are doing this on a page with more than one canvas, you wll give the same size (from the first canvas element matched) to all the canvas elements on the page, as opposed to first-to-first only with the [0]

If you want each one to be independent, you should do this instead:

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

This should also improve performance, as the query "canvas" is only matched once per invocation.

Important: In any case, you should wrap the "resize" handler in a debounce function, otherwise the browser will be doing a lot of work for nothing, causing lag. I recommend the one from underscore like this:

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

PS: Why are you using jQuery?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM