缩放和平移画布
缩放画布
以原点为基准缩放画布
// 监听鼠标滚轮事件 canvas.on('mouse:wheel', opt => { let delta = opt.e.deltaY // 滚轮向上滚一下是 -100,向下滚一下是 100 let zoom = canvas.getZoom() // 获取画布当前缩放值 // 控制缩放范围在 0.01~20 的区间内 zoom *= 0.999 ** delta if (zoom > 20) zoom = 20 if (zoom < 0.01) zoom = 0.01 // 设置画布缩放比例 canvas.setZoom(zoom) })
以鼠标指针为基准缩放画布
// 监听鼠标滚轮事件 canvas.on('mouse:wheel', opt => { let delta = opt.e.deltaY // 滚轮向上滚一下是 -100,向下滚一下是 100 let zoom = canvas.getZoom() // 获取画布当前缩放值 // 控制缩放范围在 0.01~20 的区间内 zoom *= 0.999 ** delta if (zoom > 20) zoom = 20 if (zoom < 0.01) zoom = 0.01 // 设置画布缩放比例 // 关键点!!! // 参数1:将画布的所放点设置成鼠标当前位置 // 参数2:传入缩放值 canvas.zoomToPoint( { x: opt.e.offsetX, // 鼠标x轴坐标 y: opt.e.offsetY // 鼠标y轴坐标 }, zoom // 最后要缩放的值 ) })
平移画布
canvas.on('mouse:down', opt => { // 鼠标按下时触发 let evt = opt.e if (evt.altKey === true) { // 是否按住alt canvas.isDragging = true // isDragging 是自定义的,开启移动状态 canvas.lastPosX = evt.clientX // lastPosX 是自定义的 canvas.lastPosY = evt.clientY // lastPosY 是自定义的 } }) canvas.on('mouse:move', opt => { // 鼠标移动时触发 if (canvas.isDragging) { let evt = opt.e let vpt = canvas.viewportTransform // 聚焦视图的转换 vpt[4] += evt.clientX - canvas.lastPosX vpt[5] += evt.clientY - canvas.lastPosY canvas.requestRenderAll() // 重新渲染 canvas.lastPosX = evt.clientX canvas.lastPosY = evt.clientY } }) canvas.on('mouse:up', opt => { // 鼠标松开时触发 canvas.setViewportTransform(canvas.viewportTransform) // 设置此画布实例的视口转换 canvas.isDragging = false // 关闭移动状态 })
选中状态
const rect = new fabric.Rect({ top: 100, left: 100, width: 200, height: 100, fill: 'red' }) // 元素禁止选中 rect.selectable = false // 选择三角形空白位置的时候无法选中 rect.perPixelTargetFind = true // 只选择完全包含在拖动选择矩形中的形状 canvas.selectionFullyContained = true
画布框选样式
canvas.selection = true // 画布是否可选中。默认true;false 不可选中 canvas.selectionColor = 'rgba(106, 101, 216, 0.3)' // 画布鼠标框选时的背景色 canvas.selectionBorderColor = "#1d2786" // 画布鼠标框选时的边框颜色 canvas.selectionLineWidth = 6 // 画布鼠标框选时的边框厚度 canvas.selectionDashArray = [30, 4, 10] // 画布鼠标框选时边框虚线规则 canvas.selectionFullyContained = true // 只选择完全包含在拖动选择矩形中的形状
自定义边和控制角样式
// 圆形 const circle = new fabric.Circle({ radius: 30, fill: '#f55', top: 70, left: 70 }) circle.set({ borderColor: 'red', // 边框颜色 cornerColor: 'green', // 控制角颜色 cornerSize: 10, // 控制角大小 transparentCorners: false, // 控制角填充色不透明 // transparentCorners: true // 控制角填充色透明 selectionBackgroundColor: 'orange' // 选中后,背景色变橙色 }) circle.hasBorders = false // 取消边框 circle.hasControls = false // 禁止控制角 canvas.hoverCursor = 'wait' // 设置等待指针 canvas.add(circle) canvas.setActiveObject(circle) // 选中圆
元素移动时的样式
function animate(e, dir) { if (e.target) { fabric.util.animate({ startValue: e.target.get('angle'), endValue: e.target.get('angle') + (dir ? 10 : -10), duration: 100 }) fabric.util.animate({ startValue: e.target.get('scaleX'), endValue: e.target.get('scaleX') + (dir ? 0.2 : -0.2), duration: 100, onChange: function(value) { e.target.scale(value) canvas.renderAll() }, onComplete: function() { e.target.setCoords() } }) } } canvas.on('mouse:down', function(e) { animate(e, 1) }) canvas.on('mouse:up', function(e) { animate(e, 0) })
序列化
// 输出json JSON.stringify(canvas) canvas.toJSON() canvas.toObject() // 输出png(base64版)可能会打断 canvas 的渲染 canvas.toDataURL('png') canvas.requestRenderAll() // 输出 SVG canvas.toSVG()
反序列化
const str = '{"version":"4.6.0","objects":[{"type":"rect","version":"4.6.0","originX":"left","originY":"top","left":50,"top":50,"width":20,"height":20,"fill":"green","stroke":null,"strokeWidth":1,"strokeDashArray":null,"strokeLineCap":"butt","strokeDashOffset":0,"strokeLineJoin":"miter","strokeUniform":false,"strokeMiterLimit":4,"scaleX":1,"scaleY":1,"angle":0,"flipX":false,"flipY":false,"opacity":1,"shadow":null,"visible":true,"backgroundColor":"","fillRule":"nonzero","paintFirst":"fill","globalCompositeOperation":"source-over","skewX":0,"skewY":0,"rx":0,"ry":0},{"type":"circle","version":"4.6.0","originX":"left","originY":"top","left":80,"top":80,"width":80,"height":80,"fill":"red","stroke":null,"strokeWidth":1,"strokeDashArray":null,"strokeLineCap":"butt","strokeDashOffset":0,"strokeLineJoin":"miter","strokeUniform":false,"strokeMiterLimit":4,"scaleX":1,"scaleY":1,"angle":0,"flipX":false,"flipY":false,"opacity":1,"shadow":null,"visible":true,"backgroundColor":"","fillRule":"nonzero","paintFirst":"fill","globalCompositeOperation":"source-over","skewX":0,"skewY":0,"radius":40,"startAngle":0,"endAngle":6.283185307179586}],"background":"#ddd"}' // 初始化画布 const canvas = new fabric.Canvas('canvas') // 反序列化 canvas.loadFromJSON(str)
fabric类的继承体系
StaticCanvas Canvas Object Triangle Circle Ellipse Image Line Path Rect Polyline Polygon Group ActiveSelection Text IText Textbox BaseBrush PatternBrush PencilBrush SprayBrush Point CircleBrush Gradient Color Intersection Pattern Shadow BaseFilter Blur Brightness ColorMatrix Contrast Convolute BlendColor BlendImage Gamma Grayscale HueRotation Invert Noise Pixelate RemoveColor Resize Saturation Vibrance
参考文章