问题
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