How to have source as rectangle for dragg - javascript

i have a requirement to have rectangle shape of fixed size and must be draggable to container, so that i can connect them.
i have searched alot but did not find any solution.
Question: single rectangle shape(fixed size) should be dragged to container
For full view Code pen:https://codepen.io/eabangalore/pen/LvzXxX
here is how:
Code Demo:
<!--
$Id: helloworld.html,v 1.6 2013/10/28 08:44:54 gaudenz Exp $
Copyright (c) 2006-2013, JGraph Ltd
Hello, World! example for mxGraph. This example demonstrates using
a DOM node to create a graph and adding vertices and edges.
-->
<html>
<head>
<title>Hello, World! example for mxGraph</title>
<!-- Sets the basepath for the library if not in same directory -->
<script type="text/javascript">
mxBasePath = 'https://jgraph.github.io/mxgraph/javascript/src';
</script>
<!-- Loads and initializes the library -->
<script type="text/javascript" src="https://jgraph.github.io/mxgraph/javascript/src/js/mxClient.js"></script>
<!-- Example code -->
<script type="text/javascript">
// Program starts here. Creates a sample graph in the
// DOM node with the specified ID. This function is invoked
// from the onLoad event handler of the document (see below).
function main(container)
{
// Checks if the browser is supported
if (!mxClient.isBrowserSupported())
{
// Displays an error message if the browser is not supported.
mxUtils.error('Browser is not supported!', 200, false);
}
else
{
// Disables the built-in context menu
mxEvent.disableContextMenu(container);
// Creates the graph inside the given container
var graph = new mxGraph(container);
// Enables rubberband selection
new mxRubberband(graph);
// Gets the default parent for inserting new cells. This
// is normally the first child of the root (ie. layer 0).
var parent = graph.getDefaultParent();
// Adds cells to the model in a single step
graph.getModel().beginUpdate();
try
{
var v1 = graph.insertVertex(parent, null, 'Hello,', 20, 20, 80, 30);
var v2 = graph.insertVertex(parent, null, 'World!', 200, 150, 80, 30);
var e1 = graph.insertEdge(parent, null, '', v1, v2);
}
finally
{
// Updates the display
graph.getModel().endUpdate();
}
}
};
</script>
</head>
<!-- Page passes the container for the graph to the program -->
<body onload="main(document.getElementById('graphContainer'))">
<!-- Creates a container for the graph with a grid wallpaper -->
<div id="graphContainer"
style="position:relative;overflow:scroll;width:321px;height:241px;background:url('https://jgraph.github.io/mxgraph/javascript/examples/editors/images/grid.gif');cursor:default;">
</div>
</body>
</html>
Please help me thanks in advance!!!!!

You can try something like
$(".rectagle").draggable({helper: 'clone'});
$("#canvas").droppable({
accept: ".rectagle",
drop: function(ev,ui){
$(ui.draggable).clone().appendTo(this);
}
});
#canvas {
height: 100px;
border: 1px solid lightgrey;
}
.rectagle {
display: inline-block;
height: 50px;
width: 50px;
border: 1px solid lightblue;
text-align: center;
background-color: lightgreen;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script src="//code.jquery.com/ui/1.11.2/jquery-ui.js"></script>
<div class="rectagle"></div>
<div id="canvas"></div>

function addToolbarItem(graph, toolbar, prototype, image)
{
// Function that is executed when the image is dropped on
// the graph. The cell argument points to the cell under
// the mousepointer if there is one.
var funct = function(graph, evt, cell)
{
graph.stopEditing(false);
var pt = graph.getPointForEvent(evt);
var vertex = graph.getModel().cloneCell(prototype);
vertex.geometry.x = pt.x;
vertex.geometry.y = pt.y;
graph.setSelectionCells(graph.importCells([vertex], 0, 0, cell));
}
// Creates the image which is used as the drag icon (preview)
var img = toolbar.addMode(null, image, funct);
mxUtils.makeDraggable(img, graph, funct);
}
try this example

Related

How change color of dotted line in mxgraph

I want to change the color of dotted line from black to red when we drag a vertex
Question: I want to change dotted line color to red from black while drag
Here is how it appears on drag
I tried to find the dashed color on drag in mxConstants but i did not find it
function main(container)
{
// Checks if the browser is supported
if (!mxClient.isBrowserSupported())
{
// Displays an error message if the browser is not supported.
mxUtils.error('Browser is not supported!', 200, false);
}
else
{
// Disables the built-in context menu
mxEvent.disableContextMenu(container);
// Creates the graph inside the given container
var graph = new mxGraph(container);
// Enables rubberband selection
new mxRubberband(graph);
// Gets the default parent for inserting new cells. This
// is normally the first child of the root (ie. layer 0).
var parent = graph.getDefaultParent();
// Adds cells to the model in a single step
graph.getModel().beginUpdate();
try
{
var v1 = graph.insertVertex(parent, null, 'Hello,', 20, 20, 80, 30);
}
finally
{
// Updates the display
graph.getModel().endUpdate();
}
}
};
<html>
<head>
<title>Toolbar example for mxGraph</title>
<script type="text/javascript">
mxBasePath = 'https://jgraph.github.io/mxgraph/javascript/src';
</script>
<script src="https://jgraph.github.io/mxgraph/javascript/src/js/mxClient.js"></script>
<script src="./app.js"></script>
</head>
<body onload="main(document.getElementById('graphContainer'))">
<div id="graphContainer">
</div>
</body>
</html>
Please help me thanks in advance!!!
Based on this you can do that by below code:
mxGraphHandler.prototype.previewColor = 'red';
Working snippet:
function main(container)
{
mxGraphHandler.prototype.previewColor = 'red';
// Checks if the browser is supported
if (!mxClient.isBrowserSupported())
{
// Displays an error message if the browser is not supported.
mxUtils.error('Browser is not supported!', 200, false);
}
else
{
// Disables the built-in context menu
mxEvent.disableContextMenu(container);
// Creates the graph inside the given container
var graph = new mxGraph(container);
// Enables rubberband selection
new mxRubberband(graph);
// Gets the default parent for inserting new cells. This
// is normally the first child of the root (ie. layer 0).
var parent = graph.getDefaultParent();
// Adds cells to the model in a single step
graph.getModel().beginUpdate();
try
{
var v1 = graph.insertVertex(parent, null, 'Hello,', 20, 20, 80, 30);
}
finally
{
// Updates the display
graph.getModel().endUpdate();
}
}
};
<html>
<head>
<title>Toolbar example for mxGraph</title>
<script type="text/javascript">
mxBasePath = 'https://jgraph.github.io/mxgraph/javascript/src';
</script>
<script src="https://jgraph.github.io/mxgraph/javascript/src/js/mxClient.js"></script>
<script src="./app.js"></script>
</head>
<body onload="main(document.getElementById('graphContainer'))">
<div id="graphContainer">
</div>
</body>
</html>

How to add toolbar to BokehJS plot?

My goal is to add a toolbar to a BokehJS plot. According to the plot tools documention this should be possible by doing (translating the Python example to Javascript):
plot.add_tools(new Bokeh.BoxZoomTool());
plot.add_tools(new Bokeh.ResetTool());
plot.toolbar_location = "right";
I have added these lines to the basic BokehJS example from the documentation, and they don't produce errors/warnings. However, the toolbar does not show up (properly) and the tools don't really seem to work.
I have prepared a minimal JSFiddle to demonstrate the problem: When using the rectangle select tool the plot moves around strangely, which uncovers an unstyled version of the toolbar rendered underneath the plot.
So the question is how can I get a properly working toolbar in BokehJS?
Add bk-root to the root element. <div id="plot" class="mybokehplot bk-root"></div>
Add corresponding css files (bokeh-0.12.0.min.css and bokeh-widgets-0.12.0.min.css).
JSFiddle here:
https://jsfiddle.net/blackmiaool/xzvgrqLj/
Snippet here:
// create some data and a ColumnDataSource
var x = Bokeh.LinAlg.linspace(-0.5, 20.5, 10);
var y = x.map(function(v) {
return v * 0.5 + 3.0;
});
var source = new Bokeh.ColumnDataSource({
data: {
x: x,
y: y
}
});
// create some ranges for the plot
var xdr = new Bokeh.Range1d({
start: -0.5,
end: 20.5
});
var ydr = Bokeh.Range1d(-0.5, 20.5);
// make the plot
var plot = new Bokeh.Plot({
title: "BokehJS Plot",
x_range: xdr,
y_range: ydr,
plot_width: 400,
plot_height: 400,
background_fill_color: "#F2F2F7"
});
// add axes to the plot
var xaxis = new Bokeh.LinearAxis({
axis_line_color: null
});
var yaxis = new Bokeh.LinearAxis({
axis_line_color: null
});
plot.add_layout(xaxis, "below");
plot.add_layout(yaxis, "left");
// add grids to the plot
var xgrid = new Bokeh.Grid({
ticker: xaxis.ticker,
dimension: 0
});
var ygrid = new Bokeh.Grid({
ticker: yaxis.ticker,
dimension: 1
});
plot.add_layout(xgrid);
plot.add_layout(ygrid);
// add a Line glyph
var line = new Bokeh.Line({
x: {
field: "x"
},
y: {
field: "y"
},
line_color: "#666699",
line_width: 2
});
plot.add_glyph(line, source);
// now add the tools
plot.add_tools(new Bokeh.BoxZoomTool());
plot.add_tools(new Bokeh.ResetTool());
plot.toolbar_location = "right";
// add the plot to a document and display it
var doc = new Bokeh.Document();
doc.add_root(plot);
var div = document.getElementById("plot");
Bokeh.embed.add_document_standalone(doc, div);
.mybokehplot {
position: relative;
width: 100%;
height: 100%;
border: 1px dashed #ccc;
}
<script type="text/javascript" src="https://cdn.bokeh.org/bokeh/release/bokeh-0.12.0.min.js"></script>
<script type="text/javascript" src="https://cdn.bokeh.org/bokeh/release/bokeh-widgets-0.12.0.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.bokeh.org/bokeh/release/bokeh-0.12.0.min.css">
<link rel="stylesheet" type="text/css" href="https://cdn.bokeh.org/bokeh/release/bokeh-widgets-0.12.0.min.css">
<div id="plot" class="mybokehplot bk-root"></div>
P.S. I found that the edition of bokeh's css files and js files must be same, or you would get lots of bugs.

How do I insert a node in a graph in sigmajs while inside angularjs

Note: I just vastly simplified the program and have left it with the bare essentials ...
So I am trying to add graphs within a sigma.js graph. First, let me post the javascript (sigmaAngualr.js) ...
app = angular.module('sigmaAngular', []);
app.controller('NetworkDataCtrl', function($scope){
var i, s;
$scope.newName = null;
$scope.s = null;
$scope.N = 3;
$scope.newNode = function (id, label){
return {id: id,
label: label,
x: Math.random(),
y: Math.random(),
size: Math.random()+0.2,
color:'#333'}
};
$scope.addNodeGraph = function(id, label){
$scope.s.graph.addNode($scope.newNode(id, label));
console.log(id+'-'+label);
};
$scope.tempNodes = [];
for( i=0; i<$scope.N; i++ )
$scope.tempNodes.push($scope.newNode('id'+i, 'Node'+i));
$scope.s = new sigma({graph:{nodes:$scope.tempNodes, edges:[]}})
});
app.directive('showGraph', function(){
// Create a link function
function linkFunction(scope, element, attrs){
scope.s.addRenderer({container: element[0]})
};
return {
scope: false,
link: linkFunction
}
});
And here is the HTML ...
<!DOCTYPE html>
<html>
<head>
<title>Using AngularJS</title>
<script type="text/javascript" src='lib/sigma/sigma.min.js'></script>
<script type="text/javascript" src='lib/angular/angular.min.js'></script>
<script type="text/javascript" src='lib/sigmaAngular.js'></script>
<link rel="stylesheet" type="text/css" href="main.css">
</head>
<body ng-app='sigmaAngular'>
<div>
<div ng-controller='NetworkDataCtrl'>
<input type='text' ng-model='newName' />
<button ng-click='addNodeGraph(newName,newName)'> Add Node </button>
<hr>
<div show-graph id='graph-container' s='s' tempNodes='tempNodes'>
</div>
<hr>
</div>
</div>
</body>
</html>
Of course, I am unable to add a node to the graph.
I had also tried another option of creating an entire graph when I add a node. That doesnt work either. (This is no longer true)
Let me try to explain. Now,
When I refresh the browser, I do not see a graph.
When I resize the browser window The graph suddenly appears.
When I type a random name and hit the Add Node button, the graph doesnt change.
When I resize the browser window, the graph changes to reveal the new node.
So in summary, I have to resize the browser window to see any changes in the graph.
Just a side note: The css is below:
#graph-container {
position: relative;
width: 200px;
height: 200px;
border: 1px solid indianred;
}
I feel now that I am really close to solving the problem. Just a tiny bit off somewhere ...
Any help will be greatly appreciated!!!

Canvas Clear in Paper.js

Does anyone know the best way to clear a canvas using paper.js
I tried the regular canvas clearing methods but they do not seem to work with paper.js
Html
<canvas id="myCanvas" style="background:url(images/graphpaper.jpg); background-repeat:no-repeat" height="400px" width="400px;"></canvas>
<button class="btn btn-default button" id="clearcanvas" onClick="clearcanvas();" type="button">Clear</button>
Javascript/Paperscript
<script type="text/paperscript" canvas="myCanvas">
// Create a Paper.js Path to draw a line into it:
tool.minDistance = 5;
var path;
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
function onMouseDown(event) {
// Create a new path and give it a stroke color:
path = new Path();
path.strokeColor = 'red';
path.strokeWidth= 3;
path.opacity="0.4";
// Add a segment to the path where
// you clicked:
path.add(event.point, event.point);
}
function onMouseDrag(event) {
// Every drag event, add a segment
// to the path at the position of the mouse:
path.add(event.point, event.point);
}
</script>
Regular clearing does not work because paper.js maintains a scene graph and takes care of drawing it for you. If you want to clear all items that you have created in a project, you need to delete the actual items:
project.activeLayer.removeChildren(); works as long as all your items are inside one layer. There is also project.clear() which removes everything, including the layer.
In case someone comes looking for an answer with little experience in Javascript, I made a simple example :
1) As Jürg Lehni mentioned project.activeLayer.removeChildren(); can be used to remove all items inside active layer.
2) To reflect the cleaning you have to call paper.view.draw();.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Circles</title>
<link rel="stylesheet" href="style.css">
<script type="text/javascript" src="paper-full.js"></script>
<script type="text/paperscript" canvas="canvas">
function onMouseUp(event) {
var circle = new Path.Circle({
center: event.middlePoint,
radius: event.delta.length / 2
});
circle.strokeColor = 'black';
circle.fillColor = 'white';
}
</script>
<script type="text/javascript">
paper.install(window);
window.onload = function () {
paper.setup('canvas');
document.getElementById('reset').onclick = function(){
paper.project.activeLayer.removeChildren();
paper.view.draw();
}
};
</script>
</head>
<body>
<canvas style="background-color: #eeeeed" id="canvas" resize></canvas>
<input id="reset" type="button" value="Reset"/>
</body>
</html>
CSS :
html,
body {
margin: 0;
overflow: hidden;
height: 100%;
}
/* Scale canvas with resize attribute to full size */
canvas[resize] {
width: 58%;
height: 100%;
}
you can use project.activeLayer.removeChildren(); for clear entire layer,
or you can add your new paths to group and remove all childrens in group
var myPath;
var group = new Group();
function onMouseDown(event) {
myPath = new Path();
}
function onMouseDrag(event) {
myPath.add(event.point);
}
function onMouseUp(event) {
var myCircle = new Path.Circle({
center: event.point,
radius: 10
});
myCircle.strokeColor = 'black';
myCircle.fillColor = 'red';
group.addChild(myCircle);
}
// connect your undo function and button
document.getElementById('clearbutton').onclick = btnClear;
function btnClear(){
group.removeChildren();
}
c.width = c.width; ctx.clearRect(0,0,c.width,c.height); should be a good catchall if you've not tried it.
Beware however - setting canvas width will reset the canvas state including any applied transforms.
A quick google took me to https://groups.google.com/forum/#!topic/paperjs/orL7YwBdZq4 which specifies another (more paper.js specific) solution:
project.activeLayer.removeChildren();

FabricJS - add line to canvas and control only it's length

I am using FabricJS to develop a simple floor plan editor. When adding a Line (that should be a wall) to the canvas, I want the ability to control only the length of the line, not it's width-height.
I have tried setting lockScalingY: true but the problem is that when adding a line the control handles are so close to each other that I can't interact only with the horizontal control handles... the corner handles actually block the horizontal handles...
How can this be done?
Fine control of adjoining FabricJS lines
The way graphics programs like photoshop deal with this common problem is to let the user position lines near the desired intersection and then use the arrowkeys to "nudge" the line into place pixel one at a time.
The code below illustrates a rough solution that does the same thing for FabricJS lines:
User selects a line.
Turn off the control handles and borders.
Let the user "nudge" the line into perfect alignment (here the line length is increased).
Turn the the control handles and borders back On.
This is just "proof of concept" code. In your production app:
You'll probably want to use arrowkeys instead of buttons to "nudge".
I made nudging go 10px at a time--you might do this 1px at a time.
And when the user starts nudging, you'll automatically turn off the handles and borders for them.
Here is code and a Fiddle: http://jsfiddle.net/m1erickson/dd742/
<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" media="all" href="css/reset.css" /> <!-- reset css -->
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<script type="text/javascript" src="fabric.min.js"></script>
<style>
body{ background-color: ivory; padding:30px; }
canvas{border: 1px solid red; }
</style>
<script>
$(function(){
var canvas = new fabric.Canvas('canvas');
var selectedLine;
var line1=newLine(50,100,150,100,"red");
var line2=newLine(160,50,160,150,"green");
canvas.add(line1,line2);
function newLine(x1,y1,x2,y2,color){
var line=new fabric.Line(
[x1,y1,x2,y2],
{fill:color,strokeWidth:15,selectable:true}
);
return(line);
};
$("#hOff").click(function(){
selectedLine.hasBorders=false;
selectedLine.hasControls=false;
canvas.renderAll();
});
$("#hOn").click(function(){
selectedLine.hasBorders=false;
selectedLine.hasControls=true;
canvas.renderAll();
});
$("#shorter").click(function(){
changeLineLength(selectedLine,-10);
canvas.renderAll();
});
$("#longer").click(function(){
changeLineLength(selectedLine,10);
canvas.renderAll();
});
function changeLineLength(line,adjustment){
if(!selectedLine){return;}
if(line.get("y1")==line.get("y2")){ // line is horizontal
line.set("x2",line.get("x2")+adjustment);
}else
if(line.get("x1")==line.get("x2")){ // line is vertical
line.set("y2",line.get("y2")+adjustment);
}else{ // line is diagonal
line.set("x2",line.get("x2")+adjustment);
line.set("y2",line.get("y2")+adjustment);
}
}
canvas.observe('object:selected', function(eventTarget) {
var event=eventTarget.e;
var target=eventTarget.target;
selectedLine=target;
});
}); // end $(function(){});
</script>
</head>
<body>
<p>Select a line,</p><br/>
<p>Turn handles Off</p><br/>
<p>Make lines intersect by pressing longer/shorter</p><br/>
<canvas id="canvas" width="600" height="200"></canvas>
<button id="hOff">Handles Off</button>
<button id="shorter">Shorter</button>
<button id="longer">Longer</button><br/>
<button id="hOn">Handles On</button>
</body>
</html>
May be helps somebody.
Add handler to event
'object:selected': _objSelected
Then at handler set unneeded control to false.
function _objSelected(e)
{
if(e.target.objectType == 'line')
{
var cv = e.target._controlsVisibility;
// mt - middle top, tl - top left and etc.
cv.mt = cv.mb = cv.tl = cv.bl = cv.tr = cv.br = false;
}
}
Also I added objectType (custom property) and padding (for beauty) to new object Line
var obj = new fabric.Line([50, 50, 150, 50], { padding: 10, objectType: 'line' });

Categories

Resources