I'm using the Fabricjs for creating a drawing tool. I'm using version 2.2.
Using the canvas methods selection:created and selection:updated. I'm able to remove the object like circle and rectangle bu to a line object.
Here is my JSFiddle link for the code demo.
Draw a line and try to remove it with an eraser.
var canvas = new fabric.Canvas('c', {
selection: false
});
canvas.perPixelTargetFind = true;
canvas.targetFindTolerance = 4;
var circle = new fabric.Circle({
radius: 20,
fill: 'green',
left: 100,
top: 100
});
var triangle = new fabric.Triangle({
width: 20,
height: 30,
fill: 'blue',
left: 50,
top: 50
});
canvas.add(circle, triangle);
$('#clear').on('change', function() {
if ($(this).is(':checked')) {
drawingOperation('clear');
}
});
$('#line').on('change', function() {
if ($(this).is(':checked')) {
drawingOperation('line');
}
});
$('#eraser').on('change', function() {
if ($(this).is(':checked')) {
drawingOperation('erase');
}
});
var drawingPointer = {
status: false,
previousObj: false
};
function drawingOperation(operation) {
if (drawingPointer.status == 'freedraw') {
canvas.isDrawingMode = false;
}
if (operation == 'line') {
console.log('Called to draw line');
drawingPointer.status = 'line';
canvas.defaultCursor = 'url("https://image.ibb.co/dCkbWc/icon_straight.png") 0 16 ,auto';
canvas.hoverCursor = 'auto';
return;
}
if (operation == 'erase') {
drawingPointer.status = 'erase';
canvas.defaultCursor = canvas.hoverCursor = 'url("https://image.ibb.co/h2bGWc/icon_eraser.png") 2 12 ,auto';
return;
}
if (operation == 'clear') {
drawingPointer.status = false;
drawingPointer.previousObj = false;
canvas.defaultCursor = 'auto';
canvas.hoverCursor = 'auto';
}
}
function handlerObjectSelection(o) {
console.log(o.target);
if (drawingPointer.status == 'erase') {
console.log('Called from Erase Section');
canvas.remove(o.target);
}
}
function handleMouseMovement(o) {
if (drawingPointer.status == 'line' && drawingPointer.strightLine) {
var pointer = canvas.getPointer(o.e);
drawingPointer.down = false;
drawingPointer.strightLine.set({
'x2': pointer.x,
'y2': pointer.y
});
canvas.renderAll();
}
}
function handleMouseDown(o) {
if (drawingPointer.status == 'line') {
console.log('MouseDown from Line');
var pointer = canvas.getPointer(o.e);
drawingPointer.down = true;
drawingPointer.strightLine = new fabric.Line([pointer.x, pointer.y, pointer.x, pointer.y], {
fill: 'red',
stroke: 'red',
strokeWidth: 3,
originX: 'center',
originY: 'center'
});
canvas.add(drawingPointer.strightLine);
canvas.renderAll();
}
}
function handleMouseUp(o) {
if (drawingPointer.status == 'line') {
console.log('MouseUp from Line');
var pointer = canvas.getPointer(o.e);
drawingPointer.down = false;
drawingPointer.strightLine.set({
'x2': pointer.x,
'y2': pointer.y
});
canvas.renderAll();
drawingPointer.strightLine = null;
}
}
canvas.on('selection:created', handlerObjectSelection);
canvas.on('selection:updated', handlerObjectSelection);
canvas.on('mouse:move', handleMouseMovement);
canvas.on('mouse:down', handleMouseDown);
canvas.on('mouse:up', handleMouseUp);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://rawgithub.com/kangax/fabric.js/master/dist/fabric.js"></script>
<canvas id="c" width="300" height="300" style="border: 1px solid;margin: 10px;"></canvas>
<div class="row">
<div class="col-xs-10 col-xs-offset-2">
<h3>Drawing Function</h3>
<div class="btn-group" data-toggle="buttons">
<label class="btn btn-default active">
<input type="radio" name="options" id="clear" autocomplete="off" checked>
<img src="https://image.ibb.co/iedVrc/icon_cursor.png" height="16" width="16" />
</label>
<label class="btn btn-default">
<input type="radio" name="options" id="line" autocomplete="off">
<img src="https://image.ibb.co/dCkbWc/icon_straight.png" height="16" width="16" />
</label>
<label class="btn btn-default">
<input type="radio" name="options" id="eraser" autocomplete="off">
<img src="https://image.ibb.co/h2bGWc/icon_eraser.png" height="16" width="16" />
</label>
</div>
</div>
</div>
drawingPointer.strightLine.setCoords();
You need to use setCoords after drawing complete.
var canvas = new fabric.Canvas('c', {
selection: false
});
canvas.perPixelTargetFind = true;
canvas.targetFindTolerance = 4;
var circle = new fabric.Circle({
radius: 20,
fill: 'green',
left: 100,
top: 100
});
var triangle = new fabric.Triangle({
width: 20,
height: 30,
fill: 'blue',
left: 50,
top: 50
});
canvas.add(circle, triangle);
$('#clear').on('change', function() {
if ($(this).is(':checked')) {
drawingOperation('clear');
}
});
$('#line').on('change', function() {
if ($(this).is(':checked')) {
drawingOperation('line');
}
});
$('#eraser').on('change', function() {
if ($(this).is(':checked')) {
drawingOperation('erase');
}
});
var drawingPointer = {
status: false,
previousObj: false
};
function drawingOperation(operation) {
if (drawingPointer.status == 'freedraw') {
canvas.isDrawingMode = false;
}
if (operation == 'line') {
console.log('Called to draw line');
drawingPointer.status = 'line';
canvas.defaultCursor = 'url("https://image.ibb.co/dCkbWc/icon_straight.png") 0 16 ,auto';
canvas.hoverCursor = 'auto';
return;
}
if (operation == 'erase') {
drawingPointer.status = 'erase';
canvas.defaultCursor = canvas.hoverCursor = 'url("https://image.ibb.co/h2bGWc/icon_eraser.png") 2 12 ,auto';
return;
}
if (operation == 'clear') {
drawingPointer.status = false;
drawingPointer.previousObj = false;
canvas.defaultCursor = 'auto';
canvas.hoverCursor = 'auto';
}
}
function handlerObjectSelection(o) {
console.log(o.target);
if (drawingPointer.status == 'erase') {
console.log('Called from Erase Section');
canvas.remove(o.target);
}
}
function handleMouseMovement(o) {
if (drawingPointer.status == 'line' && drawingPointer.strightLine) {
var pointer = canvas.getPointer(o.e);
drawingPointer.down = false;
drawingPointer.strightLine.set({
'x2': pointer.x,
'y2': pointer.y
});
canvas.renderAll();
}
}
function handleMouseDown(o) {
if (drawingPointer.status == 'line') {
console.log('MouseDown from Line');
var pointer = canvas.getPointer(o.e);
drawingPointer.down = true;
drawingPointer.strightLine = new fabric.Line([pointer.x, pointer.y, pointer.x, pointer.y], {
fill: 'red',
stroke: 'red',
strokeWidth: 3,
originX: 'center',
originY: 'center'
});
canvas.add(drawingPointer.strightLine);
canvas.renderAll();
}
}
function handleMouseUp(o) {
if (drawingPointer.status == 'line') {
console.log('MouseUp from Line');
var pointer = canvas.getPointer(o.e);
drawingPointer.down = false;
drawingPointer.strightLine.set({
'x2': pointer.x,
'y2': pointer.y
});
drawingPointer.strightLine.setCoords();
canvas.renderAll();
drawingPointer.strightLine = null;
}
}
canvas.on('selection:created', handlerObjectSelection);
canvas.on('selection:updated', handlerObjectSelection);
canvas.on('mouse:move', handleMouseMovement);
canvas.on('mouse:down', handleMouseDown);
canvas.on('mouse:up', handleMouseUp);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://rawgithub.com/kangax/fabric.js/master/dist/fabric.js"></script>
<canvas id="c" width="300" height="300" style="border: 1px solid;margin: 10px;"></canvas>
<div class="row">
<div class="col-xs-10 col-xs-offset-2">
<h3>Drawing Function</h3>
<div class="btn-group" data-toggle="buttons">
<label class="btn btn-default active">
<input type="radio" name="options" id="clear" autocomplete="off" checked>
<img src="https://image.ibb.co/iedVrc/icon_cursor.png" height="16" width="16" />
</label>
<label class="btn btn-default">
<input type="radio" name="options" id="line" autocomplete="off">
<img src="https://image.ibb.co/dCkbWc/icon_straight.png" height="16" width="16" />
</label>
<label class="btn btn-default">
<input type="radio" name="options" id="eraser" autocomplete="off">
<img src="https://image.ibb.co/h2bGWc/icon_eraser.png" height="16" width="16" />
</label>
</div>
</div>
</div>
Related
I've the below code, which is drawing a rec in a svg element:
.container
{
display: flex;
align-items: center;
height: 1.3em;
}
<div class="container">
<label for="from">From:</label>
<input type="number" name="from">
<label for="to">To:</label>
<input type="number" name="to">
<svg margin="0" width="200" height="1.3em">
<rect x="10" y="0" width="30" height="1.3em" stroke="black" fill="green" />
</svg>
I want to be able "prpgramatically" to:
Shift the location of the rec by changing the value of the from field
Chang the width of the rec by changing the value of the to field
const svgRect = document.querySelector('svg rect')
function xStart(XS){
svgRect.setAttribute('x',XS)
}
function rWidth(RW){
svgRect.setAttribute('width',RW)
}
.container
{
display: flex;
align-items: center;
height: 1.3em;
}
<div class="container">
<label for="from">From:</label>
<input onchange="xStart(this.value)" type="number" name="from">
<label for="to">To:</label>
<input onchange="rWidth(this.value)" type="number" name="to">
<svg margin="0" width="200" height="1.3em">
<rect x="10" y="0" width="30" height="1.3em" stroke="black" fill="green" />
</svg>
For changing width, you can add even listeners to mouse position and situations, below sample code:
let svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
svg.setAttribute("class", "octicon octicon-star");
// svg.setAttribute("viewBox", "0 0 14 16");
svg.setAttribute("version", "1.1");
svg.setAttribute("width", 240);
svg.setAttribute("height", 160);
svg.setAttribute("aria-hidden", "true");
let barThickness = 20
let orders = [100, 152];
//orders.forEach((element, index, array) => console.log('a[' + index + '] = ' + element) )
orders.forEach(function(element, index, array) {
console.log('a[' + index + '] = ' + element)
let r = document.createElementNS("http://www.w3.org/2000/svg", "rect");
r.setAttribute("x", 0);
r.setAttribute("y",(barThickness+10)*index+0);
r.setAttribute("width", element);
r.setAttribute("height", barThickness);
r.setAttribute("fill","black");
let isDrawing = false;
let x = element
let mousePosition = 0
r.addEventListener('mouseenter', e => {
e.path[0].setAttribute("fill","red")
});
r.addEventListener('mouseleave', e => {
e.path[0].setAttribute("fill","black")
if (isDrawing === true) {
isDrawing = false;
}
});
r.addEventListener('mousedown', e => {
isDrawing = true;
});
r.addEventListener('mousemove', e => {
if (isDrawing === true) {
console.log(e.offsetX)
if(e.offsetX>mousePosition) {
x++
} else if(e.offsetX < mousePosition){
x--
}
mousePosition = e.offsetX
r.setAttribute("width", x)
}
});
r.addEventListener('mouseup', e => {
if (isDrawing === true) {
isDrawing = false;
}
});
svg.appendChild(r);
document.body.appendChild(svg)
} )
var startX = 100;
var startY = 100;
function init() {
Snap("#rect").drag(dragMove, dragStart, dragEnd);
}
function dragStart(x, y, evt) {
// figure out where the circle currently is
startX = parseInt(Snap("#rect").attr("x"), 10);
startY = parseInt(Snap("#rect").attr("y"), 0);
}
function dragMove(dx, dy, x, y, evt) {
Snap("#rect").attr({
x: (startX + dx),
y: (startY + dy)
});
}
function dragEnd(evt) {
// no action required
}
.container {
display: flex;
align-items: center;
height: 1.3em;
position:relative;
}
svg {
position: absolute;
top: 0;
left:420px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/snap.svg/0.5.1/snap.svg-min.js"></script>
<body onload="init()">
<div class="container">
<label for="from">From:</label>
<input type="number" name="from">
<label for="to">To:</label>
<input type="number" name="to">
<svg margin="0" width="400" height="400">
<rect draggable="true" id='rect' x="10" y="0" width="30" height="1.3em" stroke="black" fill="green" />
</svg>
</div>
</body>
I have some rectangular shapes (they will appear when the data science toolkit buttons is clicked) and they can drag&drop to the free-space (paper). Also you can run and check easily in codepen.io.
Thing that I want to add, is remove dropped shapes by clicking close button. But I don't know how can create close button near the dropped shape and also removing that shape.
Any help would be greatly appreciated, thanks!
// Canvas where sape are dropped
var graph = new joint.dia.Graph,
paper = new joint.dia.Paper({
el: $('#paper'),
model: graph
});
// Canvas from which you take shapes
var stencilGraph = new joint.dia.Graph,
stencilPaper = new joint.dia.Paper({
el: $('#stencil'),
model: stencilGraph,
interactive: false
});
var r1a = new joint.shapes.basic.Rect({
position: {
x: 29,
y: 10
},
size: {
width: 100,
height: 40
},
attrs: {
text: {
text: 'Rect1a'
}
}
});
var r1b = new joint.shapes.basic.Rect({
position: {
x: 29,
y: 60
},
size: {
width: 100,
height: 40
},
attrs: {
text: {
text: 'Rect1b'
}
}
});
var r2a = new joint.shapes.basic.Rect({
position: {
x: 29,
y: 10
},
size: {
width: 100,
height: 40
},
attrs: {
text: {
text: 'Rect2a'
}
}
});
var r2b = new joint.shapes.basic.Rect({
position: {
x: 29,
y: 60
},
size: {
width: 100,
height: 40
},
attrs: {
text: {
text: 'Rect2b'
}
}
});
var r3a = new joint.shapes.basic.Rect({
position: {
x: 29,
y: 10
},
size: {
width: 100,
height: 40
},
attrs: {
text: {
text: 'Rect3a'
}
}
});
var r3b = new joint.shapes.basic.Rect({
position: {
x: 29,
y: 60
},
size: {
width: 100,
height: 40
},
attrs: {
text: {
text: 'Rect3b'
}
}
});
var r4a = new joint.shapes.basic.Rect({
position: {
x: 29,
y: 10
},
size: {
width: 100,
height: 40
},
attrs: {
text: {
text: 'Rect4a'
}
}
});
var r4b = new joint.shapes.basic.Rect({
position: {
x: 29,
y: 60
},
size: {
width: 100,
height: 40
},
attrs: {
text: {
text: 'Rect4b'
}
}
});
var statistic = document.getElementById("statistic-button");
var clustering = document.getElementById("clustering-button");
var classification = document.getElementById("classification-button");
var regression = document.getElementById("regression-button");
statistic.onclick = function(){
r1a.addTo(stencilGraph);
r1b.addTo(stencilGraph);
r2a.remove(stencilGraph);
r2b.remove(stencilGraph);
r3a.remove(stencilGraph);
r3b.remove(stencilGraph);
r4a.remove(stencilGraph);
r4b.remove(stencilGraph);
};
clustering.onclick = function(){
r1a.remove(stencilGraph);
r1b.remove(stencilGraph);
r2a.addTo(stencilGraph);
r2b.addTo(stencilGraph);
r3a.remove(stencilGraph);
r3b.remove(stencilGraph);
r4a.remove(stencilGraph);
r4b.remove(stencilGraph);
};
classification.onclick = function(){
r1a.remove(stencilGraph);
r1b.remove(stencilGraph);
r2a.remove(stencilGraph);
r2b.remove(stencilGraph);
r3a.addTo(stencilGraph);
r3b.addTo(stencilGraph);
r4a.remove(stencilGraph);
r4b.remove(stencilGraph);
};
regression.onclick = function(){
r1a.remove(stencilGraph);
r1b.remove(stencilGraph);
r2a.remove(stencilGraph);
r2b.remove(stencilGraph);
r3a.remove(stencilGraph);
r3b.remove(stencilGraph);
r4a.addTo(stencilGraph);
r4b.addTo(stencilGraph);
};
stencilPaper.on('cell:pointerdown', function(cellView, e, x, y) {
$('body').append('<div id="flyPaper" style="position:fixed;z-index:100;opacity:.7;pointer-event:none;"></div>');
var flyGraph = new joint.dia.Graph,
flyPaper = new joint.dia.Paper({
el: $('#flyPaper'),
model: flyGraph,
interactive: false
}),
flyShape = cellView.model.clone(),
pos = cellView.model.position(),
offset = {
x: x - pos.x,
y: y - pos.y
};
flyShape.position(0, 0);
flyGraph.addCell(flyShape);
$("#flyPaper").offset({
left: e.pageX - offset.x,
top: e.pageY - offset.y
});
$('body').on('mousemove.fly', function(e) {
$("#flyPaper").offset({
left: e.pageX - offset.x,
top: e.pageY - offset.y
});
});
$('body').on('mouseup.fly', function(e) {
var x = e.pageX,
y = e.pageY,
target = paper.$el.offset();
// Dropped over paper ?
if (x > target.left && x < target.left + paper.$el.width() && y > target.top && y < target.top + paper.$el.height()) {
var s = flyShape.clone();
s.position(x - target.left - offset.x, y - target.top - offset.y);
graph.addCell(s);
}
$('body').off('mousemove.fly').off('mouseup.fly');
flyShape.remove();
$('#flyPaper').remove();
});
});
.data-science-toolkit{
height: 300px;
border: 5px double #005580;
}
.data-science-toolkit .before-drop-display-none{
display: none;
}
.ds-tool-space{
border: 5px double #005580;
}
.free-space{
border: 5px solid #005580;
height: auto;
}
.doitcenter{
text-align: center;
}
#paper {
height: auto;
background-color: #f2e6e6;
}
#stencil {
background-color: darkcyan;
}
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
<div class="container">
<div class="row mt-4">
<div class="col-2">
<div class="data-science-toolkit mb-2">
<div class="nav-logo">
<h5 class="doitcenter" style="text-shadow: 0.5px 0.5px 1px gray;">Toolkit</h5>
</div>
<hr>
<div class="dropdown doitcenter mb-1">
<button id="statistic-button" class="btn btn-secondary dropdown-toggle" type="button" data-toggle="dropdown" style="min-width: 136px;">Statistics
<span class="caret"></span></button>
</div>
<div class="dropdown doitcenter mb-1">
<button id="clustering-button" class="btn btn-secondary dropdown-toggle" type="button" data-toggle="dropdown" style="min-width: 136px;">Clustering
<span class="caret"></span></button>
</div>
<div class="dropdown doitcenter mb-1">
<button id="classification-button" class="btn btn-secondary dropdown-toggle" type="button" data-toggle="dropdown" style="min-width: 136px;">Classification
<span class="caret"></span></button>
</div>
<div class="dropdown doitcenter mb-1">
<button id="regression-button" class="btn btn-secondary dropdown-toggle" type="button" data-toggle="dropdown" style="min-width: 136px;">Regression
<span class="caret"></span></button>
</div>
</div>
<div class="ds-tool-space mb-2">
<div id="stencil" style="height: 250px;"></div>
</div>
</div>
<div class="col-10">
<div class="free-space">
<div id="paper" style=""></div>
</div>
</div>
</div>
</div>
You can use the built-in elementTools.remove, and bind with an event like the following:
paper.on('element:mouseenter', (elementView) => {
elementView.addTools(
new joint.dia.ToolsView({
tools: [
new joint.elementTools.Remove({
useModelGeometry: true,
y: '0%',
x: '100%',
}),
],
})
);
});
paper.on('element:mouseleave', (elementView) => {
elementView.removeTools();
});
Note that you might need to change the position according to your element shape.
This is also included in the official demo
I want to when I click on every div
It's the first to be in front of everyone and the others div are moved.for example div4 is in front of everyone.when I click on div1 I want to put div1 in place of div4 and Then again, on each one that I click on, it's the front but My code does not work properly after several times and does not display one of the shapes.
$(".haml-category").click(function() {
var top = $(this).data("top");
var zindex = $(this).data("zindex");
var temp = $(".haml-category-container").find(".selected");
$(".haml-category-container").find(".selected").removeClass("selected").data("zindex", zindex).data("top", top).css({
"z-index": zindex,
"top": top
});
$(this).data("zindex", temp.data("zindex")).data("top", temp.data("top")).addClass("selected");
});
.haml-category-container {
position: relative;
background-color:#ccc;
}
.haml-category {
position: absolute;
width: 100%;
height: 500px;
top: 0;
right: 0;
border: 1px solid black;
transition: top 1s;
}
.sec-saheb-bar {
z-index: 0;
}
.sec-ranande {
z-index: 1;
top: 40px;
}
.sec-barbar {
z-index: 2;
top: 85px;
}
.sec-bazaryab {
z-index: 3;
top: 130px;
}
.selected {
z-index: 3;
top: 130px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="haml-category-container">
<div class="haml-category sec-saheb-bar" id="sec-saheb-bar" data-zindex="0" data-top="0">
<h6>div1</h6>
<p> content div1</p>
</div>
<div class="haml-category sec-ranande" id="sec-ranande" data-zindex="1" data-top="40">
<h6>div2</h6>
<p> content div2</p>
</div>
<div class="haml-category sec-barbar" id="sec-barbar" data-zindex="2" data-top="85">
<h6>div3</h6>
<p> content div3</p>
</div>
<div class="haml-category sec-bazaryab selected" id="sec-bazaryab" data-zindex="3" data-top="130">
<h6>div4</h6>
<p> content div4</p>
</div>
</div>
The variable temp may has be changed,modified as below.
$(".haml-category").click(function() {
var top = $(this).data("top");
var zindex = $(this).data("zindex");
var temp = $(".haml-category-container").find(".selected");
var top2 = temp.data("top");
var zindex2 = temp.data("zindex");
$(this).data("zindex", zindex2).data("top", top2).css({
"z-index": zindex2,
"top": top2
}).addClass("selected");
temp.removeClass("selected").data("zindex", zindex).data("top", top);
temp.css({
"z-index": zindex,
"top": top
});
});
.haml-category-container {
position: relative;
}
.haml-category {
position: absolute;
width: 100%;
height: 500px;
top: 0;
right: 0;
border: 1px solid black;
transition: top 1s;
}
.sec-saheb-bar {
z-index: 0;
}
.sec-ranande {
z-index: 1;
top: 40px;
}
.sec-barbar {
z-index: 2;
top: 85px;
}
.sec-bazaryab {
z-index: 3;
top: 130px;
}
.selected {
z-index: 3;
top: 130px;
}
#sec-saheb-bar{
background-color:#0077CC;
}
#sec-ranande{
background-color:#1F1D1C;
}
#sec-barbar{
background-color:#FECD45;
}
#sec-bazaryab{
background-color:#1AA160;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="haml-category-container">
<div class="haml-category sec-saheb-bar" id="sec-saheb-bar" data-zindex="0" data-top="0">
<h6>div1</h6>
</div>
<div class="haml-category sec-ranande" id="sec-ranande" data-zindex="1" data-top="40">
<h6>div2</h6>
</div>
<div class="haml-category sec-barbar" id="sec-barbar" data-zindex="2" data-top="85">
<h6>div3</h6>
</div>
<div class="haml-category sec-bazaryab selected" id="sec-bazaryab" data-zindex="3" data-top="130">
<h6>div4</h6>
</div>
</div>
I did this FRANKENSTEIN's monster in 2010 for testing purpose.how you can see i put everywhere z-index:9 watch the demo try to drag every element over other element.with some modifications you can convert it in jquery
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"><HTML>
<HEAD>
<TITLE></TITLE>
<style></style>
<meta charset="UTF-8">
<SCRIPT LANGUAGE="JavaScript">
<!--
// function returns array of box bounds
box_offset = function (box) {
var scrollPosition = getScrollPosition(), // get scroll position
oLeft = 0,// - scrollPosition[0], // define offset left (take care of horizontal scroll position)
oTop = 0,// - scrollPosition[1], // define offset top (take care od vertical scroll position)
box_old = box; // remember box object
// loop to the root element and return box offset (top, right, bottom, left)
do {
oLeft += box.offsetLeft;
oTop += box.offsetTop;
box = box.offsetParent;
}
while (box);
// return box offset array
// top right, bottom left
//return [ oTop, oLeft + box_old.offsetWidth, oTop + box_old.offsetHeight, oLeft ];
// top right, bottom left
return [
oLeft,
oLeft + box_old.offsetWidth,
oTop,
oTop + box_old.offsetHeight
];
};
// function returns scroll positions in array
getScrollPosition = function () {
// define local scroll position variables
var scrollX, scrollY;
// Netscape compliant
if (typeof(window.pageYOffset) === 'number') {
scrollX = window.pageXOffset;
scrollY = window.pageYOffset;
}
// DOM compliant
else if (document.body && (document.body.scrollLeft || document.body.scrollTop)) {
scrollX = document.body.scrollLeft;
scrollY = document.body.scrollTop;
}
// IE6 standards compliant mode
else if (document.documentElement && (document.documentElement.scrollLeft || document.documentElement.scrollTop)) {
scrollX = document.documentElement.scrollLeft;
scrollY = document.documentElement.scrollTop;
}
// needed for IE6 (when vertical scroll bar was on the top)
else {
scrollX = scrollY = 0;
}
// return scroll positions
return [ scrollX, scrollY ];
};
//-->
</SCRIPT>
<SCRIPT LANGUAGE="JavaScript">
<!--
swdrag = false;
var picwidth;
var picheight;
var picxpos;
var picypos;
var Drag = {
obj : null,
init : function(o, resizer, oRoot, minX, maxX, minY, maxY, bSwapHorzRef, bSwapVertRef, fXMapper, fYMapper)
{
o.onmousedown = Drag.start;
o.resizer = resizer;
o.root = o;
if ( isNaN(parseInt(o.root.style.left ))) o.root.style.left = "0px";
if ( isNaN(parseInt(o.root.style.top ))) o.root.style.top = "0px";
o.root.onDragStart = new Function();
o.root.onDragEnd = new Function();
o.root.onDrag = new Function();
calculate();
},
start : function(e)
{
var o = Drag.obj = this;
e = Drag.fixE(e);
var y = parseInt( o.root.style.top );
var x = parseInt( o.root.style.left );
o.root.onDragStart(x, y);
o.lastMouseX = e.clientX;
o.lastMouseY = e.clientY;
document.onmousemove = Drag.drag;
document.onmouseup = Drag.end;
calculate();
return false;
},
drag : function(e)
{
e = Drag.fixE(e);
var o = Drag.obj;
var nx, ny;
var ey = e.clientY;
var ex = e.clientX;
var changeX = (ex - o.lastMouseX);
var changeY = (ey - o.lastMouseY);
nx = parseInt(o.root.style.left ) + changeX;
ny = parseInt(o.root.style.top ) + changeY;
if (o.xMapper) nx = o.xMapper(y)
else if (o.yMapper) ny = o.yMapper(x)
Drag.obj.root.style["left"] = nx + "px";
Drag.obj.root.style["top"] = ny + "px";
Drag.obj.lastMouseX = ex;
Drag.obj.lastMouseY = ey;
Drag.obj.root.onDrag(nx, ny);
Drag.xmouse = Drag.obj.lastMouseX;
Drag.ymouse = Drag.obj.lastMouseY;
Drag.xmouse = e.clientX;
Drag.ymouse = e.clientY;
calculate();
calculate2();
swdrag=true;
return false;
},
end : function()
{
document.onmousemove = null;
document.onmouseup = null;
Drag.obj.root.onDragEnd( parseInt(Drag.obj.root.style["right"]),
parseInt(Drag.obj.root.style["bottom"]));
Drag.obj = null;
calculate();
if (swdrag){
swdrag = false;
}
},
fixE : function(e)
{
if (typeof e == 'undefined') e = window.event;
if (typeof e.layerX == 'undefined') e.layerX = e.offsetX;
if (typeof e.layerY == 'undefined') e.layerY = e.offsetY;
Drag.xmouse=e.clientX;
Drag.ymouse=e.clientY;
calculate();
return e;
},
xmouse:0,
ymouse:0
};
function start(){
IMAGE.style.left=x_pic_ini;
IMAGE.style.top=y_pic_ini;
//calculate();
}
function calculate(){
widthIMAGE=parseInt(IMAGE.clientWidth);
picwidth=widthIMAGE;
heightIMAGE=parseInt(IMAGE.clientHeight);
picheight=heightIMAGE;
xposex=parseInt(IMAGE.style.left);
yposex=parseInt(IMAGE.style.top);
picxpos=xposex;
picypos=yposex;
IMAGE.left=picxpos;
IMAGE.top=picypos;
}
function calculate2(){
oobj=document.f1;
oobj.xpic.value=picxpos;
oobj.ypic.value=picypos;
//fiecare celula | every box
if(lastbox!=null)
{
//lastbox.style.background='white';
//lastbox.style.color='black';
}
mxrows=document.getElementById("tb1").rows.length;
for(i=0;i<mxrows;i++){
mxcols=document.getElementById("tb1").rows[i].cells.length;
for(u=0;u<3;u++){
//a("i"+i+u+"=");
theboxobj=eval(document.getElementById("i"+i+u));
xyb=box_offset(theboxobj);
oox=picxpos;
ooy=picypos+(heightIMAGE-theboxobj.clientHeight)/2;
if ((oox>xyb[0])&&(oox<xyb[1])&&(ooy>xyb[2])&&(ooy<xyb[3]))
{
a('i('+i+' '+u+')');
theboxobj.style.background='red';
theboxobj.style.color='yellow';
lastbox=theboxobj;
if(!swdrag){
break;
// imobj=document.getElementById("image");
//document.write(obj2(obj,'obj'));
// oldobj=imobj.outerHTML;
// imobj=new Object();
// lastbox.appendChild(imobj);
lastbox.parentNode.removeChild(lastbox);
//imobj=new Object();
lastbox.parentNode.appendChild(imobj);
lastbox.parentNode.outerHTML='<td>xx</td>';
// imobj.parentNode.removeChild(imobj);
// lastbox.innerHTML=oldobj;
}
//alert(oldobj);
break;
}
}
}
}
//-->
</SCRIPT>
<SCRIPT LANGUAGE="JavaScript">
<!--
//---------------obj 2 --------------------------------
function obj2(obj, obj_name) {
var result = "";
for (var i in obj)
result += obj_name + "." + i + " = " + obj[i] +'-'+typeof obj[i]+ "\n<br>\n";
return result
}
function obj1(obj,txt){//obj(this.style)
tt=document.open('about:blank','here','');
tt.document.write(obj2(obj,txt));
}
//-----------------------------------------------------
//-->
</SCRIPT>
<SCRIPT LANGUAGE="JavaScript">
<!--
ids=new Array();
ids[0]='dsdsad';
ids[1]='tre1';
ids[2]='image';
ids[3]='image2';
ids[4]='newd';
ids[5]='txt';
function overb(obj){
color='#FF0000';
width='3px';
obj.style.borderTopWidth = width;
obj.style.borderTopColor =color;
obj.style.borderTopStyle ='solid';
obj.style.borderLeftWidth = width;
obj.style.borderLeftColor =color;
obj.style.borderLeftStyle ='solid';
obj.style.borderRightWidth = width;
obj.style.borderRightColor =color;
obj.style.borderRightStyle ='solid';
obj.style.borderBottomWidth = width;
obj.style.borderBottomColor =color;
obj.style.borderBottomStyle ='solid';
obj.style.zIndex='999';
off=box_offset(obj);
x_pic_ini=off[0];
y_pic_ini=off[2];
IMAGE=document.getElementById(obj.id);
//obj1(IMAGE,'IMAGE');
Drag.init(IMAGE);
start();
}
function outb(obj){
obj.style.borderTopWidth = '0px';
obj.style.borderLeftWidth = '0px';
obj.style.borderRightWidth = '0px';
obj.style.borderBottomWidth = '0px';
obj.style.zIndex='9'
}
//-->
</SCRIPT>
</HEAD>
<BODY onload="">
<FORM METHOD=POST ACTION="#" NAME="f1">
<div style="position:absolute;left:50;top:50;z-index:9;"
onmouseover="overb(this);doit(this)" onmouseout="outb(this);" id="canalica">xpic<INPUT TYPE="text" NAME="xpic"></div>
<div style="position:absolute;left:50;top:75;z-index:9;" onmouseover="overb(this);doit(this)" onmouseout="outb(this);" id="tre1">ypic<INPUT TYPE="text" NAME="ypic"></div>
<div style="position:absolute;left:50;top:75;z-index:9;" onmouseover="overb(this);doit(this)" onmouseout="outb(this);" id="submit">ypic<INPUT TYPE="submit" NAME="submit" value="submit"></div>
</FORM><HR>
<div style="position:absolute;left:50;top:150;z-index:9;border-top:1px solid green;" onmouseover="overb(this);doit(this)" onmouseout="outb(this);" id="image">Yes!</div>
<div style="position:absolute;left:50;top:150;z-index:9;border-top:1px solid green;" onmouseover="overb(this);doit(this);" onmouseout="outb(this);" id="image2">yep yep !</div>
<div style="position:absolute;left:50;top:150;z-index:9;border-top:1px solid green;" onmouseover="overb(this);/*document.write(obj2(this.style,'this.style'));*/doit(this)" onmouseout="outb(this);" id="newd"><TABLE border="1px" CELLSPACING="0" CELLPADDING="0" BORDER="0" WIDTH="500" id="tb1" align="left" style="margin:0;">
<TR>
<TD id="i00">11</TD>
<TD id="i01">12</TD>
<TD id="i02">13</TD>
</TR>
<TR>
<TD id="i10">21</TD>
<TD id="i11">22</TD>
<TD id="i12">23</TD>
</TR>
<TR>
<TD id="i20">31</TD>
<TD id="i21">32</TD>
<TD id="i22">33</TD>
</TR>
</TABLE></div>
<FORM METHOD=POST ACTION="#" NAME="f3">
<TEXTAREA style="position:absolute;left:50;top:175;z-index:9;" onmouseover="overb(this);doit(this)" onmouseout="outb(this);" id="txt" NAME="aa" ROWS="20" COLS="20"></TEXTAREA>
</FORM>
<BR>
<BR>
<BR>
<BR>
<BR>
<BR>
<BR>
<BR>
<BR>
<BR>
<BR>
<BR>
<BR>
<BR>
<BR>
<BR>
<BR>
<BR>
<BR>
<BR>
<BR>
<BR>
<BR>
<BR>
<BR>
<BR>
<BR>
<BR>
<BR>
<BR>
<BR>
<BR>
<BR>
<BR>
<BR>
<BR>
<BR>
<BR>
<BR>
<BR>
<BR>
<BR>
<BR>
<BR>
<BR>
<BR>
<BR>
<BR>
<BR>
<BR>
<BR>
<BR>
<BR>
<BR>
<BR>
<BR>
<BR>
<BR>
<BR>
<script type="text/javascript">
//-----------------------------------------------------
var x_pic_ini, y_pic_ini,IMAGE;
function doit(obj){
}
//------------------------------------------------------
</script>
<SCRIPT LANGUAGE="JavaScript">
<!--
/* for(i=0;i<ids.length;i++){
oo=document.getElementById(ids[i]);
//obj1(oo,'oo');
oo.style.Left=i*20;
oo.style.Top=i*20;
//alert(ids[i]);
}*/
//-->
</SCRIPT>
<SCRIPT LANGUAGE="JavaScript">
<!--
function a(val){
ww=document.f3.aa.value+val;
document.f3.aa.value=ww;
}
var div1=document.getElementById("newd");
div1.style.left=600;
div1.style.top=200;
//fiecare celula
for(i=0;i<3;i++){
for(u=0;u<3;u++){
a("i"+i+u+"=");
a(box_offset(eval(document.getElementById("i"+i+u)))+'\n');
}
}
var lastbox=null;
//doar div-ul..
//alert(box_offset(div1));
//-->
</SCRIPT>
</BODY></HTML>
My code works well but when i refresh my page, both <div> run together whereas i need only one when each radio button is clicked.
<input type="radio" name="cardType" id="one" class="css-checkbox" value="db" checked>Pie
<input type="radio" name="cardType" id="two" class="css-checkbox" value="cc">Column
$(document).ready(function () {
$(".css-checkbox").click(function () {
if ($(this).attr('id') == "one") {
$('#a').show();
$('#b').hide();
} else {
$('#a').hide();
$('#b').show();
}
});
});
<div id="a">
<div id="Revenue" style="min-width: 400px; height: 400px; margin: 0 auto"></div>
</div>
<div id="b">
<div id="Revenue2" style="min-width: 400px; height: 400px; margin: 0 auto"></div>
</div>
and here's my graph code. Revenue and revenue2 basically a graph that will alternately shown when radio button is clicked. so basically both code are the same with different data only.
<script type="text/javascript">
$(document).ready(function() {
var options = {
chart: {
renderTo: 'Revenue2',
plotBackgroundColor: null,
plotBorderWidth: null,
plotShadow: false
},
title: {
text: 'Revenue'
},
xAxis: {
type: 'category',
labels: {
rotation: -45,
style: {
fontSize: '13px',
fontFamily: 'Verdana, sans-serif'
}
}
},
yAxis: {
min: 0,
title: {
text: 'Revenue (RM)'
}
},
plotOptions: {
column: {
allowPointSelect: true,
cursor: 'pointer',
dataLabels: {
enabled: true,
color: '#000000',
connectorColor: '#000000',
formatter: function() {
return '<b>'+ this.point.name;
}
}
}
},
series: [{
type: 'column',
name: 'Revenue',
data: []
}]
}
$.getJSON("dataCountryRevenue.php", function(json) {
options.series[0].data = json;
chart = new Highcharts.Chart(options);
});
});
</script>
Try hiding one of the divs on document load:
EDIT:
I'm not super familiar with the HighCharts API, but it looks like there is a callback in the constructor that will allow you to do something after the chart is done loading. In this case, I hide the chart after it has finished loading.
$(document).ready(function() {
$(".css-checkbox").click(function() {
if ($(this).attr('id') == "one") {
$('#a').show();
$('#b').hide();
} else {
$('#a').hide();
$('#b').show();
}
});
var options1 = {
//removed for brevity;
}
var options2 = {
//removed for brevity;
}
//get chart1
$.getJSON("dataCountryRevenue.php", function(json) {
options.series[0].data = json;
chart = new Highcharts.Chart(options1);
});
//get chart2
$.getJSON("dataCountryRevenue.php", function(json) {
options.series[0].data = json;
chart = new Highcharts.Chart(options2, function() {
//hide chart after it has been loaded
$("#b").hide();
});
});
});
Since you are dealing with something filling the contents while potentially hidden, you might set the div off screen rather than display: none;.
function setOnScreen(id){
var $a = $("#a");
var $b = $("#b");
var $hide = (id === "one" ? $a : $b);
var className = "offscreen";
$a.addClass(className);
$b.addClass(className);
$hide.removeClass(className);
}
$(document).ready(function () {
setOnScreen($(".css-checkbox[checked]").attr("id"));
$(".css-checkbox").click(function () { setOnScreen($(this).attr("id")); });
});
#a { background-color: aliceblue; border: solid 1px; }
#b { background-color: mistyrose; border: solid 1px; }
.offscreen {
position: absolute;
left: -10000px;
}
<div id="a" class="offscreen">
<div id="Revenue" style="min-width: 100px; height: 100px; margin: 0 auto"></div>
</div>
<div id="b" class="offscreen">
<div id="Revenue2" style="min-width: 100px; height: 100px; margin: 0 auto"></div>
</div>
<input type="radio" name="cardType" id="one" class="css-checkbox" value="db" checked>Pie
<input type="radio" name="cardType" id="two" class="css-checkbox" value="cc">Column
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
my english is a trash, but I want to try.
that is a version modified by me, these vectors colorful buttons are. I'm trying to display a text when you click each of the buttons.but when I click other buttons, texts overlap, as shown in this picture:
http://i.stack.imgur.com/S39dX.png
This is the code that handles the event:
$('.get').find('.arc').each(function(i){
var t = $(this),
color = t.find('.color').val(),
value = t.find('.percent').val(),
text = t.find('.text').text();
conteudo = t.find('.conteudo').text();
alet = ( 11.25 * i );
/*title.rotate(20.25 * i);*/
rad = arco_espaco;
var z = r.path().attr({ arc: [value, color, rad], 'stroke-width': arco_width,});
var zm = r.path().attr({ arc: [value, color, rad], 'stroke-width': arco_width, opacity: 0}).toFront();/*MASK*/
var title = r.text(220, 0, defaultText).attr({
font: '20px Arial',
fill: '#fff'
}).toFront();
title.rotate(11.25*(i+0.40),-1,5);
var texto = r.text(300, 10, conteudo).attr({
font: '20px Arial',
fill: '#fff',
"text-anchor":"start",
opacity: 0
}).toFront();
var group = r.set();
group.push(z);
group.push(title);
ativo = 1;
zm.mouseover(function(){
group.animate({ 'stroke-width': arco_ganho, opacity: .75 }, 1000, 'elastic');
if(Raphael.type != 'VML') //solves IE problem
title.stop().animate({ opacity: 1 }, speed, '>', function(){
title.attr({ text: text + '\n'}).animate({ opacity: 1 }, 50, '<');
title.toFront();
zm.toFront();
});
document.body.style.cursor = "pointer";
zm.mouseout(function(){
zm.toFront();
group.stop().animate({ 'stroke-width': arco_width, opacity: 1 }, speed*4, 'elastic');
title.stop().animate({ opacity: 0 }, speed, '>', function(){
title.attr({ text: defaultText }).animate({ opacity: 0 }, speed, '<');
title.attr({ text: text + '\n' }).animate({ opacity: 0, align: left }, speed, '<');
});
document.body.style.cursor = "auto";
});
zm.click(function () {
$("#diagram").css("background-color",color);
texto.attr({opacity: 1});
tempp = texto;
});
})
zm.toFront();
});
the text come from the html file:
<div class="get">
<div class="arc">
<span class="text">Secretaria</span>
<input type="hidden" class="percent" value="100" />
<input type="hidden" class="color" value="#f6c201" />
<span class="conteudo">TEEEEEXXXXXXTT >>>SECRETARIA<<<</span>
</div>
<div class="arc">
<span class="text">Financeiro</span>
<input type="hidden" class="percent" value="100" />
<input type="hidden" class="color" value="#97BE0D" />
<span class="conteudo">TEEE-------XTT >>>FINANCEIRO<<<</span>
</div>
</div>
see on jsbin http://jsbin.com/unojov/2/edit