Open asturur opened 2 years ago
@ShaMan123
I also wonder how to check target from Event on object as it is unkown type
canvas.on('object:scaled', e=>{ let target = e.target; }
Error Msg: Property 'target' does not exist on type 'unkown'.
That event is deprecated. object:modified instead and check for the action or actionName if you need
@bladerunner2020 please post your good comment in the relative thread #8899 and remove from this one
A list of a few breaking changes not listed yet (I'll update this list as we migrate to fabric v6):
type
property of objects is not overridable anymore because it's only a getternamespace
to module
. This also means that fabric TS types need to be imported now, cannot rely on global fabric.Object
type for instanceHow can we initialize a Canvas
in React and ensure that the fabric.Canvas
object is available in methods outside useEffect
as well? Sorry I struggle with that, and would like some help there as this version provides interaction with group which I very importantly need.
Thanks for all the efforts you guys are putting and good luck!
How can we initialize a Canvas in React...
Though it's not clear what do you mean by 'outside useEffect', I would suggest to look at the article, that helped us a lot to setup React-wrapper for fabric: https://binarapps.com/integrate-fabric-js-canvas-drawing-library-with-react-app-via-uncontrolled-component/
How can we initialize a
Canvas
in React and ensure that thefabric.Canvas
object is available in methods outsideuseEffect
as well? Sorry I struggle with that, and would like some help there as this version provides interaction with group which I very importantly need.Thanks for all the efforts you guys are putting and good luck!
You can wrap your canvas component with React Context
Thank you @vinkovsky @ShaMan123 and @bladerunner2020 .
Pardon my lack of knowledge working with ReactJS, I followed @ShaMan123 's link (even though it's Typescript and I would like JS) and got it working somehow. However, @bladerunner2020 , your solution causes an issue of canvas already initialised
already mentioned in #8899 .
Happy to help provide more info if it helps.
added breaking changes from #8930
Are there any breaking changes with free drawing? I'm migrating my v5 app to v6 and can't get it working just by setting isDrawingMode on the canvas to true. (It worked in my v5 app.)
Yes, thanks!
Canvas#freeDrawingBrush
is not set by default.
so just canvas.freeDrawingBrush = new PencilBrush()
Yes, thanks!
Canvas#freeDrawingBrush
is not set by default. so justcanvas.freeDrawingBrush = new PencilBrush()
This worked. Thank you!
@asturur and @ShaMan123 I will start off by saying that first of all thank you for this version, it automatically helps resolve a lot of issues for me at work (most importantly object manipulation in groups (although it breaks for nested groups but that's not the purpose of this comment))
The issue is documented in this CodeSandbox (my original version is beta7 but this sandbox only had beta1), but it's also appearing here. The issue is that when I save JSON in my Firestore database (via canvas.toJSON
) and try to load it via loadFromJSON
, it just... throws many strange errors. Sometimes it would say No class registered for Group
and sometimes it would say can't set _set on null e
.
What is weird that I did not face any issue of this sort on v5 but it's breaking for v6. @ShaMan123 is it also the right way I have setup code in React in your opinion?
Happy to provide more info if needed!
edit: there's also the issue that it sometimes works fine locally and also loads the objects on canvas, but they're invisible, only when I click them do they become visible.
I didn't look into your sandbox but it is probably #9009 Open a dedicated issue next time
Hi @ShaMan123 @asturur , do you have ETA for the v6 release and not sure if we have a documentation for it yet? I am working on upgrading from v2x to v5, maybe I will wait for v6 since it has Promise support. Thank you so much for this version !
I noticed that the type support for canvas.getActiveObject() is off. I was chasing down a bug because I was unaware it returned a Promise. Usually my IDE warns me about unhandled promises, but it didn't for this one, and jumping into the definition shows me this, which can't be right:
getActiveObject(): FabricObject | undefined {
return this._activeObject;
}
I noticed that the type support for canvas.getActiveObject() is off. I was chasing down a bug because I was unaware it returned a Promise. Usually my IDE warns me about unhandled promises, but it didn't for this one, and jumping into the definition shows me this, which can't be right:
getActiveObject(): FabricObject | undefined { return this._activeObject; }
It is correct, no promise
Hi, I am going to start new project with fabric.js
and typescript
.
My question is which version should I use in production? v6 beta
or v5
?
I am afraid to migrate v5
to v6
.
At the same time, I am not sure it is right to use beta version
in production.
Please give me advice.
We are working on v6 for our projects. Typescript in v6 only. The amount of fixes in v6 is overwhelming. Since you are starting, v6 is the right choice IMO - you decide
We use 6 beta in prod. So far so good)
Same here. We started a new project with v6 a month ago and it's running in production now. No regrets so far.
How can we use fabric.util.addClass?
Tried converting some class based examples from the fabric js website but Im running into issues.
import React, { useEffect, useRef } from 'react';
import * as fabric from 'fabric';
const AnimatedCross = ({ canvas }) => {
const crossRef = useRef(null);
useEffect(() => {
const Cross = fabric.util.createClass(fabric.Object, {
objectCaching: false,
initialize: function (options) {
this.callSuper('initialize', options);
this.animDirection = 'up';
this.width = 100;
this.height = 100;
this.w1 = this.h2 = 100;
this.h1 = this.w2 = 30;
},
animateWidthHeight: function () {
const interval = 2;
if (this.h2 >= 30 && this.h2 <= 100) {
const actualInterval = this.animDirection === 'up' ? interval : -interval;
this.h2 += actualInterval;
this.w1 += actualInterval;
}
if (this.h2 >= 100) {
this.animDirection = 'down';
this.h2 -= interval;
this.w1 -= interval;
}
if (this.h2 <= 30) {
this.animDirection = 'up';
this.h2 += interval;
this.w1 += interval;
}
},
_render: function (ctx) {
ctx.fillRect(-this.w1 / 2, -this.h1 / 2, this.w1, this.h1);
ctx.fillRect(-this.w2 / 2, -this.h2 / 2, this.w2, this.h2);
},
});
const cross = new Cross({ top: 100, left: 100 });
crossRef.current = cross;
canvas.add(cross);
const animate = () => {
cross.animateWidthHeight();
cross.dirty = true;
canvas.renderAll();
requestAnimationFrame(animate);
};
animate();
}, [canvas]);
return null;
};
export default AnimatedCross;
@thisisdice I have removed your comment since it is spamming, proof is you couldn't see my previous comment
moved to native classes => no more
createClass
Originally posted by @ShaMan123 in https://github.com/fabricjs/fabric.js/issues/8299#issuecomment-1427028792
@asturur please update the desc to include classes and prototype changes (props, ownDefaults, etc.)
@abdussami-tayyab open an issue, reproduce it properly. Bugs are to be fixed, not worked around.
ActiveSelection
is a constant ref on canvas
canvas.setActiveObject(new ActiveSelection())
will break selection #9066
Hi @ShaMan123 !!
How is the beta going? Is it close to the v6 release?
Thanks in advance!
V6 is doing good Unfortunately timelines are not available. Everyone, including the team, wants it out already. I encourage everyone to move to beta now as it requires work and a change of some points in mindset. Contributions are welcome always. Testing is becoming easier thanks to playwright so contributing might become easier as well hopefully.
Is playwright used for e2e testing and/or more? Is there a main page for V6 for status, getting started, API, installing, running locally for contributing, examples, best implemented editors, etc.?
Is playwright used for e2e testing and/or more?
hmmm. I don't know. We just introduced it. I have been experimenting the past few days. Have any suggestions?
Is there a main page for V6 for status, getting started, API, installing, running locally for contributing, examples, best implemented editors, etc.?
There is this ticket. The README.md and CONTRIBUTING.md are pretty much up to date, if not or if irrelevant please say so/PR.
Ping me if that is not enough, I'd be happy to lend a hand.
For the greater community:
We want to wrap up the TS migration and we need help.
Contributions are needed!
Current task is to type the remaining files and address TS errors.
Contributors can search for files with @ts-nocheck
and get to work.
Open a draft PR with the title chore(TS): [SCOPE]
once you get started stating which files you wish to address so people don't work on the same thing.
Then when you are done, move it out of the draft state and review it and then one of us will review as well.
Be sure to check for open PRs before you start working.
If someone wishes to do it all go ahead.
Thanks!
Is playwright used for e2e testing and/or more?
hmmm. I don't know. We just introduced it. I have been experimenting the past few days. Have any suggestions?
Typically used for e2e testing, could be used to automate other things in the browser. Would suggest to use shared/reusable page objects. https://playwright.dev/docs/pom
Initialization threw an error
trying to initialize a canvas that has already been initialized at CanvasDOMManager.createLowerCanvas
Initialization threw an error
trying to initialize a canvas that has already been initialized at CanvasDOMManager.createLowerCanvas
The problem was finally found to be caused by executing react useEffect twice
It is recommended to export the options types of Rect Circle Line and other classes in fabric.ts, because importing the declaration files of these classes alone will trigger eslinet prettier warnings
At the same time, the options of canvas lack the type declaration
@hsbtr You should open an issue for this. Object options are now exported Exporting canvas options is a todo
When using canvas.loadFromJSON how can we handle images with outdated src properties returning 404s? I tried using the method's reviver arguments to handle this gracefully, but it looks like the callback is running when it's already too late.
Please do not abuse this ticket, we do not want to lock it. Use the appropriate channels (issues, discussions etc.)
centerPoint
doesn't exist anymore as initialization option to fabric.Group
groupSVGElements
doesn't accept the initial Group options anymore <= as it is now, it's not useful at all. Could be just removedloadSVGFromURL
signature changed, it's returning a Promise now什么时候能实现?
A few notes from my migration from v5 to v6:
Setting background image based on a data URL
canvas.setBackgroundImage(source.toDataURL(), renderCallback, options)
can become
canvas.backgroundImage = new fabric.Image(source, options)
PencilBrush._drawSegment
is now PencilBrush.drawSegment
Accessing fabric.document
and fabric.window
directly has been replaced by fabric.getFabricDocument()
/fabric.getFabricWindow()
PencilBrush._captureDrawingPath(pointer)
can be replaced with PencilBrush._addPoint(new fabric.Point(pointer.x, pointer.y))
什么时候能实现?
他们正在修复最后的错误,几周后应该就可以了
I use 6.x in my project and everything looks good, but EraserBrush can not be use. finially, I rollback to 5.x version 😭
@zhengguorong subscribe to #8499
Hey, do you have plans to implement kinda cornerBorderScaleFactor for changing the width of control borders? If yes, then I can try to contribute. My team really need it.
Trying to use "fabric": "v6.0.0-beta13" with Angular 15, getting the following error, do you know what is wrong?
Trying to use "fabric": "v6.0.0-beta13" with Angular 15, getting the following error, do you know what is wrong?
I'd recommend using skipLibCheck
in the tsconfig.json to avoid TS type checking the libs, including fabric. For the toObject
issue you can see https://github.com/fabricjs/fabric.js/pull/9014
Hey, do you have plans to implement kinda cornerBorderScaleFactor for changing the width of control borders? If yes, then I can try to contribute. My team really need it.
Open a discussion or a feature request with a screenshot of what you would like to get. Some of the answers could include that you can simply make your control render function with zero issues.
FYI. There is a break when upgrade the nextjs version from 13.4.19 to 13.5.1 for case using useEffect. My solution for now is revert next to previous version. Please refer to the screenshot for error message:
export default function Studio() {
useEffect(() => {
const canvas = new fabric.Canvas("canvas", {
height: 500,
width: 800,
backgroundColor: "#ededed",
})
}, [])
return (
<div>
<canvas id="canvas" className="h-[500px] w-[800px]" />
</div>
)
}
package.json
{
...
"dependencies": {
...
"fabric": "^6.0.0-beta13",
"next": "13.5.1",
...
},
}
b.0.0-beta16
This list is in progress and is meant to be an easy go to place to add things and find them when the time comes to write a document on what has changed. This will be a list of descriptive items, extended as needed to capture behavior changes. Apart from what is described here MANY bugs have been fixed in the process.
Generic concepts
Imports we moved from
import { fabric } from 'fabric'
toimport { Canvas, Rect, util } from 'fabric'
orimport * as fabric from 'fabric'
. To avoid packaging issues node has its own entrypointimport { StaticCanvas } from 'fabric/node'
. This means there is no fabric namespace/object anymore.classRegistry
to bridge the absence of a namespaceenv
concept,getEnv
to allow node/browser specific values/logic. That has made importing fabric in SSR possible and will allow offscreen support in the future.fabric.Object
=>FabricObject
fabric.Text
=>FabricText
fabric.Image
=>FabricImage
registerFont
has been removed, useregisterFont
exposed by node canvasmethod chaining is now deprecated, don't use it anymore. Not all methods were chainable, and chaining seems to offer limited advantages ( maybe saving 1-2 bytes in the code you write when minified? unsure what else ). Just for consistency sake and to be free to start returning useful information from some methods we will stop using it. We didn't remove it from everywhere so that there isn't unnecessary breakage, but you should consider that unsafe to use, since will break entirely on the next major release after 6.0 ( add detailed list of where has been removed so far )
Callbacks are mostly gone, all of the functions that took a callback now return a Promise, this on top of being breaking slightly alter code behavior when is fixed. Before sync code would execute the callback synchronously, now is chained to however the browser handle the promise ( not sure if it goes in the event loop and under which circumstances ). https://github.com/fabricjs/fabric.js/issues/3684
TS: The code base is typed! If you used
@types/fabric
you should uninstall itPrototype Mutation: Fabric has moved to native classes. No more
createClass
orobject.util.extend
. You can still mutate the prototype, however, properties do not exist on the prototype in native classes. Look intogetDefaults
instead.scene vs. viewport We introduced these concepts to describe the rendering/view planes as follows: The viewer is viewing the scene (what is rendered/"playing") from the viewport. The scene was considered is the past as the
absolute
plane whereas the viewport wasn't #9175. Normally geometry calculations occur in the scene with the exception ofpadding
which is a viewport scalar.scenePoint
andviewportPoint
properties replacing the deprecated and confusingabsolutePointer
andpointer
properties. Brushes are still in need of this change.Canvas#getPointer
in favor ofgetScenePoint
orgetViewportPoint
viewportTransform
is rather confusing with this change (especially withsendPointToPlane
etc.) perhaps be renaming tosceneTransform
is the correct migration path in the future.React Compatibility:
useEffect
, especially with React 18. Refer to this hook for guidance.dispose
is called while rendering is still in progress. This should burden your react app.Canvas#dispose
is calledCollection
fabric.Collection
any longer, was never meant to, it was a constrain of the previous build system ( we had no imports or require or bundling before ).insertAt
method signature changed frominsertAt(object, index)
toinsertAt(index, ...objects)
Group
:sendObjectToBack
sendToBackbringObjectToFront
bringToFrontsendObjectBackwards
sendBackwardsbringObjectForward
bringForwardmoveObjectTo
moveToCanvas and StaticCanvas
Canvas.dispose and StaticCanvas.dispose are now async In order to handle some concurrency issue with requestAnimationFrame, dispose is now checking and waiting for any uncancellable render to finish. This could have some side effects, especially in complex environments with UI frameworks and hot reload of code.
trying to initialize a canvas that has already been initialized
#7776 is not breaking, it saves the dev from a silent breakage that they weren't aware ofremoved canvas.straightenObject wasn't really useful.
changed cloneWithoutData , now it does not clone backgrounds.
canvas.clone now correctly return either a canvas or staticCanvas
drawClipPathOnCanvas
signature changed: now accepts the clipPath as a second argument instead of rechecking its existencegetCenter
renamed togetCenterPoint
#7699add
returns the length of the array of objects after adding, likeArray#push
remove
returns an array with the removed objects insideinsertAt
method signature changed (refer to theCollection
section)removed
sendToBack
,bringToFront
,sendBackward
,moveTo
,bringForward
( and gained similar methods from collection (refer to theCollection
section)Canvas#freeDrawingBrush
is not set by defaultscene vs. viewport changes
getPointer
in favor ofgetScenePoint
orgetViewportPoint
_normalizePointer
,restorePointerVpt
rm
interactive
flag, useinstance of Canvas
insteadrm
setBackgroundColor
,setBackgroundImage
,setOverlayColor
,setOverlayImage
: assign the property directly and render the canvasObject
lineCoords
aCoords
should be treated as protected , if you need the scene corners of an object usegetCoords
absolute
,calculate
from geometry methods signatures (all listed methods operate in the scene):getCoords
intersectsWithRect
intersectsWithObject
isContainedWithinObject
isContainedWithinRect
getBoundingRect
containsPoint
changed signature entirely and fixedgetRelativeXY
/setRelativeXY
to get/set the coordinate in the parent plane,getXY
/setXY
to get/set the coordinate in the scene planeadjustPosition
is gone. It took a parameter only, was internally unused, didn't take care of internal edge cases setPositionByOrigin is more flexible_setOriginToCenter
and_resetOrigin
#9179oCoords
) are calculated only if the object has acanvas
reftype
has become a static field and should be used only for serialization withclassRegistry
. There is still a deprecated getter on the object for compatibility reasons. Avoid using it.stateful
was used to fire an object modified every render cycle in which a change in state properties was determiend. All the events that can modify an object already fire anobject:modified
event, and the user has no ability to change colors or state outside developer written code, so there is no really need for event firing here. statefulCache was an experiment and the suggestion to useset(property, value)
replaced it since long. FabricJS internally still use some stateful logic for now, but the intention is to get rid of it.center
,centerH
,centerV
,viewportCenter
are gone. Those were aliases for the canvas methods, use them instead.animate
changed to adapt to animation changescontrols
object is not shared between instances - it is not on the prototype as all class fieldsObject#getObjectScaling
,Object#getTotalObjectScaling
now returnsPoint
instead of{scaleX,scaleY}
#7710Text
data-fabric-hiddentextarea
todata-fabric
with valuetextarea
, if you were usinghasAttribute('data-fabric-hiddentextarea')
now you have to usegetAttribute('data-fabric')
and then check for equality withtextarea
or change your cssSelector accordingly._getStyleDeclaration
returns an empty object instead of undefined when style is not set.Polyline Polygon Path
_setPositionDimensions
(considered private in the past), has been renamed tosetDimensions
. The logic with which Polyline based object calculate the size is changed. There wasn't an api in 5.x to change the size, but devs needed to do it anyway and the alternative was to create a new object. Is not called setPositionAndDimensions because the logic to correcly change size while keeping a visual correct position is not there yet and maybe it won't.createPolyControls
Group
parent
property onFabricObject
alongsidegroup
to allow an object to return to itsparent
after being deselected from an active selection.addWithUpdate
is gone, nowadd
does what it has to do.LayoutManager
has been introduced to handle group layout #9152. By default it will befit-content
, meaning the group will fit around its objects, updating when objects are added/removed/modified.Controls
shouldActivate
for ease of use #8934 #9374Serialization
Text#styles
is now exported differently. This is BREAKING only if you are handling the style object post export The default object we exported was large most of the time, with tons of empty keys and verbosity. It seems reasonable to think that most of the time text is styled in some chunk of text with coherent different styles ( eg: a red word in a black text or some words underlined and some not more than a rainbow of different stylings per object ) for that reason we changed the approach of serialization to an array with start and end index for the style. We didn't apply that to actual runtime code because we were unsure of performance, so at least for version 6, styles at runtime are going to be the same. It is highly recommended to not fiddle with the style object directly and to treat it as internal, using the public facing methods to apply changes. https://github.com/fabricjs/fabric.js/pull/8006populateWithProperties
=>pick
populate with properties was used internally to add the extra options to exported objects. Between spread operator and new syntax, a generic pick approach seemed more correct.toJSON
is not an alias oftoObject
. This was a long standing bug, but also a breaking change.toJSON
never accepted additional properties and will give you only the default object export.toJSON
is meant forJSON#stringify
interoperability and is not meant to be used in your code base directly. reference #8111NUM_FRACTION_DIGIT
moved toconfig
and incremented from 2 to 4Brushes
PatternBrush
: removed thegetPatternSrcFunction
. Wasn't working anymore since the refactor of Pattern and also a super weird practice.Animation
+=
or-=
syntax for changes, nor accept the byValue option. You can specify an animation only by startValue and endValue.Utils
makeBoundingBoxFromPoints
signature change. The transformation is not supported anymore and requires real pointsclone
andextend
have been removed. Those were used in all examples unfortunately so the community has likely adopted them, consider migrating to a well known common library for those functionalities ( lodash, underscore ... ). Avoid using such utilities on classes.makeElementSelectable
andmakeElementUnselectable
are removed. Those were needed internally and one of them is still used internally, but is not a fabricJS core functionality and not part of the api anymore.sendObjectToPlane
,sendPointToPlane
,sendVectorToPlane
to ease common usages of linear algebra. Check them out, you will benefit from it.Misc
Observable
now returns a disposer making it easier to use and theoff
method redundant #7994Point
methods #7716 #7709