Resizing with handles in interact.js + SVG - javascript

In this jsFiddle I have an SVG rect that is resized with interact.js. This works fine, however I need to add resize handles n/ne/e/se/s/sw/w/nw, 8x8 pixel squares at each point. These handles should be used to resize the rect (instead of dragging the rect sides).
I found examples in HTML, not SVG, for example here, but I couldn't figure out how to make this work in SVG instead of HTML. Any help will be greatly appreciated.
var svg = document.getElementById('mysvg');
var rect = document.createElementNS("http://www.w3.org/2000/svg", "rect");
svg.appendChild(rect);
rect.setAttribute('x', 100);
rect.setAttribute('y', 100);
rect.setAttribute('width', 100);
rect.setAttribute('height', 100);
rect.setAttribute('class', 'resize-me');
rect.setAttribute('stroke-width', 2);
rect.setAttribute('stroke', 'white');
rect.setAttribute('fill', 'grey')
interact('.resize-me')
.resizable({
edges: { left: true, right: true, bottom: true, top: true }
})
.on('resizemove', function(event) {
var target = event.target;
var x = (parseFloat(target.getAttribute('endx')) || 0)
var y = (parseFloat(target.getAttribute('endy')) || 0)
target.setAttribute('width', event.rect.width);
target.setAttribute('height', event.rect.height);
x += event.deltaRect.left
y += event.deltaRect.top
target.setAttribute('transform', 'translate(' + x + ', ' + y + ')')
target.setAttribute('endx', x)
target.setAttribute('endy', y)
});

Okay, done. Take a look:
const svg = document.getElementById('mysvg');
const rect = document.createElementNS("http://www.w3.org/2000/svg", "rect");
const group = document.createElementNS("http://www.w3.org/2000/svg", "g");
svg.appendChild(group);
group.appendChild(rect);
group.setAttribute('class', 'resize-me');
rect.setAttribute('x', 100);
rect.setAttribute('y', 100);
rect.setAttribute('width', 100);
rect.setAttribute('height', 100);
rect.setAttribute('stroke-width', 2);
rect.setAttribute('stroke', 'white');
rect.setAttribute('fill', 'grey');
// Create the handles
const handles = [];
for (let i = 0; i < 8; i++) {
const handle = document.createElementNS("http://www.w3.org/2000/svg", "rect");
handle.setAttribute('width', 8);
handle.setAttribute('height', 8);
handle.setAttribute('stroke-width', 1);
handle.setAttribute('stroke', 'white');
handle.setAttribute('fill', 'black');
handles.push(handle);
group.appendChild(handle);
}
// Manually assign them their resize duties (R->L, T->B)
handles[0].classList.add('resize-top', 'resize-left');
handles[1].classList.add('resize-top');
handles[2].classList.add('resize-top', 'resize-right');
handles[3].classList.add('resize-left');
handles[4].classList.add('resize-right');
handles[5].classList.add('resize-bottom', 'resize-left');
handles[6].classList.add('resize-bottom');
handles[7].classList.add('resize-bottom', 'resize-right');
// This function takes the rect and the list of handles and positions
// the handles accordingly
const findLocations = (r, h) => {
const x = Number(r.getAttribute('x'));
const y = Number(r.getAttribute('y'));
const width = Number(r.getAttribute('width'));
const height = Number(r.getAttribute('height'));
// Important these are in the same order as the classes above
let locations = [
[0, 0],
[width / 2, 0],
[width, 0],
[0, height / 2],
[width, height / 2],
[0, height],
[width / 2, height],
[width, height]
];
// Move each location such that it's relative to the (x,y) of the rect,
// and also subtract half the width of the handles to make up for their
// own size.
locations = locations.map(subarr => [
subarr[0] + x - 4,
subarr[1] + y - 4
]);
for (let i = 0; i < locations.length; i++) {
h[i].setAttribute('x', locations[i][0]);
h[i].setAttribute('y', locations[i][1]);
}
}
interact('.resize-me')
.resizable({
edges: {
left: '.resize-left',
right: '.resize-right',
bottom: '.resize-bottom',
top: '.resize-top'
}
})
.on('resizemove', function(event) {
// Resize the rect, not the group, it will resize automatically
const target = event.target.querySelector('rect');
for (const attr of ['width', 'height']) {
let v = Number(target.getAttribute(attr));
v += event.deltaRect[attr];
target.setAttribute(attr, v);
}
for (const attr of ['top', 'left']) {
const a = attr == 'left' ? 'x' : 'y';
let v = Number(target.getAttribute(a));
v += event.deltaRect[attr];
target.setAttribute(a, v);
}
findLocations(rect, handles);
});
findLocations(rect, handles);
svg {
width: 100%;
height: 240px;
background-color: #2e9;
-ms-touch-action: none;
touch-action: none;
}
body {
margin: 0;
}
<script src="https://cdn.jsdelivr.net/npm/interactjs#latest/dist/interact.min.js"></script>
<svg id="mysvg"></svg>
This works by taking advantage of Interact.js's support for using separate elements as handles, as mentioned in their docs here, as well as the nifty fact that you're using SVG instead of HTML. This means that you don't have to worry about using a CSS transform. Instead, you can just move the rect's x and y, and the calculations become quite a bit simpler.
The only easy-to-miss change I had to make was that I had to put the rectangle and the handles into a group. This is because Interact.js will only let you use a child element as a handle for resizing. This means the listener is on the group, which resizes the rectangle within itself (and then, of course, causes the group to grow, since they match the size of their children).
Let me know if I've missed anything.

Related

Calculate % position of the group in fabric js

I am stuck in a problem, don't know if this is related to the current thread.
I have created a rectangle inside the canvas like this:
The grey part is the canvas there is a small rectangle inside. This is the code I have written:
// THIS METHOD WHEN THE COMPONENT IS INITIALIZED
// THAT IS VERY FIRST TIME
// htmlCanvas = Canvas from HTML file
initCanvas(htmlCanvas) {
this.mockupDrawableAreaCanvasSize = size;
this.mainCanvasDivRef = htmlCanvas;
fabric.textureSize = 4096;
fabric.charWidthsCache = {};
fabric.Object.prototype.borderScaleFactor = 2;
fabric.Object.prototype.objectCaching = false;
fabric.Object.prototype.noScaleCache = true;
fabric.Object.prototype.lockScalingFlip = true;
fabric.Object.prototype.hasRotatingPoint = true;
fabric.Object.prototype.transparentCorners = false;
fabric.Object.prototype.cornerColor = "rgb(255,255,255)";
fabric.Object.prototype.cornerSize = 8;
fabric.Object.prototype.cornerStrokeColor = "#48B774";
fabric.Object.prototype.borderColor = "#48B774";
fabric.Object.prototype.fill = "#FFFFFF";
fabric.Object.prototype.cornerStyle = "rect";
fabric.Object.prototype.borderOpacityWhenMoving = .5;
fabric.Object.prototype.snapAngle = 90;
fabric.Object.prototype.snapThreshold = 5;
fabric.Object.prototype.charWidthsCache = {};
this.canvas = new fabric.Canvas(htmlCanvas.nativeElement, this.defaultOption);
this.canvas.backgroundColor = '#e8e8e8';
this.canvas.uniScaleTransform = true;
this.canvas.requestRenderAll()
// -------
const {
width,
height
} = this.getDimensions();
this.drawingBoard = new fabric.Rect({
excludeFromExport: false,
hasControls: false,
height,
selectable: false,
borderColor: "transparent",
strokeWidth: 0,
stroke: 'transparent',
fill: '#ffffff',
width,
preserveObjectStacking: false,
absolutePositioned: true,
clip_id: 'io_main_canvas',
originX: 'center',
originY: 'center',
lockUniScaling: true,
});
}
// Here mockupDrawableAreaCanvasSize = {width: 1080, height: 1080}
getDimensions() {
let containerWidth: any = parseInt(this.mockupDrawableAreaCanvasSize.width, 10);
let containerHeight: any = parseInt(this.mockupDrawableAreaCanvasSize.height, 10);
const footer: any = document.querySelector('.footer-toolbar');
const container = document.querySelector('.upper-canvas');
const lowerCanvasEl = container && window.getComputedStyle(container, null);
let canvasHeight = parseInt(lowerCanvasEl.height, 10) - 1.5 * parseInt(footer.offsetHeight, 10);
const canvasWidth = parseInt(lowerCanvasEl.width, 10);
// Complete fit
if (containerWidth <= canvasWidth && containerHeight <= canvasHeight) {
return {
width: containerWidth,
height: containerHeight
}
}
if (canvasWidth < containerWidth) {
containerWidth = canvasWidth - 80;
canvasHeight = (containerWidth / (containerWidth / containerHeight)) - 6 * parseInt(footer.offsetHeight, 10)
}
let width = (containerWidth / containerHeight) * canvasHeight;
return {
width,
height: canvasHeight
}
}
This code works well in every use case. I want to position the objects at the same place where they were initially in the bigger or smaller screens.
My approach was:
Group everything, Add the group to canvas, calculate the percentage, scale and finally ungroup
But the objects are very small as shown in the below picture
How should I scale the object so that the whole content is a perfect fit in the group?
Group everything -> done
calculate % position of the group -> done
scale the group by ratio -> how?
-->>> The ratio between which values- group and canvas or group and drawing board?
apply for the same % position -->done
Ungroup --> done
I found many issues with the approach I was trying to implement. Now instead od repositionin, grouping, etc.I am zooming the canvas

Zooming in D3 v4 on a globe

I'm looking for a way to zoom from place to place on a globe in D3 v4 (v4 is important). What I'm looking for is basically exactly this: https://www.jasondavies.com/maps/zoom/ My problem is that Jason Davies obfuscated his code, so I can't read it, and I can't find a bl.ock containing that project or anything similar to it. I'll provide a link to what I've got here: http://plnkr.co/edit/0mjyR3ovTfkDXB8FTG0j?p=preview
The relevant is probably inside the .tween():
.tween("rotate", function () {
var p = d3.geoCentroid(points[i]),
r = d3.geoInterpolate(projection.rotate(), [-p[0], -p[1]]);
return function (t) {
projection.rotate(r(t));
convertedLongLats = [projection(points[0].coordinates), projection(points[1].coordinates)]
c.clearRect(0, 0, width, height);
c.fillStyle = colorGlobe, c.beginPath(), path(sphere), c.fill();
c.fillStyle = colorLand, c.beginPath(), path(land), c.fill();
for (var j = 0; j < points.length; j++) {
var textCoords = projection(points[j].coordinates);
c.fillStyle = textColors, c.textAlign = "center", c.font = "18px FontAwesome", c.fillText(points[j].icon, textCoords[0], textCoords[1]);
textCoords[0] += 15;
c.textAlign = "left", c.font = " 12px Roboto", c.fillText(points[j].location, textCoords[0], textCoords[1]);
}
c.strokeStyle = textColors, c.lineWidth = 4, c.setLineDash([10, 10]), c.beginPath(), c.moveTo(convertedLongLats[0][0], convertedLongLats[0][1]), c.lineTo(convertedLongLats[1][0], convertedLongLats[1][1]), c.stroke();
};
})
Basically, I want what I've got now but I want it to zoom in, pretty much exactly like it is in the Animated World Zoom example I provided above. I'm not really looking for code, I'd rather someone point me in the right direction with an example or something (it's worth noting that I'm fairly new to d3 and that this project is heavily based on World Tour by mbostock, so it uses canvas). Thank you all in advance!
Based on your plunker and comment, a challenge in zooming out between two points in a transition is that the interpolator will only interpolate between two values. The solution in your plunker relies on two interpolators, one for zooming in and zooming out. This method has added un-needed complexity and somewhere along the line, as you note, it jumps to an incorrect scale. You could simplify this:
Take an interpolator that interpolates between -1 and 1, and weight each scale according to the absolute value of the interpolator. At zero, the zoom should be out all the way, while at -1,1, you should be zoomed in:
var s = d3.interpolate(-1,1);
// get the appropriate scale:
scale = Math.abs(0-s(t))*startEndScale + (1-Mat.abs(0-s(t)))*middleScale
This is a little clunky as it goes from zooming out to zooming in rather abruptly, so you could ease it with a sine type easing:
var s = d3.interpolate(0.0000001,Math.PI);
// get the appropriate scale:
scale = (1-Math.abs(Math.sin(s(t))))*startEndScale + Math.abs(Math.sin(s(t)))*middleScale
I've applied this to your plunker here.
For a simple and minimal example using the example that I suggested and your two points and path (and using your plunkr as a base), stripping out the animated line and icons, I would probably put together something like (plunker, snippet below best viewed on full screen):
var width = 600,
height = 600;
var points = [{
type: "Point",
coordinates: [-74.2582011, 40.7058316],
location: "Your Location",
icon: "\uF015"
}, {
type: "Point",
coordinates: [34.8887969, 32.4406351],
location: "Caribe Royale Orlando",
icon: "\uF236"
}];
var canvas = d3.select("body").append("canvas")
.attr("width", width)
.attr("height", height);
var c = canvas.node().getContext("2d");
var point = points[0].coordinates;
var projection = d3.geoOrthographic()
.translate([width / 2, height / 2])
.scale(width / 2)
.clipAngle(90)
.precision(0.6)
.rotate([-point[0], -point[1]]);
var path = d3.geoPath()
.projection(projection)
.context(c);
var colorLand = "#4d4f51",
colorGlobe = "#2e3133",
textColors = "#fff";
d3.json("https://unpkg.com/world-atlas#1/world/110m.json", function (error, world) {
if (error) throw error;
var sphere = { type: "Sphere" };
var land = topojson.feature(world, world.objects.land);
var i = 0;
var scaleMiddle = width/2;
var scaleStartEnd = width * 2;
loop();
function loop() {
d3.transition()
.tween("rotate",function() {
var flightPath = {
type: 'Feature',
geometry: {
type: "LineString",
coordinates: [points[i++%2].coordinates, points[i%2].coordinates]
}
};
// next point:
var p = points[i%2].coordinates;
// current rotation:
var currentRotation = projection.rotate();
// next rotation:
var nextRotation = projection.rotate([-p[0],-p[1]]).rotate();
// Interpolaters:
var r = d3.geoInterpolate(currentRotation,nextRotation);
var s = d3.interpolate(0.0000001,Math.PI);
return function(t) {
// apply interpolated values
projection.rotate(r(t))
.scale( (1-Math.abs(Math.sin(s(t))))*scaleStartEnd + Math.abs(Math.sin(s(t)))*scaleMiddle ) ;
c.clearRect(0, 0, width, height);
c.fillStyle = colorGlobe, c.beginPath(), path(sphere), c.fill();
c.fillStyle = colorLand, c.beginPath(), path(land), c.fill();
c.beginPath(), path(flightPath), c.globalAlpha = 0.5, c.shadowColor = "#fff", c.shadowBlur = 5, c.lineWidth = 0.5, c.strokeStyle = "#fff", c.stroke(), c.shadowBlur = 0, c.globalAlpha = 1;
}
})
.duration(3000)
.on("end", function() { loop(); })
}
});
<script src="http://d3js.org/d3.v4.min.js"></script>
<script src="http://d3js.org/topojson.v1.min.js"></script>

FabricJS Clipping and SVG Export

I have a small fabricjs scene which loads images and clips them to SVG shapes that are defined in an SVG layout. The clipping is done using the code that is specified in this stack.
I have two issues:
When I export to SVG (see the "export to SVG" button), the clipping does not persist. Is this possible, perhaps to export to SVG maybe by converting the clippings to in SVG?
I have a SVG string inside the let clippingSVG variable. Is it possible to apply this SVG as another clipPath for the complete canvas (including export possibility), or the group of images?
Thanks in advance
This is rough implementation of top of the other answer that propose a toSVG method change to make clip ( fixed ) respected in toSVG.
The non fixed case is harder, i hope this helps.
var img01URL = 'http://fabricjs.com/assets/printio.png';
var img02URL = 'http://fabricjs.com/lib/pug.jpg';
var img03URL = 'http://fabricjs.com/assets/ladybug.png';
var img03URL = 'http://fabricjs.com/assets/ladybug.png';
function toSvg() {
document.getElementById('svg').innerHTML = canvas.toSVG();
}
fabric.Image.prototype.toSVG = function(reviver) {
var markup = this._createBaseSVGMarkup(), x = -this.width / 2, y = -this.height / 2, clipUrl = '';
if (this.clipPath) {
var id = fabric.Object.__uid++;
if (this.clipPath.fixed) {
markup.push('<clipPath id="myClip' + id + '">\n',
this.clipPath.toSVG(reviver),
'</clipPath>\n');
}
clipUrl = ' clip-path="url(#myClip' + id + ')" ';
}
markup.push('<g ', clipUrl, '>',
'<g transform="', this.getSvgTransform(), this.getSvgTransformMatrix(), '"', '>\n',
'\t<image ', this.getSvgId(), 'xlink:href="', this.getSvgSrc(true),
'" x="', x, '" y="', y,
'" style="', this.getSvgStyles(),
// we're essentially moving origin of transformation from top/left corner to the center of the shape
// by wrapping it in container <g> element with actual transformation, then offsetting object to the top/left
// so that object's center aligns with container's left/top
'" width="', this.width,
'" height="', this.height,
'"></image>\n'
);
if (this.stroke || this.strokeDashArray) {
var origFill = this.fill;
this.fill = null;
markup.push(
'<rect ',
'x="', x, '" y="', y,
'" width="', this.width, '" height="', this.height,
'" style="', this.getSvgStyles(),
'"/>\n'
);
this.fill = origFill;
}
markup.push('</g></g>\n');
return reviver ? reviver(markup.join('')) : markup.join('');
};
fabric.Image.prototype._render = function(ctx) {
// custom clip code
if (this.clipPath) {
ctx.save();
if (this.clipPath.fixed) {
var retina = this.canvas.getRetinaScaling();
ctx.setTransform(retina, 0, 0, retina, 0, 0);
// to handle zoom
ctx.transform.apply(ctx, this.canvas.viewportTransform);
//
this.clipPath.transform(ctx);
}
this.clipPath._render(ctx);
ctx.restore();
ctx.clip();
}
// end custom clip code
var x = -this.width / 2, y = -this.height / 2, elementToDraw;
if (this.isMoving === false && this.resizeFilter && this._needsResize()) {
this._lastScaleX = this.scaleX;
this._lastScaleY = this.scaleY;
this.applyResizeFilters();
}
elementToDraw = this._element;
elementToDraw && ctx.drawImage(elementToDraw,
0, 0, this.width, this.height,
x, y, this.width, this.height);
this._stroke(ctx);
this._renderStroke(ctx);
};
var canvas = new fabric.Canvas('c');
canvas.setZoom(0.5)
fabric.Image.fromURL(img01URL, function(oImg) {
oImg.scale(.25);
oImg.left = 10;
oImg.top = 10;
oImg.clipPath = new fabric.Circle({radius: 40, top: 50, left: 50, fixed: true, fill: '', stroke: '' });
canvas.add(oImg);
canvas.renderAll();
});
fabric.Image.fromURL(img02URL, function(oImg) {
oImg.scale(.40);
oImg.left = 180;
oImg.top = 0;
oImg.clipPath = new fabric.Path('M85.6,606.2c-13.2,54.5-3.9,95.7,23.3,130.7c27.2,35-3.1,55.2-25.7,66.1C60.7,814,52.2,821,50.6,836.5c-1.6,15.6,19.5,76.3,29.6,86.4c10.1,10.1,32.7,31.9,47.5,54.5c14.8,22.6,34.2,7.8,34.2,7.8c14,10.9,28,0,28,0c24.9,11.7,39.7-4.7,39.7-4.7c12.4-14.8-14-30.3-14-30.3c-16.3-28.8-28.8-5.4-33.5-11.7s-8.6-7-33.5-35.8c-24.9-28.8,39.7-19.5,62.2-24.9c22.6-5.4,65.4-34.2,65.4-34.2c0,34.2,11.7,28.8,28.8,46.7c17.1,17.9,24.9,29.6,47.5,38.9c22.6,9.3,33.5,7.8,53.7,21c20.2,13.2,62.2,10.9,62.2,10.9c18.7,6.2,36.6,0,36.6,0c45.1,0,26.5-15.6,10.1-36.6c-16.3-21-49-3.1-63.8-13.2c-14.8-10.1-51.4-25.7-70-36.6c-18.7-10.9,0-30.3,0-48.2c0-17.9,14-31.9,14-31.9h72.4c0,0,56-3.9,70.8,26.5c14.8,30.3,37.3,36.6,38.1,52.9c0.8,16.3-13.2,17.9-13.2,17.9c-31.1-8.6-31.9,41.2-31.9,41.2c38.1,50.6,112-21,112-21c85.6-7.8,79.4-133.8,79.4-133.8c17.1-12.4,44.4-45.1,62.2-74.7c17.9-29.6,68.5-52.1,113.6-30.3c45.1,21.8,52.9-14.8,52.9-14.8c15.6,2.3,20.2-17.9,20.2-17.9c20.2-22.6-15.6-28-16.3-84c-0.8-56-47.5-66.1-45.1-82.5c2.3-16.3,49.8-68.5,38.1-63.8c-10.2,4.1-53,25.3-63.7,30.7c-0.4-1.4-1.1-3.4-2.5-6.6c-6.2-14-74.7,30.3-74.7,30.3s-108.5,64.2-129.6,68.9c-21,4.7-18.7-9.3-44.3-7c-25.7,2.3-38.5,4.7-154.1-44.4c-115.6-49-326,29.8-326,29.8s-168.1-267.9-28-383.4C265.8,13,78.4-83.3,32.9,168.8C-12.6,420.9,98.9,551.7,85.6,606.2z',{top: 0, left: 180, fixed: true, fill: '', stroke: '', scaleX: 0.2, scaleY: 0.2 });
canvas.add(oImg);
canvas.renderAll();
});
#c {
border:1px solid #ccc;
}
<script src="//cdnjs.cloudflare.com/ajax/libs/fabric.js/1.7.17/fabric.min.js"></script>
<button onClick='toSvg();'>TOSVG</button>
<canvas id="c" width="400" height="400"></canvas>
<div id="svg"></div>
Thank you AndreaBogazzi for starting me off on the right foot. I'd prefer to use a subclass of fabric.Image rather than replace a couple of its prototype methods. Cut-and-paste can be dangerous; in fact, the newest version of fabricjs is already incompatible with the that solution. So, here's a subclass version of the same solution. In my case I'm always using a fixed clipPath so I removed all references to fixed.
const ClippedImage = fabric.util.createClass(fabric.Image, {
type: 'ClippedImage',
initialized: function(options) {
options || (options = {})
this.callSuper('initialize', options)
},
_render: function(ctx) {
if (this.clipPath) {
ctx.save()
var retina = this.canvas.getRetinaScaling()
ctx.setTransform(retina, 0, 0, retina, 0, 0)
ctx.transform.apply(ctx, this.canvas.viewportTransform)
this.clipPath.transform(ctx)
this.clipPath._render(ctx)
ctx.restore()
ctx.clip()
}
this.callSuper('_render', ctx)
},
toSVG: function(reviver) {
let result = this.callSuper('toSVG')
if(this.clipPath) {
const clipId = `Clipped${fabric.Object.__uid++}`
result = `
<clipPath id="${clipId}">
${this.clipPath.toSVG(reviver)}
</clipPath>
<g clip-path="url(#${clipId})">${result}</g>`
}
return reviver ? reviver(result) : result
}
})

Dynamically flexible path between two points in SVG

Hi can some one help me bend path like here
here u can see it in action (it's almost what i need, but it on canvas)
QUESTION
how i can calculate it?
which formula describes this
and how correctly to describe the parameters 'd' of path
here's my code (maybe it needs some improvements?)
var app = angular.module('app', []);
app.controller("ctrl", function ($scope) {
var lineGraph = d3.select("#container").append("svg:svg").attr("width", '100%').attr("height", '100%');
$scope.linesArr = [];
$scope.blocksArr = [{
id: 0,
x: 0,
y: 0,
lineToID: [2]
},{
id: 1,
x: 0,
y: 0,
lineToID: [0,2]
},{
id: 2,
x: 0,
y: 0,
lineToID: []
}];
$scope.createLines = function(){
for(var i = 0; i < $scope.blocksArr.length; i++){
if($scope.blocksArr[i].lineToID.length){
for(var j = 0; j < $scope.blocksArr[i].lineToID.length; j++){
$scope.linesArr[$scope.blocksArr[i].id + ":"+j] = (lineGraph.append("svg:line"));
}
}
}
};
$scope.createLines();
$scope.checkPoints = function(){
for(var i = 0; i < $scope.blocksArr.length; i++){
$scope.blocksArr[i].x = parseInt(document.querySelector('#b' + i).style.left) + (document.querySelector('#b' + i).offsetWidth / 2);
$scope.blocksArr[i].y = parseInt(document.querySelector('#b' + i).style.top) + (document.querySelector('#b' + i).offsetHeight / 2);
if($scope.blocksArr[i].lineToID.length){
for(var j = 0; j < $scope.blocksArr[i].lineToID.length; j++){
$scope.linesArr[$scope.blocksArr[i].id+":"+j]
.attr("x1", $scope.blocksArr[$scope.blocksArr[i].id].x)
.attr("y1", $scope.blocksArr[$scope.blocksArr[i].id].y)
.attr("x2", $scope.blocksArr[$scope.blocksArr[i].lineToID[j]].x)
.attr("y2", $scope.blocksArr[$scope.blocksArr[i].lineToID[j]].y)
.style("stroke", "rgb(6,120,155)");
//console.log();
}
}
}
};
$scope.dragOptions = {
start: function(e) {
//console.log("STARTING");
},
drag: function(e) {
$scope.checkPoints();
//console.log("DRAGGING");
},
stop: function(e) {
//console.log("STOPPING");
},
container: 'container'
}
});
app.directive('ngDraggable', function($document) {
return {
restrict: 'A',
scope: {
dragOptions: '=ngDraggable'
},
link: function(scope, elem, attr) {
var startX, startY, x = 0, y = 0,
start, stop, drag, container;
var width = elem[0].offsetWidth,
height = elem[0].offsetHeight;
// Obtain drag options
if (scope.dragOptions) {
start = scope.dragOptions.start;
drag = scope.dragOptions.drag;
stop = scope.dragOptions.stop;
var id = scope.dragOptions.container;
if (id) {
container = document.getElementById(id).getBoundingClientRect();
}
}
// Bind mousedown event
elem.on('mousedown', function(e) {
e.preventDefault();
startX = e.clientX - elem[0].offsetLeft;
startY = e.clientY - elem[0].offsetTop;
$document.on('mousemove', mousemove);
$document.on('mouseup', mouseup);
if (start) start(e);
});
// Handle drag event
function mousemove(e) {
y = e.clientY - startY;
x = e.clientX - startX;
setPosition();
if (drag) drag(e);
}
// Unbind drag events
function mouseup(e) {
$document.unbind('mousemove', mousemove);
$document.unbind('mouseup', mouseup);
if (stop) stop(e);
}
// Move element, within container if provided
function setPosition() {
if (container) {
if (x < container.left) {
x = container.left;
} else if (x > container.right - width) {
x = container.right - width;
}
if (y < container.top) {
y = container.top;
} else if (y > container.bottom - height) {
y = container.bottom - height;
}
}
elem.css({
top: y + 'px',
left: x + 'px'
});
}
}
}
})
html,body, #container{
height: 100%;
margin: 0;
}
.box{
position: absolute;
width: 100px;
height: 30px;
line-height: 30px;
border: 1px solid #c07f7f;
text-align: center;
background: #f3f4ff;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div ng-controller="ctrl" ng-app="app" id="container">
<div class="box" id="b{{$index}}" ng-repeat="i in blocksArr" ng-draggable='dragOptions' ng-style="{top: blocksArr[$index].y, left: blocksArr[$index].x}">{{$index}}</div>
</div>
Guessing, I'm thinking that what you want is to:
Show two points on screen.
Calculate an axis-aligned right triangle that touches those points.
Draw a triangle for the fill and colored lines for the edges of the triangles.
Allow the user to use the mouse to click and drag the points to new locations.
Dynamically update the right triangle based on those points.
It is unclear which part of the above you are having trouble with (other than, perhaps, "all of it"). In general, computer programming is about identifying what you want to do, breaking it down into simple steps (as I did above) and then working on those steps one at a time.
Can you calculate two 'random' points on screen? (Hint: Math.random() might be appropriate, or else you can just pick two fixed starting locations.)
Can you draw two points on screen? (Hint: You can use a SVG <circle> and adjust the cx and cy attributes.)
Can you calculate where the third point should be? (Hint: one way is to use the 'x' value of one point and the 'y' value of the other point.)
Can you draw a filled triangle between these points? (Hint: an easy way is to use an SVG <polygon> and adjust the points attribute.)
Can you draw three lines for the edges? (Hint: use <line> or <polyline> elements that are later in the document than the <polygon> so that they draw on top...but have the <circle> elements even lower in the document so that the circles draw on top of everything else.)
Can you make it so that when the user clicks and drags on the circles they stay under the mouse? (Hint: see this answer and example of mine, or go Google about making SVG elements draggable.)
During your drag handler, can you recalculate your triangle and points and lines and update them all? (Hint: you can either use setAttribute() to update attributes of SVG elements, e.g. setAttribute(myPoly,'points',arrayOfPoints.join()), or you can use SVG DOM bindings—e.g. myPoly.getItem(0).x = 43.)
Your question is too broad and vague currently. Either edit this question to make it specific to your exact desire and the exact code that is not working for you, or create a new question that is similarly targeted. Your code snippet does basically nothing useful for all the code you have in there.

Animating SVG polygons

I wrote a code to drawing polygons:
var svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
svg.setAttribute('width', '100%');
svg.setAttribute('height', window.innerHeight);
document.querySelector('#bg').appendChild(svg);
for(var x = 0; x < polygons.length; x++){
var polygon = document.createElementNS(svg.namespaceURI, 'polygon');
polygon.setAttribute('points', polygons[0 + x]);
polygon.setAttribute('fill', polygons[0 + x][1]);
svg.appendChild(polygon);
}
My full code with polygon points:
http://codepen.io/anon/pen/WrqrbB
I would like to animate this polygons similar to this animation:
http://codepen.io/zessx/pen/ZGBMXZ
How to animate my polygons?
You can
call an animation function to manipulate your coordinate values as desired,
convert them to a string, e.g. using .join(),
send the resulting string back to the polygon as its points attribute value, redrawing the shape (as you were already doing when you initially created your shapes), and
have the animation function, when it is finished, call itself again at a reasonable built-in time-delay using requestAnimationFrame.
The following snippet gives a basic idea of what can be done.
(Note that I've redefined the array polygons in my example so that it is different from what you had, but that was done for the sake of simplicity in this example.)
var svg = document.getElementsByTagName("svg")[0];
var polygons = [], numSteps = 100, stepNum = 0;
var coords = [
[40, 20, 80, 20, 80, 60, 40, 60],
[140, 20, 180, 20, 160, 50]
];
for (var x = 0; x < coords.length; x++) {
polygons[x] = document.createElementNS(svg.namespaceURI, 'polygon');
polygons[x].setAttribute('points', coords[x].join());
svg.appendChild(polygons[x]);
}
function anim() {
for (var x = 0; x < coords.length; x++) {
coords[x] = coords[x].map(function(coord) {
return coord + 4 * (Math.random() - 0.5);
});
polygons[x].setAttribute('points', coords[x].join());
stepNum += 1;
}
if (stepNum < numSteps) requestAnimationFrame(anim);
}
anim();
<svg></svg>
UPDATE The above snippet shows generally how to animate a polygon. In your case, however, there is a further issue. On your codepen demo, it is clear that you have hard-coded the point coordinates for each polygon separately. Thus, if you want to move one point, you're going to have to update coordinates in at least 2 if not more places, for every polygon that touches that point.
A better approach would be to create a separate array of all points and then define each polygon with respect to that array. (This is similar to how things are sometimes done in 3D graphics, e.g. WebGL.) The following code snippet demonstrates this approach.
var svg = document.getElementsByTagName("svg")[0];
var polyElems = [], numSteps = 100, stepNum = 0;
var pts = [[120,20], [160,20], [200,20], [240,20], [100,50], [140,50], [180,50], [220,50], [260,50], [120,80], [160,80], [200,80], [240,80]];
var polyPts = [[0,1,5], [1,2,6], [2,3,7], [0,4,5], [1,5,6], [2,6,7], [3,7,8], [4,5,9], [5,6,10], [6,7,11], [7,8,12], [5,9,10], [6,10,11], [7,11,12]];
for (var x = 0; x < polyPts.length; x++) {
polyElems[x] = document.createElementNS(svg.namespaceURI, 'polygon');
polyElems[x].setAttribute('fill', '#'+Math.floor(Math.random()*16777215).toString(16));
// random hex color routine from http://www.paulirish.com/2009/random-hex-color-code-snippets/
drawPolygon(x);
}
function anim() {
pts = pts.map(function(pt) {
return pt.map(function(coord) {
return coord + 3 * (Math.random() - 0.5); // move each point
});
});
for (var x = 0; x < polyPts.length; x++) {drawPolygon(x);}
stepNum += 1;
if (stepNum < numSteps) requestAnimationFrame(anim); // redo anim'n until all anim'n steps done
}
anim(); // start the animation
function drawPolygon(x) {
var ptNums = polyPts[x];
var currCoords = [pts[ptNums[0]], pts[ptNums[1]], pts[ptNums[2]]].join();
// creates a string of coordinates; note that [[1,2],[3,4],[5,6]].join() yields "1,2,3,4,5,6"
polyElems[x].setAttribute('points', currCoords);
svg.appendChild(polyElems[x]);
}
<svg></svg>

Categories