我正在尝试使用100%Canvas来适应视口或父div。 这就是我所拥有的:
<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);
});
但是画布的大小是html中定义的600px。我的控制台日志显示了这个:
width of canvas is: 600
1440
所以我知道我的javascript最后运行,因此我希望画布大小为1440px而不是600px。
此外,我尝试将.ready更改为.load或window.load,但它没有帮助。
答案 0 :(得分:0)
在绑定fabric
之前显式更改画布的属性值正常。
演示: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);