I'm new to fabricjs, I've been trying to blur an image using a HTML slider(range from 0 - 1). The image has already been loaded on the canvas. But while applying the blur effect using Filters arrays, I don't see any visible change.
I'm using a controlled blur component in React as follows :
<div>
Blur
<input
id="blur"
type="range"
min="0"
max="1"
step="0.1"
value={editor?.canvas?.getActiveObject()?.filters?.slice(-1)[0]?.blur || 0}
onChange={(e) => handleChangeSlider("blur", e?.target?.value)}
></input>
<span>{editor?.canvas?.getActiveObject()?.filters.slice(-1)[0]?.blur || 0}</span>
</div>
the onChange handler function is as follows :
function handleChangeSlider(){
setBlur(value)
editor?.canvas?.getActiveObject()?.filters?.push({
blur: 0.5,
horizontal: false,
aspectRatio: 1,
})
// editor?.canvas?.getActiveObject()?.applyFilters()
}
editor.canvas.renderAll()
}
The same approach works if I'm setting opacity on the image, like:
editor.canvas.getActiveObject().set({ opacity: value })
But, as far as I know, the Blur has to be inside the filters array, So I've tried doing the same, but it is not working at all.
Some Observations :
Even after doing the editor.canvas.renderAll() , I think editor?.canvas?.getActiveObject()?.applyFilters() is necessary to apply the blur property. But if I uncomment that line from above code, i get the following error "filter.isNeutralState is not a function" . While that line being kept commented, I don't see any error or any change.
I found this codepen link, where the author is literally doing the same, But I'm not sure what I'm doing wrong in my case.
My editor?.canvas?.getActiveObject()
Сreate a filter like this:
new fabric.Image.filters.Blur({
blur: 0.5,
horizontal: false,
aspectRatio: 1,
});
In order to solve the cross-origin issue use the additional parameter:
fabric.Image.fromURL(
activeDragDropItem.src,
function (oImg) {
oImg.scale(0.2);
oImg.top = e.nativeEvent.layerY;
oImg.left = e.nativeEvent.layerX;
editor.canvas.add(oImg);
},
{
crossOrigin: "",
}
);
I have two small green divs within my canvas. It can be drag within the canvas with an id myid_templates_editor_canvas, with the use of the code below:
myid_templates_editor_make_draggable('div1');
myid_templates_editor_make_draggable('div2');
// Make an element draggable within the canvas
function myid_templates_editor_make_draggable(id){
jQuery('#' + id).draggable({
cursor: 'move',
cursorAt: { top: 56, left: 56 },
containment: '#myid_templates_editor_canvas',
});
}
See images below:
I have made a line between 2 draggable divs using jsPlumb.
var jsPlumb_instance = jsPlumb.getInstance();
var endpointOptions = {
anchor:'BottomCenter',
maxConnections:1,
endpoint:['Rectangle',{width:'0px', height:'0px' }],
paintStyle:{fillStyle:'black'},
connectorStyle : { lineWidth: '1px' , strokeStyle: 'black' },
connector : ['Straight'],
setDragAllowedWhenFull:true,
};
div1Endpoint = jsPlumb_instance.addEndpoint('div1', endpointOptions);
div2Endpoint = jsPlumb_instance.addEndpoint('div2', endpointOptions);
jsPlumb_instance.connect({
source:div1Endpoint,
target:div2Endpoint,
});
jsPlumb_instance.draggable('div1');
jsPlumb_instance.draggable('div2');
I dont want the line outside the canvas border. See 3rd picture.
I want the line to be contained within the canvas with an id myid_templates_editor_canvas.See the image below:
I tried changing part of the code above with the the code below, with no luck.
jsPlumb_instance[id].draggable(id1, {containment:'#myid_templates_editor_canvas'});
jsPlumb_instance[id].draggable(id2 , {containment:'#myid_templates_editor_canvas'});
Yes, the two points was somehow constrained because the length of the maximum line was limited but still goes out of the border of the canvas.Below is the html set-up of the canvas and two points.
<table>
<tr>
<td>
<canvas id="myid_templates_editor_canvas"></canvas>
<div id="div1"></div>
<div id="div2"></div>
</td>
</tr>
</table>
I worked with jsPlumb for quite long already and I remembered it need to refer to a lot of library.
Because jsPlumb using draggable feature from jQuery UI, you can read this article for understanding how it is being worked.
https://jqueryui.com/draggable/#constrain-movement
In your case, myid_templates_editor_canvas will not be consider as the containment, it is for drawing only. So I suggest you to modify your html as below try, let me know your result as well.
I put an ID for table element and it will be the containment for 2 end points. The containment must be an element that contains child element - in the other words - parent element.
myid_templates_editor_make_draggable('div1');
myid_templates_editor_make_draggable('div2');
// Make an element draggable within the canvas
function myid_templates_editor_make_draggable(id){
jQuery('#' + id).draggable({
cursor: 'move',
cursorAt: { top: 56, left: 56 },
containment: '#main-container',
});
}
<table id="main-container">
<tr>
<td>
<canvas id="myid_templates_editor_canvas"></canvas>
<div id="div1"></div>
<div id="div2"></div>
</td>
</tr>
</table>
Actually you can set containment via jsPlumb. See my jsFiddle. The reason why your solution did not work is that you have set draggable via jsPlumb, not jQuery. They do not know about it other, so can not work together. You need to provide options to draggable function:
jsPlumb_instance.draggable(element, { containment:true });
To know more about draggable in jsPlumb see help. You can set containment container explicitly when you get instance of jsPlumb:
var jsPlumb_instance = jsPlumb.getInstance({ Container:"inner" });
You can also specify DragOptions and DropOptions if you need (more info).
It is better to set draggable via jsPlumb, as a plus, then no need to call repaint after dragging is finished. A huge performance benefit with a lot of elements.
A common feature of interfaces using jsPlumb is that the elements are
draggable. You should use the draggable method on a jsPlumbInstance to
configure this:
myInstanceOfJsPlumb.draggable("elementId");
...because if you don't, jsPlumb won't know that an element has been
dragged, and it won't repaint the element.
I had made a solution to my problem. I changed my code above to to code below:
myid_templates_editor_make_draggable('div1');
myid_templates_editor_make_draggable('div2');
//Make an element draggable within the canvas
function myid_templates_editor_make_draggable(id){
jQuery('#' + id).draggable({
cursor: 'move',
cursorAt: { top: 56, left: 56 },
containment: '#myid_templates_editor_canvas',
drag: function(e, ui){
jsPlumb_instance.repaintEverything();
},
});
}
I had also omit the line of code that make JsPlumb two endpoints draggable.
var jsPlumb_instance = jsPlumb.getInstance();
var endpointOptions = {
anchor:'BottomCenter',
maxConnections:1,
endpoint:['Rectangle',{width:'0px', height:'0px' }],
paintStyle:{fillStyle:'black'},
connectorStyle : { lineWidth: '1px' , strokeStyle: 'black' },
connector : ['Straight'],
setDragAllowedWhenFull:true,
};
div1Endpoint = jsPlumb_instance.addEndpoint('div1', endpointOptions);
div2Endpoint = jsPlumb_instance.addEndpoint('div2', endpointOptions);
jsPlumb_instance.connect({
source:div1Endpoint,
target:div2Endpoint,
});
Hope it helps everyone that is going through the same problem with me.
I've seen this hack for native apps to auto scroll the window, but wondering best way to do it in React Native... When a <TextInput> field gets focus and is positioned low in the view, the keyboard will cover up the text field.
You can see this issue in example UIExplorer's TextInputExample.js view.
Does anyone have a good solution?
2017 Answer
The KeyboardAvoidingView is probably the best way to go now. Check out the docs here. It is really simple compared to Keyboard module which gives Developer more control to perform animations. Spencer Carli demonstrated all the possible ways on his medium blog.
2015 Answer
The correct way to do this in react-native does not require external libraries, takes advantage of native code, and includes animations.
First define a function that will handle the onFocus event for each TextInput (or any other component you would like to scroll to):
// Scroll a component into view. Just pass the component ref string.
inputFocused (refName) {
setTimeout(() => {
let scrollResponder = this.refs.scrollView.getScrollResponder();
scrollResponder.scrollResponderScrollNativeHandleToKeyboard(
React.findNodeHandle(this.refs[refName]),
110, //additionalOffset
true
);
}, 50);
}
Then, in your render function:
render () {
return (
<ScrollView ref='scrollView'>
<TextInput ref='username'
onFocus={this.inputFocused.bind(this, 'username')}
</ScrollView>
)
}
This uses the RCTDeviceEventEmitter for keyboard events and sizing, measures the position of the component using RCTUIManager.measureLayout, and calculates the exact scroll movement required in scrollResponderInputMeasureAndScrollToKeyboard.
You may want to play around with the additionalOffset parameter, to fit the needs of your specific UI design.
Facebook open sourced KeyboardAvoidingView in react native 0.29 to solve this problem. Documentation and usage example can be found here.
We combined some of the code form react-native-keyboard-spacer and the code from #Sherlock to create a KeyboardHandler component that can be wrapped around any View with TextInput elements. Works like a charm! :-)
/**
* Handle resizing enclosed View and scrolling to input
* Usage:
* <KeyboardHandler ref='kh' offset={50}>
* <View>
* ...
* <TextInput ref='username'
* onFocus={()=>this.refs.kh.inputFocused(this,'username')}/>
* ...
* </View>
* </KeyboardHandler>
*
* offset is optional and defaults to 34
* Any other specified props will be passed on to ScrollView
*/
'use strict';
var React=require('react-native');
var {
ScrollView,
View,
DeviceEventEmitter,
}=React;
var myprops={
offset:34,
}
var KeyboardHandler=React.createClass({
propTypes:{
offset: React.PropTypes.number,
},
getDefaultProps(){
return myprops;
},
getInitialState(){
DeviceEventEmitter.addListener('keyboardDidShow',(frames)=>{
if (!frames.endCoordinates) return;
this.setState({keyboardSpace: frames.endCoordinates.height});
});
DeviceEventEmitter.addListener('keyboardWillHide',(frames)=>{
this.setState({keyboardSpace:0});
});
this.scrollviewProps={
automaticallyAdjustContentInsets:true,
scrollEventThrottle:200,
};
// pass on any props we don't own to ScrollView
Object.keys(this.props).filter((n)=>{return n!='children'})
.forEach((e)=>{if(!myprops[e])this.scrollviewProps[e]=this.props[e]});
return {
keyboardSpace:0,
};
},
render(){
return (
<ScrollView ref='scrollView' {...this.scrollviewProps}>
{this.props.children}
<View style={{height:this.state.keyboardSpace}}></View>
</ScrollView>
);
},
inputFocused(_this,refName){
setTimeout(()=>{
let scrollResponder=this.refs.scrollView.getScrollResponder();
scrollResponder.scrollResponderScrollNativeHandleToKeyboard(
React.findNodeHandle(_this.refs[refName]),
this.props.offset, //additionalOffset
true
);
}, 50);
}
}) // KeyboardHandler
module.exports=KeyboardHandler;
First you need to install react-native-keyboardevents.
In XCode, in the project navigator, right click Libraries ➜ Add
Files to [your project's name] Go to node_modules ➜
react-native-keyboardevents and add the .xcodeproj file
In XCode, in the
project navigator, select your project. Add the lib*.a from the keyboardevents
project to your project's Build Phases ➜ Link Binary With Libraries Click
.xcodeproj file you added before in the project navigator and go the Build
Settings tab. Make sure 'All' is toggled on (instead of 'Basic').
Look for Header Search Paths and make sure it contains both
$(SRCROOT)/../react-native/React and $(SRCROOT)/../../React - mark
both as recursive.
Run your project (Cmd+R)
Then back in javascript land:
You need to import the react-native-keyboardevents.
var KeyboardEvents = require('react-native-keyboardevents');
var KeyboardEventEmitter = KeyboardEvents.Emitter;
Then in your view, add some state for the keyboard space and update from listening to the keyboard events.
getInitialState: function() {
KeyboardEventEmitter.on(KeyboardEvents.KeyboardDidShowEvent, (frames) => {
this.setState({keyboardSpace: frames.end.height});
});
KeyboardEventEmitter.on(KeyboardEvents.KeyboardWillHideEvent, (frames) => {
this.setState({keyboardSpace: 0});
});
return {
keyboardSpace: 0,
};
},
Finally, add a spacer to your render function beneath everything so when it increases size it bumps your stuff up.
<View style={{height: this.state.keyboardSpace}}></View>
It is also possible to use the animation api, but for simplicity's sake we just adjust after the animation.
react-native-keyboard-aware-scroll-view solved the problem for me.
react-native-keyboard-aware-scroll-view on GitHub
Try this:
import React, {
DeviceEventEmitter,
Dimensions
} from 'react-native';
...
getInitialState: function() {
return {
visibleHeight: Dimensions.get('window').height
}
},
...
componentDidMount: function() {
let self = this;
DeviceEventEmitter.addListener('keyboardWillShow', function(e: Event) {
self.keyboardWillShow(e);
});
DeviceEventEmitter.addListener('keyboardWillHide', function(e: Event) {
self.keyboardWillHide(e);
});
}
...
keyboardWillShow (e) {
let newSize = Dimensions.get('window').height - e.endCoordinates.height;
this.setState({visibleHeight: newSize});
},
keyboardWillHide (e) {
this.setState({visibleHeight: Dimensions.get('window').height});
},
...
render: function() {
return (<View style={{height: this.state.visibleHeight}}>your view code here...</View>);
}
...
It worked for me. The view basically shrinks when the keyboard is displayed, and grows back again when its hidden.
Just wanted to mention, now there is a KeyboardAvoidingView in RN. Just import it and use it as any other module in RN.
Here is the link to the commit on RN:
https://github.com/facebook/react-native/commit/8b78846a9501ef9c5ce9d1e18ee104bfae76af2e
It is available from 0.29.0
They have also included an example on UIExplorer.
Maybe is to late, but the best solution is to use a native library, IQKeyboardManager
Just drag and drop IQKeyboardManager directory from demo project to your iOS project. That's it. Also you can setup some valus, as isToolbar enabled, or the space between text input and keyboard in the AppDelegate.m file. More details about customisation are in the GitHub page link that I've added.
I used TextInput.onFocus and ScrollView.scrollTo.
...
<ScrollView ref="scrollView">
...
<TextInput onFocus={this.scrolldown}>
...
scrolldown: function(){
this.refs.scrollView.scrollTo(width*2/3);
},
#Stephen
If you don't mind not having the height animate at exactly the same rate that the keyboard appears, you can just use LayoutAnimation, so that at least the height doesn't jump into place. e.g.
import LayoutAnimation from react-native and add the following methods to your component.
getInitialState: function() {
return {keyboardSpace: 0};
},
updateKeyboardSpace: function(frames) {
LayoutAnimation.configureNext(animations.layout.spring);
this.setState({keyboardSpace: frames.end.height});
},
resetKeyboardSpace: function() {
LayoutAnimation.configureNext(animations.layout.spring);
this.setState({keyboardSpace: 0});
},
componentDidMount: function() {
KeyboardEventEmitter.on(KeyboardEvents.KeyboardDidShowEvent, this.updateKeyboardSpace);
KeyboardEventEmitter.on(KeyboardEvents.KeyboardWillHideEvent, this.resetKeyboardSpace);
},
componentWillUnmount: function() {
KeyboardEventEmitter.off(KeyboardEvents.KeyboardDidShowEvent, this.updateKeyboardSpace);
KeyboardEventEmitter.off(KeyboardEvents.KeyboardWillHideEvent, this.resetKeyboardSpace);
},
Some example animations are (I'm using the spring one above):
var animations = {
layout: {
spring: {
duration: 400,
create: {
duration: 300,
type: LayoutAnimation.Types.easeInEaseOut,
property: LayoutAnimation.Properties.opacity,
},
update: {
type: LayoutAnimation.Types.spring,
springDamping: 400,
},
},
easeInEaseOut: {
duration: 400,
create: {
type: LayoutAnimation.Types.easeInEaseOut,
property: LayoutAnimation.Properties.scaleXY,
},
update: {
type: LayoutAnimation.Types.easeInEaseOut,
},
},
},
};
UPDATE:
See #sherlock's answer below, as of react-native 0.11 the keyboard resizing can be solved using built in functionality.
You can combine a few of the methods into something a little simpler.
Attach a onFocus listener on your inputs
<TextInput ref="password" secureTextEntry={true}
onFocus={this.scrolldown.bind(this,'password')}
/>
Our scroll down method looks something like :
scrolldown(ref) {
const self = this;
this.refs[ref].measure((ox, oy, width, height, px, py) => {
self.refs.scrollView.scrollTo({y: oy - 200});
});
}
This tells our scroll view (remember to add a ref) to scroll to down to the position of our focused input - 200 (it's roughly the size of the keyboard)
componentWillMount() {
this.keyboardDidHideListener = Keyboard.addListener(
'keyboardWillHide',
this.keyboardDidHide.bind(this)
)
}
componentWillUnmount() {
this.keyboardDidHideListener.remove()
}
keyboardDidHide(e) {
this.refs.scrollView.scrollTo({y: 0});
}
Here we reset our scroll view back to the top,
I'm using a simpler method, but it's not animated yet. I have a component state called "bumpedUp" which I default to 0, but set to 1 when the textInput gets focus, like this:
On my textInput:
onFocus={() => this.setState({bumpedUp: 1})}
onEndEditing={() => this.setState({bumpedUp: 0})}
I also have style that gives the wrapping container of everything on that screen a bottom margin and negative top margin, like this:
mythingscontainer: {
flex: 1,
justifyContent: "center",
alignItems: "center",
flexDirection: "column",
},
bumpedcontainer: {
marginBottom: 210,
marginTop: -210,
},
And then on the wrapping container, I set the styles like this:
<View style={[styles.mythingscontainer, this.state.bumpedUp && styles.bumpedcontainer]}>
So, when the "bumpedUp" state gets set to 1, the bumpedcontainer style kicks in and moves the content up.
Kinda hacky and the margins are hardcoded, but it works :)
I use brysgo answer to raise the bottom of my scrollview. Then I use the onScroll to update the current position of the scrollview. I then found this React Native: Getting the position of an element to get the position of the textinput. I then do some simple math to figure out if the input is in the current view. Then I use scrollTo to move the minimum amount plus a margin. It's pretty smooth. Heres the code for the scrolling portion:
focusOn: function(target) {
return () => {
var handle = React.findNodeHandle(this.refs[target]);
UIManager.measureLayoutRelativeToParent( handle,
(e) => {console.error(e)},
(x,y,w,h) => {
var offs = this.scrollPosition + 250;
var subHeaderHeight = (Sizes.width > 320) ? Sizes.height * 0.067 : Sizes.height * 0.077;
var headerHeight = Sizes.height / 9;
var largeSpace = (Sizes.height - (subHeaderHeight + headerHeight));
var shortSpace = largeSpace - this.keyboardOffset;
if(y+h >= this.scrollPosition + shortSpace) {
this.refs.sv.scrollTo(y+h - shortSpace + 20);
}
if(y < this.scrollPosition) this.refs.sv.scrollTo(this.scrollPosition - (this.scrollPosition-y) - 20 );
}
);
};
},
I also meet this question. Finally, I resolve it by defining the height of each scene, such as:
<Navigator
...
sceneStyle={{height: **}}
/>
And, I also use a third-party module https://github.com/jaysoo/react-native-extra-dimensions-android to get the real height.
I have a web page that is loading images and scans across about 600+ images as the user presses next or previous. This is working fine. However, the image load time is slow so the idea is to put a processing while in place of the images until they are fully loaded. I can get the processing wheel to load perfectly fine but I cannot get it to hide once the image or document is loaded. I have tried doing this two different ways:
Attempt 1:
$('#centerImage').ready(function () {
$('.spinner').css('display', 'none');
});
Attempt 2:
$('#centerImage').ready(function () {
$('.spinner').hide();
});
I have also tried replacing the selector #centerImage on the .ready() function with document but still don't see the Processing Wheel get hidden.
What I find strange is that when I try and hide an ID instead of a Class, it works perfectly fine. I tried a 'Try Me' on W3 Schools with a simple example and hiding a class with the .hide() doesn't work there either.
Google isn't returning anything specific to any limitations with jQuery hiding classes. Is this possible or am I approaching this the wrong way?
NOTE: I'm using spin.js for the processing wheel.
All Code:
JavaScript:
EDIT: Added .load instead of .ready
var previousImage = document.getElementById("previousImage");
var centerImage = document.getElementById("centerImage");
var nextImage = document.getElementById("nextImage");
previousImage.setAttribute("src", "../.." + document.getElementById("MainContent_lblPreviousImage").innerHTML);
centerImage.setAttribute("src", "../.." + document.getElementById("MainContent_lblCenterImage").innerHTML);
nextImage.setAttribute("src", "../.." + document.getElementById("MainContent_lblNextImage").innerHTML);
$('#centerImage').load(function () {
$('.spinner').hide();
});
HTML/ASP.NET:
<div id="images">
<img id="previousImage" onload="showProgress()" alt="" src=""/>
<img id="centerImage" onload="showProgress()" alt="" src=""/>
<img id="nextImage" onload="showProgress()" alt="" src=""/>
</div>
Show Progress JavaScript File:
function showProgress () {
var opts = {
lines: 13, // The number of lines to draw
length: 20, // The length of each line
width: 10, // The line thickness
radius: 30, // The radius of the inner circle
corners: 1, // Corner roundness (0..1)
rotate: 0, // The rotation offset
direction: 1, // 1: clockwise, -1: counterclockwise
color: '#000', // #rgb or #rrggbb or array of colors
speed: 1, // Rounds per second
trail: 60, // Afterglow percentage
shadow: false, // Whether to render a shadow
hwaccel: false, // Whether to use hardware acceleration
className: 'spinner', // The CSS class to assign to the spinner
zIndex: 2e9, // The z-index (defaults to 2000000000)
top: '50%', // Top position relative to parent
left: '50%' // Left position relative to parent
};
var target = document.getElementById('images');
var spinner = new Spinner(opts).spin(target);
}
Thanks in advance for any helpful input.
As #Barmar $("#centerimage").ready() is the same as $(document).ready(). There's no separate ready event for each element, it just applies to the whole DOM.
Ready is used to check if the DOM is ready and the load is used to check if the Content is loaded.
Use load instead of ready:
$('#centerImage').load(function () {
In Scriptaculous 1, you could animate styles:
new Effect.Morph('id', {
style: { background: tomato },
duration: '4' });
But a better way was to keep the CSS and JS separate and merely reference a class:
new Effect.Morph('id', {
style: 'important',
duration: '4' });
Marvellous. But this doesn't seem to work with the new Scripty 2. Works:
$('id').morph('background: tomato', { duration: 4 });
Breaks:
$('id').morph('important', { duration: 4 });
What is the right way to animate using a class in Scripty 2? (I suspected Style, but the docs were vague.)
I checked out the source code and s2 only takes 'styleProp:value' for the style option. The string needs to have a colon.
The only method that will additionally take the class name as well 'styleProp:value' for the style option is a method called S2.FX.Operators.WebkitCssTransition. However, the S2.Extensions.webkitCSSTransitions are turned off by default. Although, the code in that method to be used to make your own patch to the .Morph method.