Skip to content Skip to sidebar Skip to footer

How To Make Canvas Responsive According To The Div Parent Width

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

Solution 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

Solution 2:

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

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

newResizeObserver(outputsize).observe(textbox);

For HTML Structure please refer attached bin. JSBIN

Post a Comment for "How To Make Canvas Responsive According To The Div Parent Width"