简体   繁体   English

画布宽度为视口或父div的100%

[英]Canvas width of 100% of viewport or parent div

I am trying to do 100% Canvas to fit either viewport or parent div. 我试图做100%Canvas适合视口或父div。 Here is what I have: 这是我有的:

 <canvas id="mapDrawingCanvas" width="600px" height="600px" style="position:fixed;"></canvas> <script> console.log("width of canvas is: "+$("#mapDrawingCanvas").width()); </script> 

 $(document).ready(function(){ var viewportWidth = $(window).width(); var viewportHeight = $(window).height(); canvas = new fabric.Canvas('mapDrawingCanvas'); canvas.selection = false; canvas.width = viewportWidth; canvas.height = viewportHeight; console.log(canvas.width); }); 

But the size of canvas is 600px as defined in html. 但是画布的大小是600px,如html中所定义。 My console log shows this: 我的控制台日志显示如下:

 width of canvas is: 600 1440 

So I know that my javascript runs last, therefore I expect the canvas size to be 1440px not 600px. 所以我知道我的javascript运行最后,所以我希望画布大小为1440px而不是600px。

Also I tried to change .ready to .load or window.load, but it didn't helped. 我也尝试将.ready更改为.load或window.load,但它没有帮助。

Explicitly changing the attribute value for canvas before binding fabric works fine. 在绑定fabric之前显式更改画布的属性值工作正常。 Demo: https://jsfiddle.net/m7y9uo6x/2/ 演示: https//jsfiddle.net/m7y9uo6x/2/

<canvas id="mapDrawingCanvas" width="600px" height="600px" style="position:fixed;"></canvas>
<script>
  console.log("width of canvas is: " + $("#mapDrawingCanvas").width());

</script>


 var viewportWidth = $(window).width();
 var viewportHeight = $(window).height();
 debugger;
 var canvasElem = $("#mapDrawingCanvas");
 canvasElem.attr("width", viewportWidth);
 canvasElem.attr("height", viewportHeight);
 canvas = new fabric.Canvas('mapDrawingCanvas', {
   backgroundColor: 'rgb(100,100,200)'
 });
 canvas.selection = false;
 console.log("new width" + canvas.width);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM