简体   繁体   English

如何调整画布大小

[英]How to make a canvas resize

i draw a canvas with a image and i want when browser resize, this image can responsive with browser. 我用图像绘制画布,我想在浏览器调整大小时,该图像可以响应浏览器。 This is my code 这是我的代码

 function draw_canvas() { var img = new Image(); var canvas = $('canvas')[0]; img.crossOrigin = 'anonymous'; img.onload = function(){ var ctx = canvas.getContext('2d'); ctx.drawImage(this, 0, 0, $('#canvas_panel').width(), $('#canvas_panel').height()); }; img.src = 'http://dicprj.moe/media/mathimages/en/arithmetic_kinder_counting_money_01_10.png'; } $(document).ready(function() { draw_canvas(); }); $(window).resize(function() { $('#canvas_panel > canvas').each(function(i,v) { if($(this).height() != $('#canvas_panel').height() || $(this).width() != $('#canvas_panel').width()) { $(this).attr({ 'height' : $('#canvas_panel').height() + 'px', 'width' : $('#canvas_panel').width() + 'px' }); } }); }); 
 <html> <head> <meta charset="utf-8"> <title>DRAWING</title> <meta charset="utf-8"> </head> <body> <div id="canvas_panel" style="height: 500px; widht: 800px" > <canvas></canvas> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> </body> </html> 

  • The problem : when browser resize i can't can see canvas, canvas changed px but it empty. 问题:当浏览器调整大小时,我看不到画布,画布更改为px,但它为空。 can you help me ? 你能帮助我吗 ?
  • im trying with code : 我正在尝试使用代码:

 if($(this).height() != $('#canvas_panel').height() || $(this).width() != $('#canvas_panel').width()) { $(this).attr({ 'height' : $('#canvas_panel').height(), 'width' : $('#canvas_panel').width() }); //draw_canvas(); var ctx = $(this)[0].getContext('2d'); ctx.drawImage($(this)[0].toDataURL(), 0, 0, $('#canvas_panel').width(), $('#canvas_panel').height()); var img = new Image(); var canvas = $(this)[0]; img.crossOrigin = 'anonymous'; img.onload = function(){ var canvas = cloneCanvas(); var ctx = .getContext('2d'); ctx.drawImage(this, 0, 0, $('#canvas_panel').width(), $('#canvas_panel').height()); }; img.src = $(this)[0].toDataURL(); } 

Thank 谢谢

Whenever you resize a canvas, you need to redraw it. 每当您调整画布大小时,都需要重新绘制它。 So, call the draw_canvas(); 因此,调用draw_canvas(); function after resizing. 调整大小后起作用。 The new code would become 新的代码将成为

$(window).resize(function() {
  $('#canvas_panel > canvas').each(function(i,v) {
    if($(this).height() != $('#canvas_panel').height() || 
      $(this).width() !=   $('#canvas_panel').width()) 
    {
      $(this).attr({
        'height' : $('#canvas_panel').height() + 'px',
        'width'  : $('#canvas_panel').width() + 'px'    
      });
      draw_canvas();
    }
  });
});

The css can resolve this problem, just set width/height css to canvas : CSS可以解决此问题,只需将width / height CSS设置为canvas即可:

 canvas { width: 100%; height: 100%; } 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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