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

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


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 file from Oracle as starting point:

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");

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) {

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


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

    primaryStage.setScene(new Scene(root, 400, 400));;

private void appendSVG(GraphicsContext gc) {
    SVGPath svg = new SVGPath();
    svg.setContent("M 100 100 L 300 100 L 200 300 z");

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?


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.


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) {

    public void start(Stage stage) {

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

    private void appendSVG(GraphicsContext gc) {
        gc.appendSVGPath("M 50 50 L 150 50 L 100 150 z");


Using destination-over to save background and actual sketch

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({...

my svg polygons fills are not changing color on hover

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...

HTML, Canvas Path2D alternative.

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....

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

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...

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

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...

Safari on Mobile blocks [closed]

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 + canvas.toDataURL to open the PNG in a new tab for the user to save. It works fine with Chrome but as far...

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

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...

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

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...

Animate dots or points from an offset to their actual position

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...

Snap SVG Iterate over Object to build Animate properties

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)...

How to make a Javafx Image Crop App

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...

SVG animation not repeating properly

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...

Canvas element does not resize when using ReactJS and PaperJS together

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...

Canvas borders c# ( Windows Phone 7)

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...

Redraw text over clearRect 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....

Aligning StackPanel to top-center in 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...

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

This is a JS page my friend and I are making. 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...

fabric.js resize canvas to fit screen

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...

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

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...

How do I load SVGs directly in my React component using 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={} className='button--next'> {this.props.label} {NextIcon} </Link> ) } }); But this isn't working as...

d3.js grid moving around when dragging and zooming

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() {".x.axis").call(xAxis);".y.axis").call(yAxis);...

Create a cone with shadows

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...

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

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...

Equivalent of canvas quadraticCurveTo in SVG

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 shows a testbed...

Floating ghost CSS animation

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...

Why WebGL slower than Canvas?

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: I run them in Chrome and Firefox, in both browser the...

Creating SVG elements dynamically

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...

html2canvas does not print jsPlumb Connectors

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){'image/png')) }); An...

adding link_to with image_tag and image path both

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...

Trying to fill a SVG map from wordpress custom categories

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...

Center Aligning an SVG element?

I don't know how to really explain this but how can I center align this logo I have tried the following but it didnt seem to work as intended. .center-logo { display: block; margin: auto; } ...

Creating a responsive cloud shape

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...

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

I used snap.svg library to generate, with javascript, a svg element in my 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...

Cyrllic characters in SVG font

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...

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

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}}' />...

Responsive axis with percentage coordinates

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?...

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

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

Snap SVG .animate callback fires immediately

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...

DrawImage is not drawing in a canvas

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...

Svg set new coordinates with animation on 2 lines simultaneously

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) {...

Determine shape drawn on canvas from stored coordinates in an array

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...

HTML Canvas Width

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...

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

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();...

How to manipulate existing group elements with 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 ="[id='" + oldGroupId + "']"); oldGroup.outerSVG(newGroup); //This is what I want to do but outerSVG is readonly ...

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

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...

Javascript Canvas, can't draw multiple images

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...

Controlling canvas object with range 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:...

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

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...

how to define html5 svg polygon points to create graphics

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...