canvas,svg,javafx,graphicscontext , JavaFX: How to use the GraphicsContext method appendSVGPath(String svgpath)


JavaFX: How to use the GraphicsContext method appendSVGPath(String svgpath)

Question:

Tag: canvas,svg,javafx,graphicscontext

I'm working on a project that makes use of SVG's. Currently the program has the SVG's stored as SVGPath objects in an FXML file. The file is then loaded into a Group which is then added to the screen. In the FXML file, there are approximately 300 such SVGPaths. Which I believe ultimately means that there are 300 nodes on the scene graph.

I'm going to eventually have to scale up the number of SVGPath and am having concerns about putting more nodes on the scene, so I began to look at using a Cavas/GraphicsContext instead.

GraphicsContext has a method appendSVGPath(String svgpath) that I think I could use to draw my SVGs on the cavas, but am not having any luck getting them to appear.

I'm using the CanvasTest.java file from Oracle as starting point: http://docs.oracle.com/javafx/2/canvas/jfxpub-canvas.htm

I modified the file to include the following method:

private void appendSVG(GraphicsContext gc) {
     SVGPath svg = new SVGPath();
     svg.setContent("M 100 100 L 300 100 L 200 300 z");
     svg.setFill(Color.RED);
     svg.setStroke(Color.BLUE);
     gc.appendSVGPath(svg.getContent());
}

But I can't get the shape to appear on the canvas.

Full test code here:

package canvastest;

import javafx.application.Application;
import static javafx.application.Application.launch;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.paint.Color;
import javafx.scene.shape.SVGPath;
import javafx.stage.Stage;

public class CanvasTest extends Application {

private Canvas canvas = new Canvas(200, 200);
private GraphicsContext gc = canvas.getGraphicsContext2D();
private Group root = new Group();

public static void main(String[] args) {
    launch(args);
}

@Override
public void start(Stage primaryStage) {
    primaryStage.setTitle("Canvas Test");

    appendSVG(gc);

//        SVGPath svg = new SVGPath();
//        svg.setContent("M 100 100 L 300 100 L 200 300 z");
//        svg.setFill(Color.RED);
//        svg.setStroke(Color.BLUE);

    root.getChildren().add(root);
    primaryStage.setScene(new Scene(root, 400, 400));
    primaryStage.show();
}

private void appendSVG(GraphicsContext gc) {
    SVGPath svg = new SVGPath();
    svg.setContent("M 100 100 L 300 100 L 200 300 z");
    svg.setFill(Color.RED);
    svg.setStroke(Color.BLUE);
    gc.appendSVGPath(svg.getContent());
}
}

If I uncomment out the SVG section from start, and just add the svg to root, the svg will display.

Has anyone had any success using appendSVGPath?


Answer:

Canvas isn't like the scene graph, stroking and filling paths does not happen automatically. Instead you need to feed your path segments to the canvas, then explicitly call fill() or stroke() to have those operations applied. For more information, see the "path rendering" section at the front of the GraphicsContext javadoc.

svgpath

import javafx.application.Application;
import javafx.scene.*;
import javafx.scene.canvas.*;
import javafx.scene.paint.Color;
import javafx.stage.Stage;

public class CanvasTest extends Application {

    private Canvas canvas = new Canvas(200, 200);
    private GraphicsContext gc = canvas.getGraphicsContext2D();

    public static void main(String[] args) {
        launch(args);
    }

    @Override
    public void start(Stage stage) {
        appendSVG(gc);

        stage.setScene(new Scene(new Group(canvas)));
        stage.show();
    }

    private void appendSVG(GraphicsContext gc) {
        gc.setFill(Color.RED);
        gc.setStroke(Color.BLUE);
        gc.appendSVGPath("M 50 50 L 150 50 L 100 150 z");
        gc.fill();
        gc.stroke();
    }
}

Related:


How can I save my generated svg code to a .svg file in the client machine?


javascript,svg,snap.svg
I used snap.svg library to generate, with javascript, a svg element in my asp.net web form page by loading other external .svg files and manipulating them in order to get the final svg element. Once the composition of the desired svg object is finish and the resulting svg element shows...

d3.js grid moving around when dragging and zooming


javascript,svg,d3.js,gridlines
I tried to copy the behavior of the grid displayed here. The code I have is here Problem is, when I'm dragging or zooming, the grid is moving along with everything else, while it should not. I suspect the problem is around this part : function zoomed() { svg.select(".x.axis").call(xAxis); svg.select(".y.axis").call(yAxis);...

Aligning StackPanel to top-center in Canvas


c#,wpf,xaml,canvas
I'm trying to create an application which is supposed to measure quick reaction performance of it's user. The application starts up in full-screen mode and resizes it's elements accordingly to the screen resolution. The project was strongly inspired by training_aim_csgo2 map. It's mostly done, but here is the problem: I...

HTML Canvas Width


javascript,jquery,html,css,canvas
I have a problem with the initial width of the canvas. What I have is a canvas element with a image background that's set to cover and than within the jquery the canvas width is set to the window.InnerWidth, the height is the width / 3. (this is to keep...

Javascript D3.js drag a chart out of its svg Element


javascript,svg,d3.js
I want to make chart, that you can not drag out of its svg element. I'm doing this at the moment like this jsfiddle As you can see, you can zoom and drag this freely. What i want is this: If you drag it for example to the right and...

Responsive axis with percentage coordinates


javascript,svg,d3.js,graph,charts
In an attempt to build a responsive scatter graph with d3.js, I'm using %-based coordinates in a 100% x 100% svg element. How can I .call(axis) and get it to layout the axis using % and not px values, so that they always fit the svg and the plotted data?...

Equivalent of canvas quadraticCurveTo in SVG


javascript,jquery,canvas,svg,bezier-curve
I am working on a plugin to allow "natural looking" signatures to be drawn using mouse or touch. When confirmed by the user, the result will be a stored SVG that can then be displayed in place of the "Click to sign" button. The attached JSFiddle http://jsfiddle.net/TrueBlueAussie/67haj4nt/3/ shows a testbed...

DrawImage is not drawing in a canvas


javascript,html5,canvas,drawimage
Basically what I have been trying to do, is make a loop that will cycle through a tonne(only 36 atm) of tiles, and place them in order. While that part works, it doesn't actually load the images and display the images. Using console.log, I've narrowed the problem down to when...

Controlling canvas object with range slider


javascript,canvas,slider
Attempting to place a circular object on a canvas, and alter the position of the object dependent on range slider inputs (x, y). Currently the object is not placed on canvas, rather than the var cx/cy being a number value they are being returned as [object HTMLInputElement]. Why? JS code:...

SVG animation not repeating properly


svg,svg-animate,smil
I am having some difficulty getting my SVG icons to repeat properly. I need them to repeat like a gif, individually and indefinitely. I can get only two to work but I need all three to repeat one after the other. Here is a js fiddle of the SVG animation...

How can I display greek letters in D3 svg.text objects?


javascript,svg,d3.js
I am using D3 and want to add the greek letter delta. This is in the tag of my HTML: <meta http-equiv="content-type" content="application/xhtml+xml; charset=utf-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> This is where the problem lies: 'bars' is a variable that stores a selection of class '.bar' and...

adding link_to with image_tag and image path both


html,ruby-on-rails,image,ruby-on-rails-4,svg
I am trying to replace the tag with link_to in my rails application view. for replacing I have svg icon, text and link all in one tag. Here is below <a class="navbar-brand" href="index.html"><%= image_tag 'logo.svg', "data-svg-fallback" => image_path('logo.svg'), :align=> "left" ,:style => "padding-right: 5px;" %> My Project </a> but I...

Svg set new coordinates with animation on 2 lines simultaneously


jquery,html,css,css3,svg
I need a way (with CSS3 or jQuery) to change this SVG shape from X to ↓ (Down arrow). I tried more ways but i still have problems. My basic idea is to get lines with id (svg_5, svg_6) and make these the head of my arrow. $('a').click(function (e) {...

Cyrllic characters in SVG font


javascript,svg,unicode,encoding,fonts
You will have to bear with me with this, as I know very little about encodings so may be asking something very simple/obvious. I am working with some SVG fonts in browser-side Javascript and I need to pull out some information on Cyrillic characters grammatically. I am doing this currently...

How do I load SVGs directly in my React component using webpack?


svg,icons,reactjs,loader,webpack
I would like to render a material design icon directly in my NextButton component using webpack. Here's the relevant part of my code: var NextIcon = require('material-design-icons/navigation/svg/production/ic_chevron_right_18px.svg'); var NextButton = React.createClass({ render: function() { return ( <Link to={this.props.target} className='button--next'> {this.props.label} {NextIcon} </Link> ) } }); But this isn't working as...

Determine shape drawn on canvas from stored coordinates in an array


javascript,html5,canvas
I have startX,startY,endX,endY mousecoordinates using which I draw 3 shapes(a line,ellipse and a rectangle) on canvas.Now I store these coordinates(startX,startY,endX,endY) in a array(for each shape drawn) and draw it again on cleared canvas.Now,the problem is how do I determine from these coordinates stored in the array wheather the shape previously...

Trying to fill a SVG map from wordpress custom categories


wordpress,dictionary,svg
I've created a custom post_type (destinations) with a category (locations) to provide a tree structure for my SVG map: Continent/Country/Town Example locations: Europe/Germany/Berlin/POST Europe/Italiy/Sicily/POST North-Africa/Morocco/Marrakech/POST My plan was to fill the map by the country short codes like (DE for Germany, IT for Italia, LY for Libya (...). Here is...

Creating SVG elements dynamically


javascript,svg,d3.js
I am trying to create some circles in d3js dynamically, But for some reason it fails. My requirement is to show two small circles on the rectangle when I hover the rectangle. on the mouse out event circles should hide. I tried to it by creating a rect object and...

How to manipulate existing group elements with Snap.svg


javascript,svg,snap.svg
We have an existing svg-document in witch we want to replace a group-element with a new one. Is it possible to do with Snap.svg? var oldGroup = Snap.select("[id='" + oldGroupId + "']"); oldGroup.outerSVG(newGroup); //This is what I want to do but outerSVG is readonly ...

Safari on Mobile blocks window.open [closed]


javascript,jquery,html,css,canvas
I have a mobile page where the user creates there own smartphone backgrounds using textarea. I use html2canvas to translate the textarea into a canvas and windwow.open + canvas.toDataURL to open the PNG in a new tab for the user to save. It works fine with Chrome but as far...

javascript node module.exports / require() code on the front-end


javascript,node.js,svg,browserify
I've been looking into using a library such as SVGO to be able to clean user submitted SVG code on the front end. SVGO is a node.js based library which typically works on the back end, so I've been trying to wrap my head around how to go about sending...

Dynamic inclusion of javascript in SVG by means of server side filtering inside apache server


javascript,apache,svg,piwik
Years back I wrote some code to automatically include some javascript code inside html pages delivered by an http server. The approach is documented here in a blog entry and in this StackOverflow question. The solution served me well over the last years. The approach in two sentences: for every...

HTML 5 Canvas addHitRegion not working on iOS (undefined is not a function)


javascript,ios,html5,canvas
I'm building out a clickable canvas overlaying an image for my website. On the desktop, everything is working fine. I'm looping through a set of coordinates and drawing various clickable shapes. On iOS, however, my loop draws the first shape and then apparently hits an error on the last line...

Center Aligning an SVG element?


svg,path
I don't know how to really explain this but how can I center align this logo http://jsfiddle.net/fa7w3h99/3/ I have tried the following but it didnt seem to work as intended. .center-logo { display: block; margin: auto; } ...

How to move a canvas element up and down for a certain amount of time with javascript


javascript,canvas
I'm trying to make 6 guitars strings move when they are clicked on. I tried doing a simple animation by moving the string 2.5 px up and 2.5 px down for 3 seconds. but I don't really know how to do that. This is what I've tried: function onLoad(){ snaren();...

Canvas element does not resize when using ReactJS and PaperJS together


javascript,html,canvas,reactjs,paperjs
I have found that canvas elements correctly resize on window resize when they are inside react components. They also resize correctly when used with PaperJS. However, they do not resize when used with PaperJS and ReactJS together. Is this an incompatibility between PaperJS and ReactJS or am I instantiating PaperJS...

How to alter a degree value into an actual x/y position change?


javascript,canvas,radians
Im drawing a circle on html canvas, the circle is meant to indicate a "ship". I have the current position (x, y) of the "Ship" object and randomly determine a degree (0 to 360) and an amount value. I then want to alter the ship's current position by the degree...

Using destination-over to save background and actual sketch


javascript,jquery,canvas,sketchjs
I've read this and a few other questions, and it is clear I need to use destination-over to save the background and the sketch by display the new image over the old one. I'm using Sketch.JS with my code as such: var c = document.getElementById("myCanvas"); var ctx = c.getContext("2d"); $('#myCanvas').sketch({...

Why WebGL slower than Canvas?


javascript,html5,canvas,webgl
I am just started to play around with canvas and webgl, read some article, etc.. and as per my knowledge, WebGL should be much more faster than canvas, but in these following tests it is remarkably slower: http://jsperf.com/canvas-drawimage-vs-webgl-drawarrays http://jsperf.com/three-js-canvas-vs-webgl/2 I run them in Chrome and Firefox, in both browser the...

html2canvas does not print jsPlumb Connectors


svg,jsplumb,html2canvas
How to print SVG elements that are built by jsPlumb. Known that getting all SVG Elements drawen by jsPlumb is retrieved by this code : var uiJsPlumbConnectors=jsPlumb.getAllConnections().map(function(conn){return conn.canvas;}) All connectors are SVG elements : Using html2canvas to print all connectors (SVG), it does not work : html2canvas(uiJsPlumbConnectors).then(function(c){ window.open(c.toDataURL('image/png')) }); An...

Svg how to position elements lo left and right like with floats?


javascript,svg,d3.js
I'm building a organizational chart with the help of dagre-d3,js and d3.js. Its svg based so every person in the chart needs to have some kind of a employee card (or call it profile card) This card needs to show the Persons name, his group and have 2 buttons, one...

Why won't my webGl page load a second time after a refresh?


javascript,html,svg
This is a JS page my friend and I are making. http://jmecom.github.io/GameUniverse/ The page loads fine when you first open it in a tab (albeit a little slow), but when you refresh the tab, the WebGl canvas will just be completely blank. The HTML elements are displayed though. We're using...

Snap SVG .animate callback fires immediately


javascript,jquery,animation,svg,snap.svg
I am trying to pass a set of arguments to an animate function within Snap SVG including a callback function. However, the callback (in this case is to remove the element) fires immediately on click and not after the animation has completed. As it is now, the element is removed...

Creating a responsive cloud shape


html,css,css3,svg,css-shapes
I've been trying to create a responsive cloud shape in CSS for a project. I am trying not to do this with images due to HTTP requests and the requirement for responsiveness. The shape in question would be this: (but can be similar - slight variations/improvements would be cool): I...

Redraw text over clearRect HTML5 Canvas


jquery,html5,canvas
I'm trying to draw text (HTML5 canvas) depending on what option is selected in a select element. It works correctly until there's 2 set of text that appears at the same place. It seems like the clearRect function is the issue. The text won't be redrawn over that cleared space....

Create a cone with shadows


javascript,canvas,html5-canvas
I would like to create a circle with a special shadow effect. Like this one: . It should look like a cone in wood or metal. I tried to do something with the radial gradiant in canvas but i can't creat that special Effekt. I don´t know how to create...

Canvas borders c# ( Windows Phone 7)


c#,windows-phone-7,canvas
I am using Storyboard to move my Images in Canvas. I am wondering if there is an option, when Image is moving to bottom and get into bottom border and Image will not move more down but also not stay. The point is how to make that Image will just...

Animate dots or points from an offset to their actual position


jquery,html,css,html5,svg
How can I do the animation by using SVG or CSS? Animation should be like below: Initially, only lines will be visible(picture 1), after 2 seconds dots (.) will come and join to the line curves(picture 2) with some animation to the dots. Online Example Please check the code below...

Get Angular to action ng-if in new elements generated by d3.js


javascript,angularjs,svg,d3.js,angularjs-directive
I am generating a series of <circle ng-if='n'> someScopeFunction()' \> with d3.js How can I get Angular to notice and work on these new elements and ng-ifs? And how can I get it to do so with angular variables, e.g. <circle some-attr='{{i - 2}}' />...

Javascript Canvas, can't draw multiple images


javascript,canvas
For a school project, I need to make a kind of "Invader" game. Actually, I got some issue with picture drawing. It works for 1 picture, but not for multiple. Also if I try to draw only rectangles, instead of pictures, it doesn't work. So I guess something is wrong...

HTML, Canvas Path2D alternative.


canvas,drawing,mobile-safari
I draw some graphics on my website using Path2d. Nothing complicated, just two triangles. But MobileSafari fails to create Path2D() object. Is there any workaround for it ? or any library to do that ? Thanks....

How to scale an image down to fit inside a canvas, without distorting the image?


html5,canvas,fabricjs
I have a fabric js canvas that I allow users to add external images to. Often times the user adds images that are too large to fit the canvas and it's a little difficult for them to re-size them correctly. I'd like to automatically scale the larger images down so...

Snap SVG Iterate over Object to build Animate properties


javascript,svg,snap.svg
I'm looking to write a function involving Snap SVG that would allow me to pass in an object or array of values through which I can iterate to build the animation properties. For example, if I could pass: [transform: 't100,100', transform: 'r10,10,10'] Into this: animateElementWithSnap: function(element, parentSVG, animationValues, duration, easing)...

fabric.js resize canvas to fit screen


javascript,android,cordova,canvas,fabricjs
I'm currently developping an application on mobile device (android and iPhone) with ionic and cordova. I would like to edit a picture. I use fabric.js library to do that. Fabric.js converts an image and other items into canvas. Then I add some image on the canvas (stickers) and export it...

How to make a Javafx Image Crop App


java,image,canvas,graphics,javafx
I am building an application for my colleagues to crop image. I use FXML with Scene Builder to build the GUI. The user click a button to choose a image from his computer. Then, the image is shown in the GUI. User can zoom and move in the pane. At...

my svg polygons fills are not changing color on hover


jquery,css,svg
I have some svg polygons. When you mouse over a polygon, I want to find part of the polygon's id, then change the fill color of all polygons that have that part of the polygon id in their id. But it isn't working. No polygon fill is changing. Anyone know...

how to define html5 svg polygon points to create graphics


html,html5,svg
Hi i am trying to find out how to define the points for a polygon in HTML5 <svg width="300" height="200"> <polygon points="100,10 40,198 190,78 10,78 160,198" style="fill:lime;stroke:purple;stroke-width:5;fill-rule:evenodd;" /> </svg> this will end up creating a Star image. i tried to remove some points and add some arbitrary points and it...

Floating ghost CSS animation


css,svg,css-animations
I have created an SVG ghost for my website's logo. I have made a CSS animation so when a user hovers the logo, the ghost starts floating. Everything works okay except that when it is unhovered, the ghost just drops back to it's original position. Is it possible to have...

How to achieve “flying Arcs” as link in the force layout of D3.js


svg,d3.js
Please suggest how to achieve the flying arcs in the force layout of d3.JS. As in the image