Setting background image by javafx code (not css) - javafx-2

I'm trying to set an image as the background using this code:
root.setStyle("-fx-background-image: url('splash.jpg');
-fx-background-position: center center;
-fx-background-repeat: stretch;");
But it doesn't work. If I set it with CSS, it works perfectly:
root.setId("pane");
primaryStage.getScene().getStylesheets().add(JavaFXApplication9.class.getResource("style.css").toExternalForm());
and CSS:
#pane{
-fx-background-image: url('splash.jpg');
-fx-background-repeat: stretch;
-fx-background-position: center center;
}
All of my files (main class, CSS and image) placed into the same package.
So, how can I set the background image using code? Or, how can I override (replace) lines about background-image of some element in CSS from application code? Thanks!

Try next:
String image = JavaFXApplication9.class.getResource("splash.jpg").toExternalForm();
root.setStyle("-fx-background-image: url('" + image + "'); " +
"-fx-background-position: center center; " +
"-fx-background-repeat: stretch;");

If you really don't want to use CSS or the setStyle() method, you can use the following:
// new Image(url)
Image image = new Image(CurrentClass.class.getResource("/path/to/package/bg.jpg"));
// new BackgroundSize(width, height, widthAsPercentage, heightAsPercentage, contain, cover)
BackgroundSize backgroundSize = new BackgroundSize(100, 100, true, true, true, false);
// new BackgroundImage(image, repeatX, repeatY, position, size)
BackgroundImage backgroundImage = new BackgroundImage(image, BackgroundRepeat.REPEAT, BackgroundRepeat.NO_REPEAT, BackgroundPosition.CENTER, backgroundSize);
// new Background(images...)
Background background = new Background(backgroundImage);
You can find detailed documentation on BackgroundImage here.
(Sorry for replying to this old question.)

Related

fabricjs - Apply SVG inline-style to objects

I'm using loadSVGfromURL to fill a canvas with this SVG
As you can see in the link, I got some Heather effect on my shirt, along with some shadows. Plus, my SVG style applies a mix-blend-mode: multiply; to my paths.
Unfortunately, once rendered in my canvas, it seems like the paths CSS is not taken into account :
How can I make sure that this style is applied ?
Here is an exemple. Basically you need to map mix-blend-mode to globalCompositeOperation
var site_url = 'http://s3.eu-central-1.amazonaws.com/balibart-s3/SVGMockups2/59f32980b5d8493ef7f29904/front/Layer.svg';
canvas = new fabric.Canvas('canvas');
fabric.loadSVGFromURL(site_url, function(objects) {
var group = new fabric.Group(objects, {
left: 165,
top: 100,
});
canvas.add(group);
group._objects[3].globalCompositeOperation='multiply';
group._objects[2].globalCompositeOperation='multiply';
group._objects[4].globalCompositeOperation='multiply';
group._objects[5].globalCompositeOperation='multiply';
group._objects[6].globalCompositeOperation='multiply';
/*for(var i=0;i<objects.length;i++){
canvas.add(objects[i]);
}
canvas.getObjects()[5].globalCompositeOperation='multiply';*/
// canvas.add(objects);
canvas.renderAll();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/2.4.6/fabric.js"></script>
<canvas id='canvas' width="900" height="900"></canvas>

Hover Text effect next to mouse cursor

Dear community is there any way to do a text next to the cursor hover effect (in css?) like on this site here?
http://manuelraeder.co.uk/
I tried it with abbr and span style, but it doesn't seem to work. Text should be changeable with every picture.
Thanks in advance!
From the website you linked, they appear to be using Javascript. I don't think there is a way to do this purely with CSS.
When you hover your mouse over an image on the website, a new HTML tag is created at the end of the body:
<p class="tooltip" style="display: block; top: ...; left: ...;">TEXT</p>
Where top and left correspond to the pixel values that your cursor is at, and the text would be whatever text you want to float next to the cursor.
In the Javascript, you would create a hover observer for the associated images, and inside the trigger function create the new p tooltip element. You would set the text for your p element to be the respective image's alt title. Looking at the website's Javascript, this is what they did for their tooltip:
$(document).ready(function() {
// Tooltip only Text
$('.masterTooltip').hover(function(){
// Hover over code
var title = $(this).attr('title');
$(this).data('tipText', title).removeAttr('title');
$('<p class="tooltip"></p>')
.text(title)
.appendTo('body')
.fadeIn('fast');
}, function() {
// Hover out code
$(this).attr('title', $(this).data('tipText'));
$('.tooltip').remove();
}).mousemove(function(e) {
var mousex = e.pageX + 20; //Get X coordinates
var mousey = e.pageY + 10; //Get Y coordinates
$('.tooltip')
.css({ top: mousey, left: mousex })
});
});

how to stretch image size to match fabric.Image object

I am using fabricjs to implement image editing and I try to use a fabric.Image object as the background image of canvas to store the data. And the following is the code:
var canvas = new fabric.Canvas('canvasId');
var imageObject = new fabric.Image($originImage);
canvas.add(imageObject);
but I found the $originImage's size is much larger than canvas' size and also imageObject's size, so the canvas can only show part of the image. I want to know how to stretch the $originImage to adapt the canvas then canvas can display all of the $originImage?
Here what I have done
$canvas.width = $originImage.clientWidth;
$canvas.height = $originImage.clientHeight;
var fabricCanvas = new fabric.Canvas('canvasId');
// canvas.setFabricCanvas(fabricCanvas);
var imageObject = new fabric.Image($originImage);
// fabricCanvas.add(imageObject);
// fabricCanvas.isDrawingMode = true;
fabricCanvas.setBackgroundImage(imageObject, fabricCanvas.renderAll.bind(fabricCanvas), {
scaleX: fabricCanvas.width / $originImage.naturalWidth,
scaleY: fabricCanvas.height / $originImage.naturalHeight
});
the upper is my related code and below is the display:
it is solved, and the previous question is because I resize the $originImage first, so when I input the image src as setBackgroundImage's parameter, it can display normally.
For version 2.0 of fabricjs, they have changed the way to handle width/height compared to previous version. If you apply width/height, then it basically crop the image to that particular size compared to the original image size. In order to resize it to a proper size, you have to switch to use scaleX/scaleY like other people have suggested.
For example, I use image.fromUrl to load an image and set it to be the background:
fabric.Image.fromURL(imgUrl, function(img) {
img.set({
scaleX: currentWidth / img.width,
scaleY: currentHeight / img.height,
top: topPosition,
left: leftPosition
originX: 'left', originY: 'top'
});
canvas.setBackgroundImage(img, canvas.renderAll.bind(canvas));
});
where currentWidth/currentHeight can be your canvas size if you want full background or they can be a specific width/height that you want (in my project, I want to do letter-boxed image instead so I set the width and height based on my letter-boxing algorithm), and top/left is the location that you want to place your image in the canvas (leave it none if you want to be full background image). Do not set any width and height since that will crop the scaled image rather than setting the image to be the exact size.
If this does not work, check the backgroundImage object from the canvas and see if its dimension and scale properties are different compared to a manual calculation. If you take a look, you will see the width and height properties are your natural image width and height, but it will have scaleX and scaleY less than 1 if your canvas size is less than the image size or more than 1 if it is bigger.
Also I see you are loading image directly into an image object. That might be different compared to load the data and set it directly using setBackgroundImage.
canvas.setBackgroundImage(img, canvas.renderAll.bind(canvas), {
scaleX: canvas.width / $originalImg.naturalWidth,
scaleY: canvas.width / $originalImg.naturalHeight
});
use scaleX,scaleY to resize.
(function() {
var $originalImg = $('#originalImage')[0];
console.dir($originalImg)
var canvas = this.__canvas = new fabric.Canvas('c');
var img = new fabric.Image($originalImg);
canvas.setBackgroundImage(img,canvas.renderAll.bind(canvas),{
scaleX:canvas.width/$originalImg.naturalWidth,
scaleY:canvas.width/$originalImg.naturalHeight
});
})();
canvas{
border-width: 1pz;
border-style: solid;
border-color: #000;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/2.0.0-rc.3/fabric.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img id='originalImage'src='http://fabricjs.com/assets/pug_small.jpg'>
<canvas id='c' width=200 height=200></canvas>
I am using the following script to ensure the image is no larger than the canvas width:
var aspect = image.width / image.height; //Aspect ratio of image
new fabric.Image(image, {
scaleX: canvas.width / image.width,
scaleY: canvas.width / (image.height * aspect)
});

fabricjs set boundingrect to the new object after cropping object using clipto method

I have clipped an image using clipto method of fabricjs and this works fine. But the problem is boudingrect is still to the actual image area. Is there any way to reset boundingrect same as new cropped image? I tried setCoords but this does not work.
FabricJS has two methods available to "crop" an object, the one you are using clipTo(), and a toDataURL() method. Using toDataURL() creates a new image with a reset boundingrect same as new cropped image.
fabric.Image.fromURL('data:image/;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAACa0lEQVRYhbVXMW7bQBAcMgRTWCJdC+qFOLAaudFDnEKdYL1AfoCRB8gvkJJUAQw/RI3cSIBg13ZShzxWBEK6sEjf7e3dkYC8Fckhduf2doZHryzLEpY4e/mp3M+jEW7TB/bdq+457rMnpGVeP9v3p7b08K0oE7NoiHk0Yotfxxdt07UnsEy3Gomq+F32qKy+SQRtCVTtn0VDAEBS5nXx7//WbdPpBOQ9/3YywDwaYRYNsUy3dfHksMquHwLF27uieF+53JFFssFK7Gps3Zsg9j+bCcjFb07H+PrnFwD3ik14NYQyCWsH5OKe5wHQ206Lu/BqODkSGgFanBbp+iG71y7cpBDvy/MPxQeozmUdL9Nt3WIuOFyeKc4ntA5UbaRmIw8htyIXXg3mffakPNd8gNM5Tb4SOyySTWPc5hNaB+hA0eRyEQCIvdCKy8W52fDn0Qj7/lRZsazzxOJsosideOyF9XUVV91z7PtT3JyOEbiczaRjqhYT7vKRAGivY1rchdvy1zPQVMeiyFmfcOGm/MoQJmVeezsXsRcCPrTkTXEuf02Afs8/ygdo/kAG77JHiCLXzIjTuVzEhdvyByadfrQPVPmDldhpEpJ94OV/piWvQhS59Uwlihz9T533dw9xmz6oWyAHZXxsH6Dd0ghw7TqmDyzFzv41NHn2sXyAhkf/CxbJxvo9Nw2dCafnicvOwH4mpBKSk9t8oqmPXHYGynP2TNhGx01wk5SNBGQSLh27Tsm24iyBdW+i3I///rb6BPdfIOt83ZsobY8O5wMjAXlAuHB1hK7Wla/1rxlX3KZzV7QmYPIJ2z7b4hVhK2M6UYICmwAAAABJRU5ErkJggg==', function(origImage) {
var origBoundingRect = origImage.getBoundingRect();
fabric.Image.fromURL(origImage.toDataURL({
width: origImage.width - 5,
height: origImage.height - 5
}), function(newImage) {
var newBoundingRect = newImage.getBoundingRect();
console.log('origBoundingRect:\r\n' + JSON.stringify(origBoundingRect) + '\r\n\r\n' + 'newBoundingRect:\r\n' + JSON.stringify(newBoundingRect));
});
});
<script src="//cdnjs.cloudflare.com/ajax/libs/fabric.js/1.7.7/fabric.min.js"></script>
If you run the code snip-it above it logs to the console a before and after shot of the boundingrect.
Hope this helps, matey. Let me know if you have any further questions.

Draw text on canvas using fabric.js

I want to draw text on canvas., how to do it any sample example?
The canvas already contains some shape drawn, i want to show text on the top of that shape on canvas
How can i do it?
Also be aware that you need to actually have loaded a cufon font. There is no default font when using Fabric.js.
<script src="fabric.js"></script>
<script src="cufon.calibri.js"></script>
There are so many fonts available from http://www.cufonfonts.com/
This being the case the author is planning on removing the need for cufon. Discussed here: Fabric.js + Google Fonts
If you're wanting to render a block, then some text inside of that block. I would do something like this.
//Render the block
var block = canvas.add(new fabric.Rect({
left: 100,
top: 100,
fill: 'blue'
}));
//Render the text after the block (so that it is in front of the block)
var text = canvas.add(new fabric.Text('I love fabricjs', {
left: block.left, //Take the block's position
top: block.top,
fill: 'white'
}));
//Render the text and block on the canvas
//This is to get the width and height of the text element
canvas.renderAll();
//Set the block to be the same width and height as the text with a bit of padding
block.set({ width: text.width + 15, height: text.height + 10 });
//Update the canvas to see the text and block positioned together,
//with the text neatly fitting inside the block
canvas.renderAll();
Take a look at How to render text tutorial.
It's as simple as:
canvas.add(new fabric.Text('foo', {
fontFamily: 'Delicious_500',
left: 100,
top: 100
}));
Also worth noting that you might need to adjust Cufon's offsetLeft to help correctly position the text. Something like:
Cufon.fonts[your-fontname-in-lowercase-here].offsetLeft = 120;
The kitchen sink demo of fabric uses this:
http://kangax.github.com/fabric.js/lib/font_definitions.js

Resources