fabric
https://www.jianshu.com/p/1a2efc425c6f
https://juejin.cn/post/7140812541197811726
创建画布
// var fcanvas = new fabric.StaticCanvas('canvas', { // 静态画布
var fcanvas = new fabric.Canvas('canvas', {
// 交互式画布
// backgroundColor: 'blue' // 画布背景色为蓝色
// preserveObjectStacking: true // 禁止选中的图层置于顶级。后添加的图层会盖在先添加的图层上,选中的图层会显示在顶层(方便你操作,失焦后就恢复原来的层级了)
// perPixelTargetFind: true, // 点击真实图像才能选中和拖拽图层,点击padding处不行。
// selectionColor: 'red', // 鼠标点击拖拽 框选图层时,矩形的背景颜色
// selectionBorderColor: 'red', // 鼠标点击拖拽 框选图层时,矩形的边框颜色
// selectionLineWidth: 20 // 鼠标点击拖拽 框选图层时,矩形的边框大小
// selectionDashArray: [10, 5], // 鼠标点击拖拽 框选图层时,矩形的虚线边框(首先要设置边框颜色)。 [10px线 - 5px间隔 - 10px线 ...]
// selection: false, // 禁止 鼠标点击拖拽 框选图层
// isDrawingMode: true, // 自由绘制模式,画布上点击和移动会被解释为铅笔。(需要关闭框选图层)
});
// 设置宽高
fcanvas.setWidth(300);
fcanvas.setHeight(300);
事件监听
function Observer() {
// 监听添加图层
fcanvas.on('object:added', (e) => {
console.log('添加图层');
})
// 监听图层变化(放大/缩小/移动/旋转)
fcanvas.on('object:modified', (e) => {
const {
action, target } = e;
switch (action) {
case 'drag':
console.log('拖拽');
break;
case 'scale':
console.log('缩放')
break;
case 'rotate':
console.log('旋转')
break;
}
// target是操作的图层
// console.log(target);
// console.log(target.toDataURL());
});
// 监听添加图层
fcanvas.on('object:removed', (e) => {
console.log('删除图层');
})
// 监听图层首次获得焦点
// 一个图层获得焦点时,点击另一个图层不会触发,要先失焦再点击图层才能重新触发
// 可鼠标点击框选,同时选中多个图层
fcanvas.on('selection:created', (e) => {
const {
selected, target } = e;
console.log('图层首次获得焦点');
console.log(`图层中包含${
selected.length}个图层`);
});
// 监听图层选中切换
// 首次选中图层不触发 | 选中图层 - 失焦 - 再次选中 不触发
// 选中一个图层 - 选中另一个图层 触发
fcanvas.on('selection:updated', (e) => {
const {
selected, deselected } = e;
console.log({
desc: '上次选中的图层', deselected});
console.log(