Raphael JS rotate group/set not individually - svg

I've been toying around with Raphael JS, but failed to find any solution to rotate a group/set of paths as group, and not individually.
A group/set of path:
Each element is rotated. Not the entire group/set:
How I do:
var bobble = map.paper.set();
bobble.push(map.paper.add([{
"fill":fill,
"stroke":"none",
x: 50,
y: 50,
width: 100,
height: 100,
"type":"rect",
"r": 4
},{
"fill":fill,
"stroke":"none",
x: 100,
y: 25,
width: 200,
height: 50,
"type":"rect",
"r": 4
}]));
bobble.rotate(45);
What am I doing wrong?

Here you go DEMO
var paper = Raphael('arrows');
var r1 = paper.rect(100,100,200,10,5).attr({fill:'white'});
var r2 = paper.rect(50,200,100,15,5).attr({fill:'white'});
var st = paper.set(r1,r2);
var l_coord = st.getBBox().x,
r_coord = st.getBBox().x2,
t_coord = st.getBBox().y,
b_coord = st.getBBox().y2;
var cx = (l_coord + r_coord)/2,
cy = (t_coord + b_coord)/2;
st.rotate(54,cx,cy);
Since you need to get your Raphael set's center coordinates, you can use getBBox() function which returns you:

The set of raphaeljs is a list of element. So, when you use tranform method, it is just a transform of unique element of list in the set.
I had created an plugin which supports g tag for my project. But I haven't yet implement the transform method.
const SVG = 'http://www.w3.org/2000/svg';
function TCRaphael(container, width, height) {
var paper = new Raphael(container, width, height);
paper.node = document.getElementById(container).getElementsByTagName("svg")[0];
console.log(paper.node)
paper.group = function (parent) {
return new Group(parent);
};
function Group(parent) {
var me = this;
this.node = document.createElementNS(SVG, "g");
if (typeof parent !== 'undefined') {
if (typeof parent.node != 'undefined')
parent.node.appendChild(me.node);
else{
parent.appendChild(me.node);
}
}
this.append = function (child) {
me.node.appendChild(child.node);
return child;
};
this.appendNode = function (childNode) {
me.node.appendChild(childNode);
};
this.appendTo = function (parent) {
if (typeof parent !== 'undefined') {
if (typeof parent.node != 'undefined')
parent.node.appendChild(me.node);
else{
parent.appendChild(me.node);
}
}
};
this.remove = function(){
me.node.parentNode.remove();
};
this.circle = function(x, y, r){
return me.append(paper.circle(x, y, r));
};
this.ellipse =function(x, y, rx, ry){
return me.append(paper.ellipse(x, y, rx, ry));
};
this.image = function(src, x, y, width, height){
return me.append(paper.image(src, x, y, width, height));
};
this.path = function(pathString){
return me.append(paper.path(pathString));
};
this.rect = function(x, y, width, height, r){
return me.append(paper.rect(x, y, width, height, r));
};
this.text = function(x, y, text){
return me.append(paper.text(x, y, text));
}
}
return paper;
}
You can add more function which you want to TCRaphael.

I think it's a little easier.
myset.transform("R45,20,20")
does exactly the same as
myset.rotate(45,20,20) // deprecated
the whole myset will rotate around the center at 20,20 (maybe the center of the set)
otherwise
myset.transform("R45")
will rotate each element of the set around it's own center

Related

How to rotate cubee by quaternion in three.js?

I have some problems with understanding of how to rotate the figure by a quaternion. Can somebody please explain how to do it? In function render I want to rotate cubes by quaternions
function main() {
const canvas = document.querySelector('#c');
const renderer = new THREE.WebGLRenderer({canvas});
const fov = 100;
const aspect = 2; // the canvas default
const near = 0.1;
const far = 5;
const camera = new THREE.PerspectiveCamera(fov, aspect, near, far);
camera.position.z = 3;
const scene = new THREE.Scene();
{
const color = 0xFFFFFF;
const intensity = 1;
const light = new THREE.DirectionalLight(color, intensity);
light.position.set(-1, 2, 4);
scene.add(light);
}
function makeInstance(color, x, width, height, depth) {
const material = new THREE.MeshPhongMaterial({color});
const geometry = new THREE.BoxGeometry(width, height, depth);
const cube = new THREE.Mesh(geometry, material);
scene.add(cube);
cube.position.x = x;
return cube;
}
const cubes = [
makeInstance(0x8844aa, -2, 3, 1, 1),
makeInstance(0xaa8844, 0.5, 2, 1, 1),
];
function resizeRendererToDisplaySize(renderer) {
const canvas = renderer.domElement;
const width = canvas.clientWidth;
const height = canvas.clientHeight;
const needResize = canvas.width !== width || canvas.height !== height;
if (needResize) {
renderer.setSize(width, height, false);
}
return needResize;
}
function render(time) {
time *= 0.001;
if (resizeRendererToDisplaySize(renderer)) {
const canvas = renderer.domElement;
camera.aspect = canvas.clientWidth / canvas.clientHeight;
camera.updateProjectionMatrix();
}
// cubes.forEach((cube, ndx) => {
//const speed = 1 + ndx * .1;
//const rot = time * speed;
//cube.rotation.x = rot;
//cube.rotation.y = rot;
//});
renderer.render(scene, camera);
requestAnimationFrame(render);
}
requestAnimationFrame(render);
}
main();
You have an Object3d (Points, Lines, Meshes, etc.) that you want to rotate via quaternions. You have a mesh (the cube). The immediate answer is to:
cube.applyQuaternion(myquat);
And where does myquat come from? Probably from one of these:
myquat = new THREE.Quaternion(); // now, Probably from one of these:
myquat.setFromAxisAngle ( axis : Vector3, angle : Float )
myquat.setFromEuler ( euler : Euler )
myquat.setFromRotationMatrix ( m : Matrix4 )
myquat.setFromUnitVectors ( vFrom : Vector3, vTo : Vector3 )
I hope this gives you a start, even to ask a more specific question.

javascript fabricjs - Adding an object to multiple canvases in a single click

I'm building an app that can design your own business card. I have to add an object to two canvases in a single click. Here are my codes:
$('#image-list').on('click','.image-option',function(e) {
var el = e.target;
/*temp code*/
var offset = 50;
var left = fabric.util.getRandomInt(0 + offset, 200 - offset);
var top = fabric.util.getRandomInt(0 + offset, 400 - offset);
var angle = fabric.util.getRandomInt(-20, 40);
var width = fabric.util.getRandomInt(30, 50);
var opacity = (function(min, max){ return Math.random() * (max - min) + min; })(0.5, 1);
var canvasObject;
// if ($('#flip').attr('data-facing') === 'front') {
// canvasObject = canvas;
// } else {
// canvasObject = canvas2;
// }
fabric.Image.fromURL(el.src, function(image) {
image.set({
left: left,
top: top,
angle: 0,
padding: 10,
cornersize: 10,
hasRotatingPoint:true
});
canvas.add(image);
canvas2.add(image);
});
})
The problem is, when I resized or move the image on the 'front canvas', it also renders the same way in the 'back canvas'. In my case, I don't want the object to be that way. So is there a way to prevent the obect 'mirroring' on the other canvas? Thanks.
You cannot add the same object to 2 canvases.
You have to create 2 objects.
Also take note that if you have an html image element on your page you do not need to load it from URL again. Is already loaded, so pass the image element to the constructor directly
$('#image-list').on('click','.image-option',function(e) {
var el = e.target;
/*temp code*/
var offset = 50;
var left = fabric.util.getRandomInt(0 + offset, 200 - offset);
var top = fabric.util.getRandomInt(0 + offset, 400 - offset);
var angle = fabric.util.getRandomInt(-20, 40);
var width = fabric.util.getRandomInt(30, 50);
var opacity = (function(min, max){ return Math.random() * (max - min) + min; })(0.5, 1);
var canvasObject;
// if ($('#flip').attr('data-facing') === 'front') {
// canvasObject = canvas;
// } else {
// canvasObject = canvas2;
// }
image = new fabric.Image(el, {
left: left,
top: top,
angle: 0,
padding: 10,
cornersize: 10,
hasRotatingPoint:true
});
image2 = new fabric.Image(el, {
left: left,
top: top,
angle: 0,
padding: 10,
cornersize: 10,
hasRotatingPoint:true
});
canvas.add(image);
canvas2.add(image2);
});
})

fabricJS Not persisting Floodfill

I have an algorithm for Floodfilling a canvas. Im trying to incorporate this with fabricJS. So here is the dilemna.... I create a fabric.Canvas(). Which creates a wrapper canvas and also an upper-canvas canvas. I click on the canvas to apply my Floodfill(). This works fine and applies my color. But as soon as i go to drag my canvas objects around, or add additional objects to the canvas, the color disappears and looks like it resets of sort.
Any idea why this is?
This happen because fabricjs wipe out all canvas every frame and redraw from its internal data.
I made a JSfiddle that implements Flood Fill for Fabric JS. Check it here: https://jsfiddle.net/av01d/dfvp9j2u/
/*
* FloodFill for fabric.js
* #author Arjan Haverkamp (av01d)
* #date October 2018
*/
var FloodFill = {
// Compare subsection of array1's values to array2's values, with an optional tolerance
withinTolerance: function(array1, offset, array2, tolerance)
{
var length = array2.length,
start = offset + length;
tolerance = tolerance || 0;
// Iterate (in reverse) the items being compared in each array, checking their values are
// within tolerance of each other
while(start-- && length--) {
if(Math.abs(array1[start] - array2[length]) > tolerance) {
return false;
}
}
return true;
},
// The actual flood fill implementation
fill: function(imageData, getPointOffsetFn, point, color, target, tolerance, width, height)
{
var directions = [[1, 0], [0, 1], [0, -1], [-1, 0]],
coords = [],
points = [point],
seen = {},
key,
x,
y,
offset,
i,
x2,
y2,
minX = -1,
maxX = -1,
minY = -1,
maxY = -1;
// Keep going while we have points to walk
while (!!(point = points.pop())) {
x = point.x;
y = point.y;
offset = getPointOffsetFn(x, y);
// Move to next point if this pixel isn't within tolerance of the color being filled
if (!FloodFill.withinTolerance(imageData, offset, target, tolerance)) {
continue;
}
if (x > maxX) { maxX = x; }
if (y > maxY) { maxY = y; }
if (x < minX || minX == -1) { minX = x; }
if (y < minY || minY == -1) { minY = y; }
// Update the pixel to the fill color and add neighbours onto stack to traverse
// the fill area
i = directions.length;
while (i--) {
// Use the same loop for setting RGBA as for checking the neighbouring pixels
if (i < 4) {
imageData[offset + i] = color[i];
coords[offset+i] = color[i];
}
// Get the new coordinate by adjusting x and y based on current step
x2 = x + directions[i][0];
y2 = y + directions[i][1];
key = x2 + ',' + y2;
// If new coordinate is out of bounds, or we've already added it, then skip to
// trying the next neighbour without adding this one
if (x2 < 0 || y2 < 0 || x2 >= width || y2 >= height || seen[key]) {
continue;
}
// Push neighbour onto points array to be processed, and tag as seen
points.push({ x: x2, y: y2 });
seen[key] = true;
}
}
return {
x: minX,
y: minY,
width: maxX-minX,
height: maxY-minY,
coords: coords
}
}
}; // End FloodFill
var fcanvas; // Fabric Canvas
var fillColor = '#f00';
var fillTolerance = 2;
function hexToRgb(hex, opacity) {
opacity = Math.round(opacity * 255) || 255;
hex = hex.replace('#', '');
var rgb = [], re = new RegExp('(.{' + hex.length/3 + '})', 'g');
hex.match(re).map(function(l) {
rgb.push(parseInt(hex.length % 2 ? l+l : l, 16));
});
return rgb.concat(opacity);
}
function floodFill(enable) {
if (!enable) {
fcanvas.off('mouse:down');
fcanvas.selection = true;
fcanvas.forEachObject(function(object){
object.selectable = true;
});
return;
}
fcanvas.deactivateAll().renderAll(); // Hide object handles!
fcanvas.selection = false;
fcanvas.forEachObject(function(object){
object.selectable = false;
});
fcanvas.on({
'mouse:down': function(e) {
var mouse = fcanvas.getPointer(e.e),
mouseX = Math.round(mouse.x), mouseY = Math.round(mouse.y),
canvas = fcanvas.lowerCanvasEl,
context = canvas.getContext('2d'),
parsedColor = hexToRgb(fillColor),
imageData = context.getImageData(0, 0, canvas.width, canvas.height),
getPointOffset = function(x,y) {
return 4 * (y * imageData.width + x)
},
targetOffset = getPointOffset(mouseX, mouseY),
target = imageData.data.slice(targetOffset, targetOffset + 4);
if (FloodFill.withinTolerance(target, 0, parsedColor, fillTolerance)) {
// Trying to fill something which is (essentially) the fill color
console.log('Ignore... same color')
return;
}
// Perform flood fill
var data = FloodFill.fill(
imageData.data,
getPointOffset,
{ x: mouseX, y: mouseY },
parsedColor,
target,
fillTolerance,
imageData.width,
imageData.height
);
if (0 == data.width || 0 == data.height) {
return;
}
var tmpCanvas = document.createElement('canvas'), tmpCtx = tmpCanvas.getContext('2d');
tmpCanvas.width = canvas.width;
tmpCanvas.height = canvas.height;
var palette = tmpCtx.getImageData(0, 0, tmpCanvas.width, tmpCanvas.height); // x, y, w, h
palette.data.set(new Uint8ClampedArray(data.coords)); // Assuming values 0..255, RGBA
tmpCtx.putImageData(palette, 0, 0); // Repost the data.
var imgData = tmpCtx.getImageData(data.x, data.y, data.width, data.height); // Get cropped image
tmpCanvas.width = data.width;
tmpCanvas.height = data.height;
tmpCtx.putImageData(imgData,0,0);
fcanvas.add(new fabric.Image(tmpCanvas, {
left: data.x,
top: data.y,
selectable: false
}))
}
});
}
$(function() {
// Init Fabric Canvas:
fcanvas = new fabric.Canvas('c', {
backgroundColor:'#fff',
enableRetinaScaling: false
});
// Add some demo-shapes:
fcanvas.add(new fabric.Circle({
radius: 80,
fill: false,
left: 100,
top: 100,
stroke: '#000',
strokeWidth: 2
}));
fcanvas.add(new fabric.Triangle({
width: 120,
height: 160,
left: 50,
top: 50,
stroke: '#000',
fill: '#00f',
strokeWidth: 2
}));
fcanvas.add(new fabric.Rect({
width: 120,
height: 160,
left: 150,
top: 50,
fill: 'red',
stroke: '#000',
strokeWidth: 2
}));
fcanvas.add(new fabric.Rect({
width: 200,
height: 120,
left: 200,
top: 120,
fill: 'green',
stroke: '#000',
strokeWidth: 2
}));
/* Images work very well too. Make sure they're CORS
enabled though! */
var img = new Image();
img.crossOrigin = 'anonymous';
img.onload = function() {
fcanvas.add(new fabric.Image(img, {
left: 300,
top: 100,
angle: 30,
}));
}
img.src = 'http://misc.avoid.org/chip.png';
});

Control z-index in Fabric.js

In fabricjs, I want to create a scene in which the object under the mouse rises to the top of the scene in z-index, then once the mouse leaves that object, it goes back to the z-index where it came from. One cannot set object.zindex (which would be nice). Instead, I'm using a placeholder object which is put into the object list at the old position, and then the old object is put back in the position where it was in the list using canvas.insertAt. However this is not working.
See http://jsfiddle.net/rFSEV/ for the status of this.
var canvasS = new fabric.Canvas('canvasS', { renderOnAddition: false, hoverCursor: 'pointer', selection: false });
var bars = {}; //storage for bars (bar number indexed by group object)
var selectedBar = null; //selected bar (group object)
var placeholder = new fabric.Text("XXXXX", { fontSize: 12 });
//pass null or a bar
function selectBar(bar) {
if (selectedBar) {
//remove the old topmost bar and put it back in the right zindex
//PROBLEM: It doesn't go back; it stays at the same zindex
selectedBar.remove();
canvasS.insertAt(selectedBar, selectedBar.XZIndex, true);
selectedBar = null;
}
if (bar) {
//put a placeholder object ("XXX" for now) in the position
//where the bar was, and put the bar in the top position
//so it shows topmost
selectedBar = bar;
canvasS.insertAt(placeholder, selectedBar.XZIndex, true);
canvasS.add(bar);
canvasS.renderAll();
}
}
canvasS.on({
'mouse:move': function(e) {
//hook up dynamic zorder
if (!e.target) return;
if (bars[e.target])
selectBar(e.target);
else
selectBar(null);
},
});
var objcount = canvasS.getObjects().length;
//create bars
for (var i = 0; i < 20; ++i) {
var rect = new fabric.Rect({
left: 0,
top: 0,
rx: 3,
ry: 3,
stroke: 'red',
width: 200,
height: 25
});
rect.setGradientFill({
x1: 0,
y1: 0,
x2: 0,
y2: rect.height,
colorStops: {
0: '#080',
1: '#fff'
}
});
var text = new fabric.Text("Bar number " + (i+1), {
fontSize: 12
});
var group = new fabric.Group([ rect, text ], {
left: i + 101,
top: i * 4 + 26
});
group.hasControls = group.hasBorders = false;
//our properties (not part of fabric)
group.XBar = rect;
group.XZIndex = objcount++;
canvasS.add(group);
bars[group] = i;
}
canvasS.renderAll();
Since fabric.js version 1.1.4 a new method for zIndex manipulation is available:
canvas.moveTo(object, index);
object.moveTo(index);
I think this is helpful for your use case. I've updated your jsfiddle - i hope this is what you want:
jsfiddle
Also make sure you change z-index AFTER adding object to canvas.
So code will looks like:
canvas.add(object);
canvas.moveTo(object, index);
Otherwise fabricjs don`t care about z-indexes you setup.
After I added a line object, I was make the line appear under the object using:
canvas.add(line);
canvas.sendToBack(line);
Other options are
canvas.sendBackwards
canvas.sendToBack
canvas.bringForward
canvas.bringToFront
see: https://github.com/fabricjs/fabric.js/issues/135
You can modify your _chooseObjectsToRender method to have the following change at the end of it, and you'll be able to achieve css-style zIndexing.
objsToRender = objsToRender.sort(function(a, b) {
var sortValue = 0, az = a.zIndex || 0, bz = b.zIndex || 0;
if (az < bz) {
sortValue = -1;
}
else if (az > bz) {
sortValue = 1;
}
return sortValue;
});
https://github.com/fabricjs/fabric.js/pull/5088/files
You can use these two functions to get z-index of a fabric object and modify an object's z-index, since there is not specific method to modify z-index by object index :
fabric.Object.prototype.getZIndex = function() {
return this.canvas.getObjects().indexOf(this);
}
fabric.Canvas.prototype.moveToLayer = function(object,position) {
while(object.getZIndex() > position) {
this.sendBackwards(object);
}
}

selecting multiple svg elements and dragging them in Raphael.js

Does anyone know how I can achieve this?
I basically have an svg document with multiple shapes,lines,text,etc... and I am trying to implement a selection tool which helps me select multiple elements, group them and drag them.
There is a feature in raphäel called set: http://raphaeljs.com/reference.html#set
You can add all the elements you want to drag around to a new set and then apply the dragging mechanism to the set.
I made you this: http://jsfiddle.net/Wrajf/
It's not perfect. I would add the mousemove event to the document, but for that you need a library like jQuery. Otherwise if you move the mouse to fast you have a fall out.
I did this (example here) :
EDIT : something cleaner
Create methods to set and retrieve the group of an element :
Raphael.el.setGroup = function (group) {
this.group = group;
};
Raphael.el.getGroup = function () {
return this.group;
};
Create the method of your grouped elements :
Raphael.fn.superRect = function (x, y, w, h, text) {
var background = this.rect(x, y, w, h).attr({
fill: "#FFF",
stroke: "#000",
"stroke-width": 1
});
var label = this.text(x+w/2,y+h/2, text);
var layer = this.rect(x, y, w, h).attr({
fill: "#FFF",
"fill-opacity": 0,
"stroke-opacity": 0,
cursor: "move"
});
var group = this.set();
group.push(background, label, layer);
layer.setGroup(group);
return layer;
};
create functions to drag a grouped elements :
var dragger = function () {
this.group = this.getGroup();
this.previousDx = 0;
this.previousDy = 0;
},
move = function (dx, dy) {
var txGroup = dx-this.previousDx;
var tyGroup = dy-this.previousDy;
this.group.translate(txGroup,tyGroup);
this.previousDx = dx;
this.previousDy = dy;
},
up = function () {};
Init SVG paper and create your elements (the order of element is important)::
window.onload = function() {
var paper = Raphael(0, 0,"100%", "100%");
var x=50, y=50, w=30, h=20;
paper.superRect(x, y, w, h, "abc").drag(move, dragger, up);
x +=100;
paper.superRect(x, y, w, h, "def").drag(move, dragger, up);
};

Resources