前提代码准备,vue2 框架,下载好 fabric.js ( npm i fabric --save )
<div class="box">
<canvas id="c" style="border: 1px solid pink;"></canvas>
</div>
1、初始化的时候画布宽高设置成外层盒子宽高
var canvas = new fabric.Canvas('canvasBox', {
selection: false,
// jQuery
width: $(".box").width(),
height: $(".box").height(),
// 原生写法
// width: document.getElementsByClassName("box")[0].getBoundingClientRect().width,
// height: document.getElementsByClassName("box")[0].getBoundingClientRect().height,
});
2、页面大小发生变化时候动态改变
mounted() {
window.addEventListener('resize', () => {
this.resizeCanvas()
}, false);
},
methods(){
resizeCanvas() {
if (this.canvas) {
const box = document.querySelector('.box')
let width = box.getBoundingClientRect().width
let height = box.getBoundingClientRect().height
this.canvas.setHeight(height);
this.canvas.setWidth(width);
this.canvas.renderAll();
}
}
}
-
该方法在外层盒子大小发生变化的时候,画布也可以动态的改变大小,但画布中元素的相对位置可能显示不全。如果想等比例缩放,我想到的思路是:
画布缩放比例 = 现在 box 宽高 / 原 box 宽高
参考来源
https://www.codenong.com/15215494/