FabricJS - How to dragging an object in Shape filled object? - html

Im trying to drawing line Shape (fabric.Line).
and then after drawn shape. it filled image.
When finished drawing an shape, I want to drag an filled image (inside Shape)
Here is the jsfiddle >> http://jsfiddle.net/dTpVw/
var canvas = new fabric.Canvas('c', { selection:false });
var mode = "add";
var currentShape;
canvas.observe("mouse:move", function (event) {
var pos = canvas.getPointer(event.e);
if (mode === "edit" && currentShape) {
if (currentShape.type === "line") {
currentShape.set({
x2 : pos.x,
y2 : pos.y
});
canvas.renderAll();
} else if (currentShape.type === "polygon") {
var points = currentShape.get("points");
points[points.length - 1].x = pos.x - currentShape.get("left");
points[points.length - 1].y = pos.y - currentShape.get("top");
currentShape.set({
points : points
});
canvas.renderAll();
}
}
});
canvas.observe("mouse:down", function (event) {
var pos = canvas.getPointer(event.e);
if (mode === "add") {
var polygon = new fabric.Line([ pos.x, pos.y, pos.x + 2,
pos.y + 2 ], {
fill : 'red'
});
currentShape = polygon;
canvas.add(currentShape);
mode = "edit";
} else if (mode === "edit" && currentShape
&& currentShape.type === "line") {
// replace line with polygon
canvas.remove(currentShape);
var points = [];
points.push({
x : currentShape.x1 - pos.x,
y : currentShape.y1 - pos.y
});
points.push({
x : currentShape.x2 - pos.x,
y : currentShape.y2 - pos.y
});
points.push({
x : currentShape.x2 - pos.x + 5,
y : currentShape.y2 - pos.y + 5
});
var polygon = new fabric.Polygon(points, {
fill : 'blue',
left : pos.x,
top : pos.y,
opacity: 0.5 // 투명도 적용
});
canvas.add(polygon);
Spolygon = polygon;
currentShape = polygon;
canvas.renderAll();
} else if (mode === "edit" && currentShape
&& currentShape.type === "polygon") {
var points = currentShape.get("points");
points.push({
x : pos.x - currentShape.get("left"),
y : pos.y - currentShape.get("top")
});
currentShape.set({
points : points
});
canvas.renderAll();
}
});
function loadPattern(url) {
fabric.util.loadImage(url, function(img) {
console.log(Spolygon);
Spolygon.fill = new fabric.Pattern({
source : img,
repeat : 'repeat'
});
canvas.renderAll();
});
Spolygon.hasControls = false;
// Spolygon.selectable = false;
Spolygon.hasRotatingPoint = false;
Spolygon.lockMovementX = true;
Spolygon.lockMovementY = true;
}
function dblClickHandler(event)
{
currentShape.setCoords();
mode ="add2";
loadPattern('http://fabricjs.com/assets/retina_wood.png');
};
fabric.util.addListener(fabric.document, 'dblclick', dblClickHandler);
//fabric.util.removeListener(canvas.upperCanvasEl, 'dblclick', dblClickHandler);
Thank you for reading my question... Please someone help me T_T

Try something like this in your dblClickHandler event:
function dblClickHandler(event)
{
currentShape.setCoords();
mode ="add2";
loadPattern('http://fabricjs.com/assets/retina_wood.png');
//alert(currentShape.height);
//alert(currentShape.width);
currentShape.hasControls = true;
currentShape.hasRotatingPoint = true;
currentShape.lockMovementX = false;
currentShape.lockMovementY = false;
canvas.setActiveObject(currentShape);
canvas.renderAll();
};
I have updated your fiddle: http://jsfiddle.net/dTpVw/3/
I hope it helps...

Related

HTML Canvas Clears and Reappears

I have a html canvas that I draw a rect on, when I clear the canvas the screen clears but when you move the mouse the rect reappears. I stretch the rect vertically. Here is a code pen example of what is happening, you have to double click on the canvas for the rect to appear. https://codepen.io/tjquinn/pen/BYZQqo
HTML
<div id="app">
<div class="cv">
<canvas v-on:mousedown="mouseDown" v-on:mousemove="mouseMove" v-on:mouseup="mouseUp" #dblclick="dclick" id="rect" class="rect" width="150" height="700"></canvas>
<button v-on:click="clear">
Clear
</button>
</div>
</div>
JS
methods: {
checkCloseEnough: function (p1, p2) {
return Math.abs(p1 - p2) < this.closeEnough;
},
getVal: function (x) {
this.canvas2 = document.getElementById('rect');
this.ctx2 = this.canvas2.getContext('2d');
this.st = this.canvas2.height;
this.ic = (this.st / x);
},
draw: function () {
this.ctx2.fillStyle = "#222222";
this.ctx2.fillRect(this.ctx2.rect.startX, this.ctx2.rect.startY, this.ctx2.rect.w, this.ctx2.rect.h);
this.drawHandles();
},
drawHandles: function () {
this.drawCircle(this.ctx2.rect.startX + this.ctx2.rect.w/2, this.ctx2.rect.startY, this.closeEnough); //top left corner
//drawCircle(rect.startX + rect.w, rect.startY, closeEnough);
//drawCircle(rect.startX + rect.w, rect.startY + rect.h, closeEnough);
this.drawCircle(this.ctx2.rect.startX + this.ctx2.rect.w/2, this.ctx2.rect.startY + this.ctx2.rect.h, this.closeEnough);
},
drawCircle: function (x, y, radius) {
this.ctx2.fillStyle = "#FF0000";
this.ctx2.beginPath();
this.ctx2.arc(x, y, radius, 0, 2 * Math.PI);
this.ctx2.closePath();
this.ctx2.fill();
},
checkCloseEnough: function (p1, p2) {
return Math.abs(p1 - p2) < this.closeEnough;
},
mouseDown: function (event) {
this.mouseX = event.pageX - this.canvas2.offsetLeft;
this.mouseY = event.pageY - this.canvas2.offsetTop;
// if there isn't a rect yet
if (this.ctx2.rect.w === undefined) {
this.ctx2.rect.startX = this.mouseY;
this.ctx2.rect.startY = this.mouseX;
this.dragBR = true;
}
if (this.checkCloseEnough(this.mouseX, this.ctx2.rect.startX + this.ctx2.rect.w/2) && this.checkCloseEnough(this.mouseY, this.ctx2.rect.startY)) {
this.dragTL = true;
}
else if (this.checkCloseEnough(this.mouseX, this.ctx2.rect.startX + this.ctx2.rect.w/2) && this.checkCloseEnough(this.mouseY, this.ctx2.rect.startY + this.ctx2.rect.h)) {
this.dragBR = true;
}
else {
// handle not resizing
}
this.ctx2.clearRect(0, 0, this.canvas2.width, this.canvas2.height);
this.draw();
},
mouseMove: function (event) {
this.mouseX = event.pageX - this.canvas2.offsetLeft;
this.mouseY = event.pageY - this.canvas2.offsetTop;
if (this.dragTL) {
//rect.w += rect.startX - mouseX;
this.ctx2.rect.h += this.ctx2.rect.startY - this.mouseY;
//rect.startX = mouseX;
this.ctx2.rect.startY = this.mouseY;
}
else if (this.dragBR) {
//rect.w = Math.abs(rect.startX - mouseX);
this.ctx2.rect.h = Math.abs(this.ctx2.rect.startY - this.mouseY);
}
this.ctx2.clearRect(0, 0, this.canvas2.width, this.canvas2.height);
this.draw();
},
mouseUp: function () {
this.dragTL = false;
this.dragTR = false;
this.dragBL = false;
this.dragBR = false;
},
dclick: function (e) {
console.log("Fires");
e.preventDefault();
this.ctx2.rect = {
startX: 25,
startY: 100,
w: (this.canvas2.width - 50),
h: 300,
}
this.draw();
this. ln = this.lines;
this.getVal(10);
},
clear: function () {
this.cv2 = 'rect';
this.canvas2 = document.getElementById(this.cv2);
this.ctx2 = this.canvas2.getContext('2d');
console.log(this.ctx2.clearRect(0, 0, this.canvas2.width, this.canvas2.height));
console.log("Clear should run");
},
}
})
It turns out the error was in my logic that was pointed out by Kamal Singh, I needed to add clear flags to my methods so that they do not run if the screen has been cleared.
<html>
<head>
<title>Test</title>
<script src="vue.min.js"></script>
</head>
<body>
<div id="app">
<div class="cv">
<canvas style='border:1px solid;' v-on:mousedown="mouseDown" v-on:mousemove="mouseMove" v-on:mouseup="mouseUp" #dblclick="dclick" id="rect" class="rect" width="150" height="700"></canvas>
<button v-on:click="clear">
Clear
</button>
</div>
</div>
<script>
new Vue({
el: '#app',
data: function() {
return {
rect : {},
drag : false,
closeEnough : 10,
st : 0,
ic : 0,
mouseX : 0,
mouseY : 0,
dragTL : false,
dragBL : false,
dragTR : false,
dragBR : false,
cv2: '',
ln: 0,
cleared: true
}
},
mounted: function () {
this.getVal(10);
this.draw();
},
methods: {
checkCloseEnough: function (p1, p2) {
return Math.abs(p1 - p2) < this.closeEnough;
},
getVal: function (x) {
this.canvas2 = document.getElementById('rect');
this.ctx2 = this.canvas2.getContext('2d');
this.st = this.canvas2.height;
this.ic = (this.st / x);
},
draw: function () {
this.ctx2.fillStyle = "#222222";
this.ctx2.fillRect(this.ctx2.rect.startX, this.ctx2.rect.startY, this.ctx2.rect.w, this.ctx2.rect.h);
this.drawHandles();
},
drawHandles: function () {
this.drawCircle(this.ctx2.rect.startX + this.ctx2.rect.w/2, this.ctx2.rect.startY, this.closeEnough); //top left corner
//drawCircle(rect.startX + rect.w, rect.startY, closeEnough);
//drawCircle(rect.startX + rect.w, rect.startY + rect.h, closeEnough);
this.drawCircle(this.ctx2.rect.startX + this.ctx2.rect.w/2, this.ctx2.rect.startY + this.ctx2.rect.h, this.closeEnough);
},
drawCircle: function (x, y, radius) {
this.ctx2.fillStyle = "#FF0000";
this.ctx2.beginPath();
this.ctx2.arc(x, y, radius, 0, 2 * Math.PI);
this.ctx2.closePath();
this.ctx2.fill();
},
checkCloseEnough: function (p1, p2) {
return Math.abs(p1 - p2) < this.closeEnough;
},
mouseDown: function (event) {
if(this.cleared) return;
this.mouseX = event.pageX - this.canvas2.offsetLeft;
this.mouseY = event.pageY - this.canvas2.offsetTop;
// if there isn't a rect yet
if (this.ctx2.rect.w === undefined) {
this.ctx2.rect.startX = this.mouseY;
this.ctx2.rect.startY = this.mouseX;
this.dragBR = true;
}
if (this.checkCloseEnough(this.mouseX, this.ctx2.rect.startX + this.ctx2.rect.w/2) && this.checkCloseEnough(this.mouseY, this.ctx2.rect.startY)) {
this.dragTL = true;
}
else if (this.checkCloseEnough(this.mouseX, this.ctx2.rect.startX + this.ctx2.rect.w/2) && this.checkCloseEnough(this.mouseY, this.ctx2.rect.startY + this.ctx2.rect.h)) {
this.dragBR = true;
}
else {
// handle not resizing
}

Making invisible sprite with phaser

I need some help with my code. I want to make the str sprite invisible after 10 seconds.
I'm using this link for help: http://phaser.io/examples/v2/time/basic-timed-event
var game = new Phaser.Game(500, 550, Phaser.AUTO);
//var picture;
var Pacman = function (game) {
this.map = null;
this.layer = null;
this.pacman = null;
this.safetile = 14;
this.gridsize = 16;
this.speed = 100;
this.threshold = 3;
this.turnSpeed = 200;
this.marker = new Phaser.Point();
this.turnPoint = new Phaser.Point();
this.directions = [ null, null, null, null, null ];
this.opposites = [ Phaser.NONE, Phaser.RIGHT, Phaser.LEFT, Phaser.DOWN, Phaser.UP ];
this.current = Phaser.NONE;
this.turning = Phaser.NONE;
this.score=0;
this.scoreText='';
this.bonus=0;
this.bonusText='';
};
Pacman.prototype = {
init: function () {
this.scale.scaleMode = Phaser.ScaleManager.SHOW_ALL;
this.scale.pageAlignHorizontally = true;
this.scale.pageAlignVertically = true;
Phaser.Canvas.setImageRenderingCrisp(this.game.canvas);
this.physics.startSystem(Phaser.Physics.ARCADE);
},
preload: function () {
// We need this because the assets are on github pages
// Remove the next 2 lines if running locally
this.load.baseURL = 'https://nikosdaskalos.github.io/pacman/';
this.load.crossOrigin = 'anonymous';
this.load.image('str', 'assets/str.png');
this.load.image('dot', 'assets/dot.jpg');
this.load.image('coin', 'assets/coin.jpg');
this.load.image('tiles', 'assets/pacman-tiles.png');
this.load.spritesheet('pacman', 'assets/pacman.png');
this.load.tilemap('map', 'assets/pacman-map.json', null, Phaser.Tilemap.TILED_JSON);
// Needless to say, graphics (C)opyright Namco
},
create: function () {
this.map = this.add.tilemap('map');
this.map.addTilesetImage('pacman-tiles', 'tiles');
this.layer = this.map.createLayer('Pacman');
//picture = game.add.sprite(game.world.centerX, game.world.centerY, 'str');
//picture.anchor.setTo(0.5, 0.5);
//game.time.events.add(Phaser.Timer.SECOND * 4, fadePicture, this);
this.dots = this.add.physicsGroup();
this.map.createFromTiles(36, this.safetile, 'str', this.layer, this.dots);
this.map.createFromTiles(7, this.safetile, 'dot', this.layer, this.dots);
this.map.createFromTiles(35, this.safetile, 'coin', this.layer, this.dots);
// The dots will need to be offset by 6px to put them back in the middle of the grid
this.dots.setAll('x', 6, false, false, 1);
this.dots.setAll('y', 6, false, false, 1);
// Pacman should collide with everything except the safe tile
this.map.setCollisionByExclusion([this.safetile], true, this.layer);
// Position Pacman at grid location 14x17 (the +8 accounts for his anchor)
this.pacman = this.add.sprite((14 * 16) + 8, (17 * 16) + 8, 'pacman', 0);
this.pacman.anchor.set(0.5);
//this.pacman.animations.add('munch', [0, 1, 2, 1], 20, true);
this.physics.arcade.enable(this.pacman);
this.pacman.body.setSize(16, 16, 0, 0);
this.cursors = this.input.keyboard.createCursorKeys();
//this.pacman.play('munch');
this.move(Phaser.LEFT);
this.scoreText = game.add.text(0, 500, 'Score: 0', { fontSize: '34px Arial', fill: 'white' });
lives = game.add.group();
game.add.text(game.world.width - 340, 500, 'Lives : ', { fontSize: '34px Arial', fill: 'white' });
this.bonusText = game.add.text(360, 500, 'Bonus: 0', { fontSize: '20px Arial', fill: 'white' });
for (var i = 0; i < 3; i++)
{
var pacman = lives.create(game.world.width - 235 + (30 * i), 517, 'pacman');
pacman.anchor.setTo(0.5, 0.5);
pacman.angle = 90;
pacman.alpha = 0.4;
}
},
//function fadePicture() {
//game.add.tween(picture).to( { alpha: 0 }, 2000, Phaser.Easing.Linear.None, true);
//},
checkKeys: function () {
if (this.cursors.left.isDown && this.current !== Phaser.LEFT)
{
this.checkDirection(Phaser.LEFT);
}
else if (this.cursors.right.isDown && this.current !== Phaser.RIGHT)
{
this.checkDirection(Phaser.RIGHT);
}
else if (this.cursors.up.isDown && this.current !== Phaser.UP)
{
this.checkDirection(Phaser.UP);
}
else if (this.cursors.down.isDown && this.current !== Phaser.DOWN)
{
this.checkDirection(Phaser.DOWN);
}
else
{
// This forces them to hold the key down to turn the corner
this.turning = Phaser.NONE;
}
},
checkDirection: function (turnTo) {
if (this.turning === turnTo || this.directions[turnTo] === null || this.directions[turnTo].index !== this.safetile)
{
// Invalid direction if they're already set to turn that way
// Or there is no tile there, or the tile isn't index 1 (a floor tile)
return;
}
// Check if they want to turn around and can
if (this.current === this.opposites[turnTo])
{
this.move(turnTo);
}
else
{
this.turning = turnTo;
this.turnPoint.x = (this.marker.x * this.gridsize) + (this.gridsize / 2);
this.turnPoint.y = (this.marker.y * this.gridsize) + (this.gridsize / 2);
}
},
turn: function () {
var cx = Math.floor(this.pacman.x);
var cy = Math.floor(this.pacman.y);
// This needs a threshold, because at high speeds you can't turn because the coordinates skip past
if (!this.math.fuzzyEqual(cx, this.turnPoint.x, this.threshold) || !this.math.fuzzyEqual(cy, this.turnPoint.y, this.threshold))
{
return false;
}
// Grid align before turning
this.pacman.x = this.turnPoint.x;
this.pacman.y = this.turnPoint.y;
this.pacman.body.reset(this.turnPoint.x, this.turnPoint.y);
this.move(this.turning);
this.turning = Phaser.NONE;
return true;
},
move: function (direction) {
var speed = this.speed;
if (direction === Phaser.LEFT || direction === Phaser.UP)
{
speed = -speed;
}
if (direction === Phaser.LEFT || direction === Phaser.RIGHT)
{
this.pacman.body.velocity.x = speed;
}
else
{
this.pacman.body.velocity.y = speed;
}
// Reset the scale and angle (Pacman is facing to the right in the sprite sheet)
/* this.pacman.scale.x = 1;
this.pacman.angle = 0;
if (direction === Phaser.LEFT)
{
this.pacman.scale.x = -1;
}
else if (direction === Phaser.UP)
{
this.pacman.angle = 270;
}
else if (direction === Phaser.DOWN)
{
this.pacman.angle = 90;
}
this.current = direction;
},*/
this.add.tween(this.pacman).to( { angle: this.getAngle(direction) }, this.turnSpeed, "Linear", true);
this.current = direction;
},
getAngle: function (to) {
// About-face?
if (this.current === this.opposites[to])
{
return "180";
}
if ((this.current === Phaser.UP && to === Phaser.LEFT) ||
(this.current === Phaser.DOWN && to === Phaser.RIGHT) ||
(this.current === Phaser.LEFT && to === Phaser.DOWN) ||
(this.current === Phaser.RIGHT && to === Phaser.UP))
{
return "-90";
}
return "90";
},
eatDot: function (pacman, dot) {
dot.kill();
var audio = new Audio('assets/pacman_chomp.wav');
audio.play()
this.score+=10;
this.scoreText.text= 'Score: ' + this.score;
//setTimeout(audio.play(),2000);
if (this.dots.total === 0)
{
this.dots.callAll('revive');
}
},
/*function muteAudio() {
var audio = document.getElementById('audioPlayer');
if (audio.mute = false) {
document.getElementById('audioPlayer').muted = true;
}
else {
audio.mute = true
document.getElementById('audioPlayer').muted = false;
}
}*/
eatCoin: function(pacman,coin){//pente
coin.kill();
this.score+=20;
this.scoreText.text= 'Score: ' + this.score;
var audio = new Audio('assets/pacman_eatfruit.wav');
audio.play()
if(this.coins.total===0)
{
this.coins.callAll('revive');
}
},
eatStr: function(pacman,str){//pente
str.kill();
this.bonus+=100;
this.bonusText.text= 'Bonus: ' + this.bonus;
var audio = new Audio('assets/pacman_eatfruit.wav');
audio.play()
if(this.strs.total===0)
{
this.strs.callAll('revive');
}
},
update: function () {
this.physics.arcade.collide(this.pacman, this.layer);
this.physics.arcade.overlap(this.pacman, this.dots, this.eatDot, null, this);
this.physics.arcade.overlap(this.pacman, this.dots, this.eatCoin, null, this);
this.physics.arcade.overlap(this.pacman, this.dots, this.eatStr, null, this);
this.marker.x = this.math.snapToFloor(Math.floor(this.pacman.x), this.gridsize) / this.gridsize;
this.marker.y = this.math.snapToFloor(Math.floor(this.pacman.y), this.gridsize) / this.gridsize;
// Update our grid sensors
this.directions[1] = this.map.getTileLeft(this.layer.index, this.marker.x, this.marker.y);
this.directions[2] = this.map.getTileRight(this.layer.index, this.marker.x, this.marker.y);
this.directions[3] = this.map.getTileAbove(this.layer.index, this.marker.x, this.marker.y);
this.directions[4] = this.map.getTileBelow(this.layer.index, this.marker.x, this.marker.y);
this.checkKeys();
if (this.turning !== Phaser.NONE)
{
this.turn();
}
}
};
game.state.add('Game', Pacman, true);
</script>
</body>
</html>
So, can anyone help me with making the str invisible after 10 seconds?
You were pretty close.
I'm going to use pacman as an example, since I'm not 100% sure how you were going to fade out the coins. When Pacman eats them?
First, you want the following fadePicture function:
fadePicture: function() {
game.add.tween(this.pacman).to( { alpha: 0 }, 2000, Phaser.Easing.Linear.None, true);
},
Note how that was changed from function fadePicture().
Next, in your create function you can refer to it:
this.game.time.events.add(Phaser.Timer.SECOND * 4, this.fadePicture, this);
That replaces the following:
//game.time.events.add(Phaser.Timer.SECOND * 4, fadePicture, this);
I've created a JSFiddle with the relevant changes.
If you do want your coins to fade then I would try updating fadePicture to accept a dot/str parameter and then game.add.tween on that.

Fabric.js canvas image disappear after loading image second time

Hello i am uploading a image once image will upload ,i am loading that image in canvas which i am creating in popup.
Once image is loaded it appears in pop up where i am performing crop functionality,everything is working fine but when i am uploading image second time
image appears but when i click on image to crop it image disappears on canvas.
Please suggest me how to fix the issue?
Here is my code
handleImage1= function(e) {
var mousex = 0;
var mousey = 0;
var reader = new FileReader();
var baseUrl = jQuery("#base-url").val();
var file = this.files[0];
var fd = new FormData();
fd.append("afile", file);
var mouseDown;
// only allow one crop. turn it off after that
var disabled = false;
var rect;
var container = document.getElementById('c1').getBoundingClientRect();
var canvas1 = new fabric.Canvas('c1');
var center = canvas1.getCenter();
//canvas1.add(rect);
var image;
var isDown, origX, origY;
var rawImageid;
var result='';
var object;
jQuery.ajax({
type : 'POST',
url : baseUrl+'personalized/index/saveRawImage',
data : fd,
dataType : 'text',
cache: false,
beforeSend: function(){
jQuery('#divLoading').show();
},
contentType: false,
processData: false,
success : function(result) {
result=result;
var imgSizeObj;
fabric.util.loadImage(result, function(img) {
image = new fabric.Image(img);
image.selectable = false;
image.originX= 'center',
image.originY= 'center',
//image.top=center.top,
//image.left=center.left,
imgSizeObj = image.getOriginalSize();
width_ratio = canvas1.width / image.width;
height_ratio = canvas1.height / image.height;
if (height_ratio>width_ratio ) {
fw = image.width * width_ratio;
fh = image.height*fw/image.width;
} else {
fh = image.height * height_ratio;
fw = image.width*fh/image.height;
}
if (imgSizeObj.width > canvas1.width || imgSizeObj.height > canvas1.height) {
image.set({
width: fw,
height: fh
});
}
canvas1.add(image);
canvas1.centerObject(image);
canvas1.renderAll();
});
// capture the event when the user clicks the mouse button down
canvas1.on('mouse:down', function(o){
isDown = true;
var pointer = canvas1.getPointer(o.e);
origX = pointer.x;
origY = pointer.y;
var pointer = canvas1.getPointer(o.e);
canvas1.remove(rect);
rect = new fabric.Rect({
left: origX,
top: origY,
originX: 'left',
originY: 'top',
width: pointer.x-origX,
height: pointer.y-origY,
angle: 0,
opacity:0.5,
transparentCorners: false,
hasControls: false,
hasBorders: false
});
canvas1.add(rect);
canvas1.renderAll()
});
// draw the rectangle as the mouse is moved after a down click
canvas1.on('mouse:move', function(o){
if (!isDown) return;
var pointer = canvas1.getPointer(o.e);
if(origX>pointer.x){
rect.set({ left: Math.abs(pointer.x) });
}
if(origY>pointer.y){
rect.set({ top: Math.abs(pointer.y) });
}
rect.set({ width: Math.abs(origX - pointer.x) });
rect.set({ height: Math.abs(origY - pointer.y) });
canvas1.renderAll();
});
canvas1.on('mouse:up', function(o){
isDown = false;
});
jQuery('#cropB').on('click', function() {
image.selectable = true;
disabled = true;
rect.visible = false;
var cropped = new Image();
cropped.src = canvas1.toDataURL({
left: rect.left,
top: rect.top,
width: rect.width,
height: rect.height
});
fabric.util.loadImage(cropped.src, function(img) {
var image1 = new fabric.Image(img);
image1.selectable = true;
canvas.add(image1);
canvas.centerObject(image1);
image1.selectable = true;
canvas.renderAll();
});
canvas1.clear();
jQuery('#changePic').modal('hide');
});
jQuery('#add_image_custom').on('click',function(){
var rawImageValue = jQuery("#rawImages").val();
rawImageid = result;
if(rawImageValue == 0){
rawImageValue = result;
}else{
rawImageValue = rawImageValue + ','+ result;
}
jQuery("#rawImages").val(rawImageValue);
var img = new Image();
var center = canvas.getCenter();
img.onload = function () {
var imgInstance = new fabric.Image(img, {
originX: 'center',
originY: 'center',
top: center.top,
left: center.left,
});
var imgSizeObj = imgInstance.getOriginalSize();
//alert(imgSizeObj.width+'|'+imgSizeObj.height+'|'+canvas.width+'|'+canvas.height);
width_ratio = canvas.width / imgSizeObj.width;
height_ratio = canvas.height / imgSizeObj.height;
if (height_ratio>width_ratio ) {
fw = imgSizeObj.width * width_ratio;
fh = imgSizeObj.height*fw/imgSizeObj.width;
} else {
fh = imgSizeObj.height * height_ratio;
fw = imgSizeObj.width*fh/imgSizeObj.height;
}
if (imgSizeObj.width > canvas.width || imgSizeObj.height > canvas.height) {
imgInstance.set({
width: fw,
height: fh
});
}
if(canvas.width<400)
{
imgInstance.scaleX = canvas.width*0.9/imgInstance.width;
imgInstance.scaleY = imgInstance.scaleX;
}
imgInstance.RawImageId=rawImageid;
canvas.add(imgInstance);
}
img.src = result;
reader.readAsDataURL(e.target.files[0]);
canvas1.clear();
jQuery('#changePic').modal('hide');
});
/*Shrink fit code end here---------------------------------*/
//imgpopup.src = src1;
//canvas1.add(image);
//canvas1.renderAll();
//jQuery('#main-image').attr('src',result);
//jQuery('#main-image').show();
setTimeout(function(){
jQuery('#changePic').modal();
jQuery('#divLoading').hide();
}, 300);
},
error : function(xhr, status) {
//console.log(status);
//console.log(xhr); //
jQuery('.loading').hide();
}
});
}

D3Js vertical collapsible graph node overlap due to bigger radius

I have created a D3Js vertical collapsible tree by taking the code from this site. I want to increase the radius of the nodes. Currently, its at r=10 and would like to increase it to 30. Which results the neighbour nodes to overlap with each other like below.. How can I increase the distance between each node so it doesnt overlap with each other?
Thank you
function buildVerticalTree(treeData,treeContainerDom){
var margin = {top :40,right:120,bottom:20,left:120};
var width = 960 - margin.right - margin.left;
var height = 700 - margin.top - margin.bottom;
var i = 0, duration = 750;
var tree = d3.layout.tree()
.size([height,width]);
var diagonal = d3.svg.diagonal()
.projection(function(d){
return [d.x, d.y];
});
var svg = d3.select(treeContainerDom).append("svg")
.attr("width",width+margin.left+margin.right)
.attr("height",height+margin.top+margin.bottom)
.append("g")
.attr("transform","translate("+margin.left+","+margin.top+")");
var root = treeData;
update(root);
function update(source){
var nodes = tree.nodes(root).reverse();
var links = tree.links(nodes);
nodes.forEach(function(d){
d.y = d.depth * 100;
});
var node = svg.selectAll("g.node")
.data(nodes,function(d){
return d.id || (d.id=++i);
});
var nodeEnter = node.enter().append("g")
.attr("class","node")
.attr("transform",function(d){
if(!source.x0 && !source.y0)
return "";
return "translate("+source.x0+","+source.y0+")";
})
.on("click",nodeclick)
nodeEnter.append("circle")
.attr("r",10)
.attr("stroke",function(d){
return d.children || d._children ? "steelblue" : "#00c13f";
})
.style("fill",function(d){
return d.children || d._children ? "lightsteelblue" : "#fff";
});
nodeEnter.append("text")
.attr("y",function(d){
return d.children || d._children ? -18 : 18;
//return 0;
})
.attr("dy",".35em")
.attr("text-anchor","middle")
.text(function(d){
return d.name;
})
.style("fill","black")
.style("fill-opacity",1e-6)
var nodeUpdate = node.transition()
.duration(duration)
.attr("transform",function(d){
return "translate("+ d.x+","+ d.y+")";
});
nodeUpdate.select("circle")
.attr("r",10)
.style("fill",function(d){
return d._children ? "lightsteelblue" : "#fff";
});
nodeUpdate.select("text")
.style("fill-opacity",1);
var nodeExit = node.exit().transition()
.duration(duration)
.attr("transform",function(d){
return "translate("+source.x+","+source.y+")";
})
.remove();
nodeExit.select("circle")
.attr("r",1e-6);
nodeExit.select("text")
.style("fill-opacity",1e-6);
var link = svg.selectAll("path.link")
.data(links,function(d){
return d.target.id;
});
link.enter().insert("path","g")
.attr("class","link")
.attr("d",function(d){
if(!source.x0 && !source.y0)
return "";
var o = {x:source.x0,y:source.y0};
return diagonal({source:o,target:o});
});
link.transition()
.duration(duration)
.attr("d",diagonal);
link.exit().transition()
.duration(duration)
.attr("d",function(d){
var o = {x:source.x,y:source.y};
return diagonal({source:o,target:o});
})
.remove();
nodes.forEach(function(d){
d.x0 = d.x;
d.y0 = d.y;
});
}
function nodeclick(d){
if(d.children){
d._children = d.children;
d.children = null;
}else{
d.children = d._children;
d._children = null;
}
update(d);
}
}//end of buildVerticalTree
buildVerticalTree(that.objectList, "#tree");

how to show two d3.js diagrams on the same page

i read lots of threads and the Mike's blog but i haven't found how to solve my problem.
I'm using the donut chart of D3.js and everything works fine.
I use that code and change the value for each diagram:
var w = 650;
var h = 400;
var r = 150;
var ir = 75;
var textOffset = 24;
var tweenDuration = 1050;
//OBJECTS TO BE POPULATED WITH DATA LATER
var lines, valueLabels, nameLabels;
var pieData = [];
var oldPieData = [];
var filteredPieData = [];
//D3 helper function to populate pie slice parameters from array data
var donut = d3.layout.pie().value(function(d){
return d.itemValue;
});
//D3 helper function to create colors from an ordinal scale
var color = d3.scale.category20c();
//D3 helper function to draw arcs, populates parameter "d" in path object
var arc = d3.svg.arc()
.startAngle(function(d){ return d.startAngle; })
.endAngle(function(d){ return d.endAngle; })
.innerRadius(ir)
.outerRadius(r);
///////////////////////////////////////////////////////////
// GENERATE FAKE DATA /////////////////////////////////////
///////////////////////////////////////////////////////////
var data;
var dataStructure = [
{
"data":[
{
"itemLabel":"Social Media",
"itemValue":90
},
{
"itemLabel":"Blogs",
"itemValue":30
},
{
"itemLabel":"Text Messaging",
"itemValue":60
},
{
"itemLabel":"Email",
"itemValue":90
},
],
"label":"2007"
},
{
"data":[
{
"itemLabel":"Social Media",
"itemValue":80
},
{
"itemLabel":"Blogs",
"itemValue":20
},
{
"itemLabel":"Text Messaging",
"itemValue":70
},
{
"itemLabel":"Email",
"itemValue":90
},
],
"label":"2009"
},
{
"data":[
{
"itemLabel":"Social Media",
"itemValue":70
},
{
"itemLabel":"Blogs",
"itemValue":20
},
{
"itemLabel":"Text Messaging",
"itemValue":70
},
{
"itemLabel":"Email",
"itemValue":90
},
],
"label":"2011"
},
{
"data":[
{
"itemLabel":"Social Media",
"itemValue":60
},
{
"itemLabel":"Blogs",
"itemValue":20
},
{
"itemLabel":"Text Messaging",
"itemValue":70
},
{
"itemLabel":"Email",
"itemValue":90
},
],
"label":"2013"
},
];
///////////////////////////////////////////////////////////
// CREATE VIS & GROUPS ////////////////////////////////////
///////////////////////////////////////////////////////////
var vis = d3.select("#pie-chart").append("svg:svg")
.attr("width", w)
.attr("height", h);
//GROUP FOR ARCS/PATHS
var arc_group = vis.append("svg:g")
.attr("class", "arc")
.attr("transform", "translate(" + (w/2) + "," + (h/2) + ")");
//GROUP FOR LABELS
var label_group = vis.append("svg:g")
.attr("class", "label_group")
.attr("transform", "translate(" + (w/2) + "," + (h/2) + ")");
//GROUP FOR CENTER TEXT
var center_group = vis.append("svg:g")
.attr("class", "center_group")
.attr("transform", "translate(" + (w/2) + "," + (h/2) + ")");
//PLACEHOLDER GRAY CIRCLE
// var paths = arc_group.append("svg:circle")
// .attr("fill", "#EFEFEF")
// .attr("r", r);
///////////////////////////////////////////////////////////
// CENTER TEXT ////////////////////////////////////////////
///////////////////////////////////////////////////////////
//WHITE CIRCLE BEHIND LABELS
var whiteCircle = center_group.append("svg:circle")
.attr("fill", "white")
.attr("r", ir);
///////////////////////////////////////////////////////////
// STREAKER CONNECTION ////////////////////////////////////
///////////////////////////////////////////////////////////
// to run each time data is generated
function update(number) {
data = dataStructure[number].data;
oldPieData = filteredPieData;
pieData = donut(data);
var sliceProportion = 0; //size of this slice
filteredPieData = pieData.filter(filterData);
function filterData(element, index, array) {
element.name = data[index].itemLabel;
element.value = data[index].itemValue;
sliceProportion += element.value;
return (element.value > 0);
}
//DRAW ARC PATHS
paths = arc_group.selectAll("path").data(filteredPieData);
paths.enter().append("svg:path")
.attr("stroke", "white")
.attr("stroke-width", 0.5)
.attr("fill", function(d, i) { return color(i); })
.transition()
.duration(tweenDuration)
.attrTween("d", pieTween);
paths
.transition()
.duration(tweenDuration)
.attrTween("d", pieTween);
paths.exit()
.transition()
.duration(tweenDuration)
.attrTween("d", removePieTween)
.remove();
//DRAW TICK MARK LINES FOR LABELS
lines = label_group.selectAll("line").data(filteredPieData);
lines.enter().append("svg:line")
.attr("x1", 0)
.attr("x2", 0)
.attr("y1", -r-3)
.attr("y2", -r-15)
.attr("stroke", "gray")
.attr("transform", function(d) {
return "rotate(" + (d.startAngle+d.endAngle)/2 * (180/Math.PI) + ")";
});
lines.transition()
.duration(tweenDuration)
.attr("transform", function(d) {
return "rotate(" + (d.startAngle+d.endAngle)/2 * (180/Math.PI) + ")";
});
lines.exit().remove();
//DRAW LABELS WITH PERCENTAGE VALUES
valueLabels = label_group.selectAll("text.value").data(filteredPieData)
.attr("dy", function(d){
if ((d.startAngle+d.endAngle)/2 > Math.PI/2 && (d.startAngle+d.endAngle)/2 < Math.PI*1.5 ) {
return 5;
} else {
return -7;
}
})
.attr("text-anchor", function(d){
if ( (d.startAngle+d.endAngle)/2 < Math.PI ){
return "beginning";
} else {
return "end";
}
})
.text(function(d){
var percentage = (d.value/sliceProportion)*100;
return percentage.toFixed(1) + "%";
});
valueLabels.enter().append("svg:text")
.attr("class", "value")
.attr("transform", function(d) {
return "translate(" + Math.cos(((d.startAngle+d.endAngle - Math.PI)/2)) * (r+textOffset) + "," + Math.sin((d.startAngle+d.endAngle - Math.PI)/2) * (r+textOffset) + ")";
})
.attr("dy", function(d){
if ((d.startAngle+d.endAngle)/2 > Math.PI/2 && (d.startAngle+d.endAngle)/2 < Math.PI*1.5 ) {
return 5;
} else {
return -7;
}
})
.attr("text-anchor", function(d){
if ( (d.startAngle+d.endAngle)/2 < Math.PI ){
return "beginning";
} else {
return "end";
}
}).text(function(d){
var percentage = (d.value/sliceProportion)*100;
return percentage.toFixed(1) + "%";
});
valueLabels.transition().duration(tweenDuration).attrTween("transform", textTween);
valueLabels.exit().remove();
//DRAW LABELS WITH ENTITY NAMES
nameLabels = label_group.selectAll("text.units").data(filteredPieData)
.attr("dy", function(d){
if ((d.startAngle+d.endAngle)/2 > Math.PI/2 && (d.startAngle+d.endAngle)/2 < Math.PI*1.5 ) {
return 17;
} else {
return 5;
}
})
.attr("text-anchor", function(d){
if ((d.startAngle+d.endAngle)/2 < Math.PI ) {
return "beginning";
} else {
return "end";
}
}).text(function(d){
return d.name;
});
nameLabels.enter().append("svg:text")
.attr("class", "units")
.attr("transform", function(d) {
return "translate(" + Math.cos(((d.startAngle+d.endAngle - Math.PI)/2)) * (r+textOffset) + "," + Math.sin((d.startAngle+d.endAngle - Math.PI)/2) * (r+textOffset) + ")";
})
.attr("dy", function(d){
if ((d.startAngle+d.endAngle)/2 > Math.PI/2 && (d.startAngle+d.endAngle)/2 < Math.PI*1.5 ) {
return 17;
} else {
return 5;
}
})
.attr("text-anchor", function(d){
if ((d.startAngle+d.endAngle)/2 < Math.PI ) {
return "beginning";
} else {
return "end";
}
}).text(function(d){
return d.name;
});
nameLabels.transition().duration(tweenDuration).attrTween("transform", textTween);
nameLabels.exit().remove();
}
///////////////////////////////////////////////////////////
// FUNCTIONS //////////////////////////////////////////////
///////////////////////////////////////////////////////////
// Interpolate the arcs in data space.
function pieTween(d, i) {
var s0;
var e0;
if(oldPieData[i]){
s0 = oldPieData[i].startAngle;
e0 = oldPieData[i].endAngle;
} else if (!(oldPieData[i]) && oldPieData[i-1]) {
s0 = oldPieData[i-1].endAngle;
e0 = oldPieData[i-1].endAngle;
} else if(!(oldPieData[i-1]) && oldPieData.length > 0){
s0 = oldPieData[oldPieData.length-1].endAngle;
e0 = oldPieData[oldPieData.length-1].endAngle;
} else {
s0 = 0;
e0 = 0;
}
var i = d3.interpolate({startAngle: s0, endAngle: e0}, {startAngle: d.startAngle, endAngle: d.endAngle});
return function(t) {
var b = i(t);
return arc(b);
};
}
function removePieTween(d, i) {
s0 = 2 * Math.PI;
e0 = 2 * Math.PI;
var i = d3.interpolate({startAngle: d.startAngle, endAngle: d.endAngle}, {startAngle: s0, endAngle: e0});
return function(t) {
var b = i(t);
return arc(b);
};
}
function textTween(d, i) {
var a;
if(oldPieData[i]){
a = (oldPieData[i].startAngle + oldPieData[i].endAngle - Math.PI)/2;
} else if (!(oldPieData[i]) && oldPieData[i-1]) {
a = (oldPieData[i-1].startAngle + oldPieData[i-1].endAngle - Math.PI)/2;
} else if(!(oldPieData[i-1]) && oldPieData.length > 0) {
a = (oldPieData[oldPieData.length-1].startAngle + oldPieData[oldPieData.length-1].endAngle - Math.PI)/2;
} else {
a = 0;
}
var b = (d.startAngle + d.endAngle - Math.PI)/2;
var fn = d3.interpolateNumber(a, b);
return function(t) {
var val = fn(t);
return "translate(" + Math.cos(val) * (r+textOffset) + "," + Math.sin(val) * (r+textOffset) + ")";
};
}
$( "#slider" ).slider({
value: 0,
min: 0,
max: 3,
step: 1,
slide: function( event, ui ) {
update(ui.value);
console.log(ui.value);
}
})
.each(function() {
//
// Add labels to slider whose values
// are specified by min, max and whose
// step is set to 1
//
// Get the options for this slider
var opt = $(this).data().uiSlider.options;
// Get the number of possible values
var vals = opt.max - opt.min;
// Space out values
for (var i = 0; i <= vals; i++) {
var el = $('<label>'+dataStructure[i].label+'</label>').css('left',(i/vals*100)+'%');
$( "#slider" ).append(el);
}
});
update(0);
Here is the Jsfiddle of the diagram i'm using:
jsfiddle.net/brusasu/AqP73/
I created two html page, each for the diagrams with the value i need to show.
My question is how to edit the code in a way where i can use the two diagrams in the same html page.
Thanks in advance
Oki Doki. I'm no expert in these things, but looking at the css in your jsfiddle, it appears to be missing the styles that you might want for the divs "slidercontainer2", "pie-chart2 and "slider2".
Make sure that you have these properly duplicated and that will at least get you closer.