How to make canvas responsive according to the div parent width

对着背影说爱祢 提交于 2019-12-11 19:24:17

问题


So I am new to jQuery, I have been looking through the API that we can resize elements by using the resize() event handler, get the parent() div of a particular element and setting the attributes by using the attr() method.

I have tried the following code and when I output to console everything seems to be as expected (width changes according to the parent of the canvas elemt ). But when i resize the window, the canvas disappears:

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

What am I doing wrong here?

Many thanks


回答1:


You need to redraw the canvas context on resize.

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:


I have created an example that reflects, Responsiveness of canvas as per the dimension of the parent element.

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

new ResizeObserver(outputsize).observe(textbox);

For HTML Structure please refer attached bin. JSBIN



来源:https://stackoverflow.com/questions/17925444/how-to-make-canvas-responsive-according-to-the-div-parent-width

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!