I'm creating a jQuery plugin that creates Raphael objects on the fly, let's say you do...
$("div").draw({
type: 'circle',
radius: '10',
color: '#000'
})
And the plugin code (just as an example):
$.fn.draw = function( options ) {
//settings/options stuff
var width = $(this).width();
var height = $(this).height();
var widget = Raphael($(this)[0], width, height);
var c = widget.circle(...).attr({...})
//saving the raphael reference in the element itself
$(this).data('raphael', {
circle : c
})
}
But then I'd like to be able to update elements like this:
$("div").draw({
type: 'update',
radius: '20',
color: '#fff'
});
I can "rescue" the object doing $(this).data().raphael.circle, but then it refuses to animate, I know it's a raphael object because it even has the animate proto , but it yields a Uncaught TypeError: Cannot read property '0' of undefined).
I tried out your code, made some modifications, and $(this).data().raphael.circle does animate. This is what I did (I know it's not exactly the same as yours, but gives the gist)
$.fn.draw = function( options ) {
//settings/options stuff
if(options.type === 'draw') {
var width = $(this).width();
var height = $(this).height();
var widget = Raphael($(this)[0], width, height);
var c = widget.circle(100, 100, 50);
//saving the raphael reference in the element itself
$(this).data('raphael', {
circle : c
});
//$(this).data().raphael.circle.animate() does not work here
}
else if(options.type === 'update') {
$(this).data().raphael.circle.animate({cx: 200, cy: 200});
//But this works here
}
}
In this case, referencing the element with $(this).data().raphael.circle does work, but only in the else if. I'm not sure why.
Related
Attempting to inject SVG elements with raw javascript. I can inspect and see the elements have been loaded, but dimensions end up being 0x0 instead of the size set on the element.
(function() {
// Constructor
this.Loading = function() {
this.svgNamespace = "http://www.w3.org/2000/svg";
var svg = createSvgObject("svg", "loaderSvg");
svg.setAttributeNS(null, "width", 200);
svg.setAttributeNS(null, "height", 200);
document.getElementById("possibleLoadingLocation").appendChild(svg);
var circle = createSvgObject("circle", "test");
circle.setAttribute("cx", 40);
circle.setAttribute("cy", 40);
circle.setAttribute("r", 30);
circle.setAttribute("stroke", "#000");
circle.setAttribute("stroke-width", 2);
circle.setAttribute("fill", "#f00");
svg.appendChild(circle);
}
function createSvgObject(elementType, elementId) {
if (elementType === undefined || elementType == null) {
throw "elementType is required to createSvgObject";
}
var element = document.createElementNS(this.svgNamespace, elementType);
if (elementId != null) {
element.setAttributeNS(null, "id", elementId);
}
return element
}
}());
var myLoading = new Loading();
Both the SVG object and the Circle object arrive with dimensions of 0x0. I have used css in the below example to force the svg to match the dimensions of the div containing it. I have also copied the exact svg code from the inspection into the body without css where I can see it sizing properly.
Thanks for any help.
https://jsfiddle.net/t92m5L8s/3/
Change the location of
this.svgNamespace = "http://www.w3.org/2000/svg";
to before:
this.Loading = function() {
I am attempting to write a Darkroom.JS plugin that will transform white space in images to transparency.
I have used this answer (solely canvas based) to write this code:
(function() {
'use strict';
var Transparency = Darkroom.Transformation.extend({
applyTransformation: function(canvas, image, next) {
console.log(canvas);
console.log(image);
var context = canvas.getContext("2d");
var upperContext = $('.upper-canvas').get(0).getContext("2d");
var imageData = context.getImageData(0, 0, image.getWidth(), image.getHeight());
//var upperImageData = upperContext.createImageData(image.getWidth(), image.getHeight());
console.log("apply transformation called");
for(var i = 0, n = imageData.data.length; i < n; i +=4){
var r = imageData.data[i],
g = imageData.data[i+1],
b = imageData.data[i+2];
if(r >= 230 && g >= 230 && b >= 230){
imageData.data[i] = 0;
imageData.data[i+1] = 0;
imageData.data[i+2] = 0;
imageData.data[i+3] = 1;
}
};
context.putImageData(imageData, 0, 0);
upperContext.putImageData(imageData, 0, 0);
//canvas.renderAll();
next();
}
});
Darkroom.plugins['transparency'] = Darkroom.Plugin.extend({
defaults: {
clearWhiteSpace: function() {
this.darkroom.applyTransformation(
new Transparency()
);
}
},
initialize: function InitializeDarkroomTransparencyPlugin() {
var buttonGroup = this.darkroom.toolbar.createButtonGroup();
this.destroyButton = buttonGroup.createButton({
image: 'wand' //Magic Wand by John O'Shea from the Noun Project
});
this.destroyButton.addEventListener('click', this.options.clearWhiteSpace.bind(this));
},
});
})();
(I should also note I based the structure of the plugin off of the existing rotate plugin)
The code does get called, and I do not currently have it in the code (for performance reasons) but a log statement indicated that the if block where the pixel editing is done also gets called.
To verify, I presently have the pixels set to fully opacity and black (instead of transparent so that I can see the effects of editing).
Also, I noticed that Darkroom.JS seems to generate two canvas objects, an upper canvas and lower canvas. The object passed to the transform function is the "lower canvas" object, so I even tried using jQuery to grab the "upper" one and set the image data on that, to no avail.
What am I missing?
I was focusing my search for an answer far too much on Darkroom.JS.
Darkroom.JS is just a layer on top of Fabric.JS, and this answer holds the key:
fabric js or imagick remove white from image
I actually used the second answer and it works perfectly:
So there is a filter in Fabric.js that does just that.
http://fabricjs.com/docs/fabric.Image.filters.RemoveWhite.html
var filter = new fabric.Image.filters.RemoveWhite({ threshold: 40,
distance: 140 }); image.filters.push(filter);
image.applyFilters(canvas.renderAll.bind(canvas));
Here is my completed code (with some extraneous details removed to simplify):
fabric.Image.fromURL(imgData.URL, function(logoImg){
canvas.add(logoImg);
var threshold = 40;
var whitespace = function(){
var filter = new fabric.Image.filters.RemoveWhite({
threshold: threshold,
distance: 140
});
threshold+=20;
logoImg.filters.push(filter);
logoImg.applyFilters(canvas.renderAll.bind(canvas));
};
});
I am trying to follow this tutorial here https://www.smashingmagazine.com/2012/10/design-your-own-mobile-game/ and I am stuck on the second part. (2. A Blank Canvas)
I am not sure where to put the POP.Draw object. Does it go inside of the var POP{} brackets where the other objects are created? I've tried keeping it inside, outside, and in the init function which I don't think makes sense. The purpose is to create methods within the new Draw object so they can be called later to create pictures in the canvas.
Here is my current code. It is the same as the one in the link:
var POP = {
//setting up initial values
WIDTH: 320,
HEIGHT: 480,
// we'll set the rest of these
//in the init function
RATIO: null,
currentWidth: null,
currentHeight: null,
canvas: null,
ctx: null,
init: function() {
//the proportion of width to height
POP.RATIO = POP.WIDTH / POP.HEIGHT;
//these will change when the screen is resized
POP.currentWidth = POP.WIDTH;
POP.currentHeight = POP.HEIGHT;
//this is our canvas element
POP.canvas = document.getElementsByTagName('canvas')[0];
//setting this is important
//otherwise the browser will
//default to 320x200
POP.canvas.width = POP.WIDTH;
POP.canvas.width = POP.HEIGHT;
//the canvas context enables us to
//interact with the canvas api
POP.ctx = POP.canvas.getContext('2d');
//we need to sniff out Android and iOS
// so that we can hide the address bar in
// our resize function
POP.ua = navigator.userAgent.toLowerCase();
POP.android = POP.ua.indexOf('android') > -1 ? true : false;
POP.ios = (POP.ua.indexOf('iphone') > -1 || POP.ua.indexOf('ipad') > -1) ? true : false;
//we're ready to resize
POP.resize();
POP.Draw.clear();
POP.Draw.rect(120, 120, 150, 150, 'green');
POP.Draw.circle(100, 100, 50, 'rgba(225,0,0,0.5)');
POP.Draw.text('Hello WOrld', 100, 100, 10, "#000");
},
resize: function() {
POP.currentHeight = window.innerHeight;
//resize the width in proportion to the new height
POP.currentWidth = POP.currentHeight * POP.RATIO;
//this will create some extra space on the page
//allowing us to scroll past the address bar thus hiding it
if (POP.android || POP.ios) {
document.body.style.height = (window.innerHeight + 50) + 'px';
}
//set the new canvas style width and height note:
//our canvas is still 320 x 400 but we're essentially scaling it with css
POP.canvas.style.width = POP.currentWidth + 'px';
POP.canvas.style.height = POP.currentHeight + 'px';
//we use a timeout here because some mobile browsers
//don't fire if there is not a short delay
window.selfTimeout(function() {
window.scrollTo(0, 1);
})
//this will create some extra space on the page
//enabling us to scroll past the address bar
//thus hiding it
if (POP.android || POP.ios) {
document.body.style.height = (window.innerHeight + 50) + 'px';
}
}
};
window.addEventListener('load', POP.init, false);
window.addEventListener('resize', POP.resize, false);
//abstracts various canvas operations into standalone functions
POP.Draw = {
clear: function() {
POP.ctx.clearRect(0, 0, POP.WIDTH, POP.HEIGHT);
},
rect: function(x, y, w, h, col) {
POP.ctx.fillStyle = col;
POP.ctx.fillRect(x, y, w, h);
},
circle: function(x, y, r, col) {
POP.ctx.fillStyle = col;
POP.ctx.beginPath();
POP.ctx.arc(x + 5, y + 5, r, 0, Math.PI * 2, true);
POP.ctx.closePath();
POP.ctx.fill();
},
text: function(string, x, y, size, col) {
POP.ctx.font = 'bold' + size + 'px Monospace';
POP.ctx.fillStyle = col;
POP.ctx.fillText(string, x, y);
}
};
SOLVED
I didn't realize but the completed code is on the webpage. I downloaded it and looked at the example for answers.
I solved the issue by placing the POP.Draw.clear, POP.Draw.rect methods before calling the POP.resize() method. I'm not really sure why the order matters, but it does.
I create group with:
var text = new fabric.Text(textValue,{left: 20, top: 30, fontSize:25});
var rect = new fabric.Rect({
width : text.get('width') + 40,
fill : "#FFFFFF",
height : 100,
stroke : '#000000',
strokeWidth : 1
});
var myGroupObj = new fabric.CustomGroup([ rect,text ], {
left : 0,
top : 0,
});
Now whene I manually resizes my group and I want to get a new heigth.
myGroupObj.get('height')
I have always last one (100).
Somme idea to get new height, please?
Instead of accessing the .height attribute, you should call the getHeight() function, which gives you the actual height (the one you see on the screen) of a fabric.js object. In the code you have created on jsfiddle, to get the real height, you should change the line alert(activeObject.height); by alert(activeObject.getHeight()); and you will see the difference.
Cheers,
Gonzalo Gabriel
I find solution to get New Height of object after manually resizes http://jsfiddle.net/islyoung2/7Tf22/4/.
var newHeight = myGroupObj.get('height') * myGroupObj.get('scaleY')
Thank you.
When you set the new width or the new height, don't forget to update also scaleX and scaleY:
canvas.on("object:modified", function (e) {
var activeObject = e.target;
if (!activeObject) {
return;
}
var newWidth = activeObject.width * activeObject.scaleX ;
var newHeight = activeObject.height * activeObject.scaleY ;
activeObject.width = newWidth;
activeObject.height = newHeight;
activeObject.scaleX = 1;
activeObject.scaleY = 1;
});
I'm working on a project with Fabric.js.
Now I need to create a custom class and to export it to SVG.
I'm using Fabric.js tutorial to begin:
http://www.sitepoint.com/fabric-js-advanced/
Here is the javascript code:
var LabeledRect = fabric.util.createClass(fabric.Rect, {
type: 'labeledRect',
initialize: function(options) {
options || (options = { });
this.callSuper('initialize', options);
this.set('label', options.label || '');
},
toObject: function() {
return fabric.util.object.extend(this.callSuper('toObject'), {
label: this.get('label')
});
},
_render: function(ctx) {
this.callSuper('_render', ctx);
ctx.font = '20px Helvetica';
ctx.fillStyle = '#333';
ctx.fillText(this.label, -this.width/2, -this.height/2 + 20);
}
});
var canvas = new fabric.Canvas('container');
var labeledRect = new LabeledRect({
width: 100,
height: 50,
left: 100,
top: 100,
label: 'test',
fill: '#faa'
});
canvas.add(labeledRect);
document.getElementById('export-btn').onclick = function() {
canvas.deactivateAll().renderAll();
window.open('data:image/svg+xml;utf8,' + encodeURIComponent(canvas.toSVG()));
};
Here the HTML:
<canvas id="container" width="780" height="500"></canvas>
Export SVG
Here is my jsfiddle..
http://jsfiddle.net/QPDy5/
What I'm doing wrong?
Thanks in advance.
Every "class" in Fabric (rectangle, circle, image, path, etc.) knows how to output its SVG markup. The method responsible for it is toSVG. You can see toSVG of fabric.Rect, for example, or fabric.Text one.
Since you created subclass of fabric.Rect here and didn't specify toSVG, toSVG of the next object in prototype chain is used. The next "class" in the inheritance chain happens to be fabric.Rect, so you're seeing a result of fabric.Rect.prototype.toSVG.
The solution is simple: specify toSVG in your subclass. Theoretically, you would need to combine the code from fabric.Rect#toSVG and fabric.Text#toSVG, but to avoid repetition and keep things maintainable, we can utilize a bit of a hack:
toSVG: function() {
var label = new fabric.Text(this.label, {
originX: 'left',
originY: 'top',
left: this.left - this.width / 2,
top: this.top - this.height / 2,
fontSize: 20,
fill: '#333',
fontFamily: 'Helvetica'
});
return this.callSuper('toSVG') + label.toSVG();
}
The "fontSize", "fill", and "fontFamily" should ideally be moved to an instance-level property of course, to avoid repeating them there.
Here's a modified test — http://jsfiddle.net/fabricjs/QPDy5/1/
What #Sergiu Paraschiv suggested with a group is another just-as-viable solution.
Problem is there's no SVG equivalent to fillText so FabricJS seems to ignore it.
My workaround is to use a fabric.Group and build an inner Rect and Text
var LabeledRect = function(options) {
var rect = new fabric.Rect({
width: options.width,
height: options.height,
fill: options.fill
});
var label = new fabric.Text(options.label);
var group = new fabric.Group([rect, label]);
group.left = options.left;
group.top = options.top;
group.toSVG = function() {
var e=[];
for(var t = 0; t < this._objects.length; t++)
e.push(this._objects[t].toSVG());
return'<g transform="'+this.getSvgTransform()+'">'+e.join("")+"</g>"
};
return group;
};
The reason I overwrote toSVG is because the default implementation cycles through the children in reverse order (for(var t=this._objects.length;t--;)). I have no clue why it does that, but the text renders underneath the rectangle.