问题描述
所以我是jQuery的新手,我一直在研究通过使用resize()事件处理函数调整元素大小的API,获取特定元素的parent()div并通过使用attr )方法。
我已经尝试了下面的代码,当我输出到控制台时,一切似乎都如预期的那样(宽度根据canvas elemt的父元素而改变)。但是,当我调整窗口大小时,画布消失:
$(window).resize(function(){
var width = $('#line_chart_price')。parent()。width();
$('#line_chart_price')。attr('width',width);
});
我在这里做错了什么?
非常感谢
您需要在调整大小时重绘画布上下文。
JS
var can = document.querySelector( '画布');
canCtx = can.getContext('2d');
canCtx.fillRect(50,25,50,100); //一个基本的矩形。如果你愿意的话,你可以将它设置为父母的宽度。
$ b $(window).resize(function(){
width = $(can).parent()。width();
can.width = width;
canCtx.fillRect(50,25,width,100);
});
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
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);
});
这篇关于如何根据div父宽度使画布响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!