【问题标题】:How to make canvas responsive according to the div parent width如何根据 div 父宽度使画布响应
【发布时间】:2019-10-04 20:04:53
【问题描述】:

所以我是 jQuery 的新手,我一直在查看 API,我们可以通过使用 resize() 事件处理程序来调整元素的大小,获取特定元素的 parent() div 并使用 attr( ) 方法。

我尝试了以下代码,当我输出到控制台时,一切似乎都符合预期(宽度根据 canvas elemt 的父级而变化)。但是当我调整窗口大小时,画布消失了:

$(window).resize(function() {
  var width = $('#line_chart_price').parent().width();
  $('#line_chart_price').attr('width', width);
});

我在这里做错了什么?

非常感谢

【问题讨论】:

  • 也许尝试改变 $('#line_chart_price').attr('width', width);到 $('#line_chart_price').attr('width', $width);或 $('#line_chart_price').attr('width', +width);

标签: jquery html responsive-design


【解决方案1】:

您需要在调整大小时重新绘制画布上下文。

JS

var can = document.querySelector('canvas');
canCtx = can.getContext('2d');
canCtx.fillRect(50, 25, 50, 100); // a basic rect. you could set this to the width of the parent off the bat if you want.

$(window).resize(function () {
  width = $(can).parent().width();
  can.width = width;
  canCtx.fillRect(50, 25, width, 100);
});

jsbin

【讨论】:

    【解决方案2】:

    我创建了一个示例来反映画布的响应性,根据父元素的尺寸。

    function outputsize() {
      console.log(textbox.clientWidth)
     myCanvas.width = textbox.clientWidth;
    }
    outputsize()
    
    new ResizeObserver(outputsize).observe(textbox);
    

    对于 HTML 结构,请参阅附件箱。 JSBIN

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-10-22
      • 2016-01-15
      • 2021-05-21
      • 2011-08-06
      • 2023-03-12
      • 1970-01-01
      • 2017-11-19
      相关资源
      最近更新 更多