SVG + Angular2 code sample does not work with interpolation - svg

My goal is to convert code from Angular 1.3 to Angular 2 (with SVG in both cases).
I tried the following simple test code, which works in case #1 that does not involve interpolation, but does not work in case #2 (which uses interpolation), and AFAICS the only difference in the generated SVG code is the inclusion of an extra attribute in the element: class="ng-binding"
Is there a way to suppress the preceding class attribute, or is there another solution?
Btw I wasn't able to get the formatting quite right (my apologies).
Contents of HTML Web page:
<html>
<head>
<title>SVG and Angular2</title>
<script src="quickstart/dist/es6-shim.js"></script>
</head>
<body>
<!-- The app component created in svg1.es6 -->
<my-svg></my-svg>
<script>
// Rewrite the paths to load the files
System.paths = {
'angular2/*':'/quickstart/angular2/*.js', // Angular
'rtts_assert/*': '/quickstart/rtts_assert/*.js', // Runtime assertions
'svg': 'svg1.es6' // The my-svg component
};
System.import('svg');
</script>
</body>
</html>
Contents of the JS file:
import {Component, Template, bootstrap} from 'angular2/angular2';
#Component({
selector: 'my-svg'
})
#Template({
//case 1 works:
inline: '<svg><ellipse cx="100" cy="100" rx="80" ry="50" fill="red"></ellipse></svg>'
//case 2 does not work:
//inline: "<svg>{{graphics}}</svg>"
})
class MyAppComponent {
constructor() {
this.graphics = this.getGraphics();
}
getGraphics() {
// return an array of SVG elements (eventually...)
var ell1 =
'<ellipse cx="100" cy="100" rx="80" ry="50" fill="red"></ellipse>';
return ell1;
}
}
bootstrap(MyAppComponent);

SVG elements do not use the same namespace as HTML elements. When you insert SVG elements into the DOM, they need to be inserted with the correct SVG namespace.
Case 1 works because you are inserting the whole SVG, including the <svg> tags, into the HTML. The browser will automatically use the right namespace because it sees the <svg> tag and knows what to do.
Case 2 doesn't work because you are just inserting an <ellipse> tag and the browser doesn't realise it is supposed be created with the svg namespace.
If you inspect both SVGs with the browser's DOM inspector, and look at the <ellipse> tag's namespace property, you should see the difference.

You can use outerHtml of an HTML element like:
#Component({
selector: 'my-app',
template: `
<!--
<svg xmlns='http://www.w3.org/2000/svg'><ellipse cx="100" cy="100" rx="80" ry="50" fill="red"></ellipse></svg>
-->
<span [outerHTML]="graphics"></span>`
})
export class App {
constructor() {
this.graphics = this.getGraphics();
}
getGraphics() {
// return an array of SVG elements (eventually...)
var ell1 =
'<svg><ellipse cx="100" cy="100" rx="80" ry="50" fill="red"></ellipse></svg>';
return ell1;
}
}
note that the added string has to contain the <svg>...</svg>
See also How can I add a SVG graphic dynamically using javascript or jquery?

Related

Create an interactive SVG component using React

Let's say I have an SVG element with paths for all US states.
<svg>
<g id="nh">
<title>New Hampshire</title>
<path d="m 880.79902,142.42476 0.869,-1.0765 1.09022,..." id="NH" class="state nh" />
</g>
...
</svg>
The SVG data is saved in a separate file with a .svg extension. Say I want to create a React component of that map, with complete control over it so that I can modify the styling of individual states based on some external input.
Using Webpack, as far as I can tell, I have two options for loading the SVG markup: Insert it as raw markup using the raw-loader and create a component using dangerouslySetInnerHTML:
var InlineSvg = React.createClass({
render() {
var svg = require('./' + this.props.name + '.svg');
return <div dangerouslySetInnerHTML={{__html: svg}}></div>;
}
});
or manually convert the markup to valid JSX:
var NewComponent = React.createClass({
render: function() {
return (
<svg>
<g id="nh">
<title>New Hampshire</title>
<path d="m 880.79902,142.42476 0.869,-1.0765 1.09022,..." id="NH" className="state nh" />
</g>
...
</svg>
);
});
Finally, let's say that in addition to the SVG map, there's a simple HTML list of all the states. Whenever a user hovers over a list item, the corresponding SVG path should shift fill color.
Now, what I can't seem to figure out is how to update the React SVG component to reflect the hovered state. Sure, I can reach out into the DOM, select the SVG state by classname and change its color, but that doesn't seem to be the "react" way to do it. A pointing finger would be much appreciated.
PS. I'm using Redux to handle all communication between components.
You need to do two things:
1) Set an event listener on each list item to inform your app of the highlighted item.
<li
onMouseOver={() => this.handleHover('NH')}
onMouseOut={() => this.handleUnhover()}
>
New Hampshire
</li>
2) Capture the data, and propagate it your SVG component.
This is the more complicated part, and it comes down to how you've structured your app.
If your entire app is a single React component, then handleHover would simply update the component state
If your app is divided into multiple components, then handleHover would trigger a callback passed in as a prop
Let's assume the latter. The component methods might look like this:
handleHover(territory) {
this.props.onHighlight(territory);
}
handleUnhover() {
this.props.onHighlight(null);
}
Assuming you have a parent component, which contains both the SVG map and the list, it might look something like this:
class MapWrapper extends React.Component {
constructor(props) {
super(props);
this.state = {
highlighted: null;
};
}
setHighlight(territory) {
this.setState({
highlighted: territory
});
}
render() {
const highlighted = { this.state };
return (
<div>
<MapDiagram highlighted={highlighted} />
<TerritoryList onHighlight={(terr) => this.setHighlight(terr)} />
</div>
);
}
}
The key here is the highlighted state variable. Every time a new hover event occurs, highlighted changes in value. This change triggers a re-render, and the new value is passed onto MapDiagram which can then determine which part of the SVG to highlight.

Scaling a circle in SVG

I have the following SVG code. To scale the circle only, I have to scale the container. I can't scale the circle inside the SVG.
I can access the circle element, but why can't I like other html elements? Is the code scaling the circle or the container?
<html>
<head>
<script>
function scale() {
document.getElementById('container').setAttribute('currentScale', 1.5);
}
</script>
</head>
<body>
<svg height="150" width="150" id="container">
<circle cx="25" r="20" cy="20" fill="blue" id="circle"></circle>
</svg>
<button id="zoom" onclick="scale()">scale</button>
</body>
</html>
I've never tried scaling the whole SVG (using the pure SVG transform attribute). But look like you can just scale each element inside SVG. In this case you have to target (select) the circle first before calling setAttribute on it to modify the transform attribute to scale(1.5,1.5) like this:
function scale() {
document.querySelector("#container > circle")
.setAttribute('transform', 'scale(1.5,1.5)');
}
Here is the Demo. Note that you have to select the option No Wrap - in <head> (on the right hand in the Frameworks & Extensions section). Or better you should attach click handler right in JS code editor (not inline as an attribute in HTML code).
Here is one way to scale just the circle using JS:
Demo: http://jsfiddle.net/hb4nnau0/1/
For convenience, give your circle a transform attribute with no change in scale added. (Alternatively you can add this programmatically on demand.)
`
In your event handler, modify the scale of this transform element:
var circle = document.querySelector('circle'); // Or however, e.g. by id
var scale = circle.transform.animVal.getItem(0); // The first transform
scale.setScale(4,3); // Modify the transform

Using Meteor to create SVG in template works, but not in #each loop

Update: as of February 2014, Meteor supports reactive SVG, so no workaround is necessary.
Meteor 0.5.9
I would like to create a group of shapes, one for each document in the collection. I can create shapes one at a time in a template, but not inside of an {{#each loop}}.
This works:
<Template name="map">
<svg viewBox="0 0 500 600" version="1.1">
<rect x="0" y="0" width="100" height="100" fill={{color}}/>
</svg>
</Template>
Template.map.color = function() {
return "green";
};
This does not:
<Template name="map">
<svg viewBox="0 0 500 600" version="1.1">
{{#each colors}}
<rect x="0" y="0" width="100" height="100" fill={{color}}/>
{{/each}}
</svg>
</Template>
Template.map.colors = function() {
return [{color: "red"}, {color: "blue"}];
}
Anything I try to create inside of using {{#each}} just doesn't show up, even though I can create them manually, even with attributes inserted by Meteor through the template.
I also tried just sending a single object {color: "red"} to the template and using {{#with colors}}, and that does not work either. In addition to the SVG, I've also put plain s into the templates to make sure information gets to the template correctly, and those are all working as expected, with {{#each}} and with {{#with}}.
Should I be able to do what I'm trying to do?
(Updated April 1, 2013)
Found a way that combines Handlebars with insertion by Javascript. Have to give credit to this blog entry for figuring this one out:
http://nocircleno.com/blog/svg-and-handlebars-js-templates/
I created the following two files, placed them inside the client folder of a new Meteor directory and I got the html successfully.
Testing.js:
<head>
<title>testing</title>
</head>
<body>
</body>
<template name="map">
<svg version="1.1" xmlns="http://www.w3.org/2000/svg">
{{#each colors}}
<rect x="0" y="{{yPosition}}" width="100" height="100" fill="{{color}}"/>
{{/each}}
</svg>
</template>
Testing.html:
(function () {
var count = 0;
Template.map.yPosition = function() {
count++;
return (count-1) * 100;
};
Template.map.colors = function() {
return [{color: "red"}, {color: "blue"}];
};
Meteor.startup(function() {
var svgElement = document.createElementNS("http://www.w3.org/2000/svg", "svg");
svgElement.width = 500;
svgElement.height = 600;
document.getElementsByTagName("body")[0].appendChild(svgElement);
var svgFragment = new DOMParser().parseFromString(Template.map(), "text/xml");
svgElement.appendChild(svgFragment.documentElement);
});
})();
I came across the same problem experimenting with Meteor and SVG elements and discovered that you can add elements and get them to show up with the two methods below. One option is to just wrap the elements in the each loop in an <svg></svg>, like this:
<svg viewbox="0 0 100 100" xmlns="http://www.w3.org/2000/svg">
{{#each pieces}}
<svg xmlns="http://www.w3.org/2000/svg"><circle cx="{{x}}" cy="{{y}}" r="1" fill="{{color}}"></circle></svg>
{{/each}}
</svg>
Another options is to (on template render) create an svg element with jQuery that contains the element you want to insert, then use jQuery to grab that inner element and insert it into the svg element already in the DOM, like so (in coffeescript):
for piece in Pieces.find().fetch()
$el = $("<svg><circle cx='#{piece.x}' cy='#{piece.y}' r='1' class='a'></circle></svg>")
$el.find('circle').appendTo #$('svg')
You could also use something like d3 or RaphaelJS to do the inserting. You can even make the individual elements reactive to your Collection and animate easily by using a library like d3 in the Collection observer callbacks like so (again, coffeescript):
Pieces.find().observe {
added: (piece)=>
# using jquery (could use d3 instead)
$el = $("<svg><circle cx='#{piece.x}' cy='#{piece.y}' r='1' fill='#{piece.color}' data-id='#{piece._id}'></circle></svg>")
$el.find('circle').appendTo #$('svg')
changed: (newPiece, oldPiece)=>
# using d3 to animate change
d3.select("[data-id=#{oldPiece._id}]").transition().duration(1000).attr {
cx: newPiece.x
cy: newPiece.y
fill: newPiece.color
}
removed: (piece)=>
#$("[data-id=#{piece._id}]").remove()
}
These methods seem to work in latest Chrome, Safari, Firefox browsers on Mac, but I haven't tested in others.
According to the Using Blaze page, Meteor will have first class support of SVG when Blaze is released.

One SVG file, many SVG gradients inside

I’m making a set of buttons which use dynamic gradients. I’ve taken care of Firefox 3.6+ and WebKit by using their proprietary CSS extensions and all I need to do is support Opera, iOS and IE9 by using background-image: url("gradient.svg").
This is relatively easy, I made an SVG file, linked it and got it working. However, I’m making a set so I need at least 6 gradients. When I normally do it in images, I create a sprite for fast HTTP access. I’m not sure how to achieve this in SVG – can I use one file and access different parts of its XML by using #identifiers, like XBL does?
My current SVG:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN"
"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<svg version="1.1" xmlns="http://www.w3.org/2000/svg">
<defs>
<linearGradient id="select-gradient" x1="0" x2="0" y1="0" y2="1">
<stop offset="0%" stop-color="rgb(231,244,248)"/>
<stop offset="100%" stop-color="rgb(207,233,241)"/>
</linearGradient>
<style type="text/css">
rect {
fill: url(#select-gradient);
}
</style>
</defs>
<rect x="0" y="0" rx="6" ry="6" height="100%" width="100%"/>
</svg>
And then I have CSS:
.button-1 {
background-image: url("gradient-1.svg");
}
.button-2 {
background-image: url("gradient-2.svg");
}
I want to do something like this:
.button-1 {
background-image: url("gradient.svg#gradient1");
}
.button-2 {
background-image: url("gradient.svg#gradient2");
}
Is it even possible? Can you help me out? I really don’t wanna push 6 XML files when I can do it with one.
If you just want gradients for button backgrounds, most of this can be acheived in css. For the remaining browsers, ie6 + can user ms filters:
http://msdn.microsoft.com/en-us/library/ms532847.aspx
iOS uses webkit to render, so you can use -webkit vendor prefix. Unfortunately you will still need svg for opera, but this may make it easier (or just use a normal image sprite for opera's 1% of users)
in theory - according to SVG documentation #Params it is possible. You could use 2 params for setting up both colors, you could create multiple rects with different gradients, height set to 0 and then make only one 100% (like ?gradient2=100%)
What you could do is load your SVG file that contains all of the definitions first, and then load your other SVG files.
Using Firefox, jQuery SVG , and a minor shot of framework...
in your XHTML:
<div id="common_svg_defs"><!--ieb--></div>
<div id="first_thing"><!--ieb--></div>
<div id="second_thing"><!--ieb--></div>
in your JavaScript:
var do_stuff = function()
{
// load your common svg file with this goo.
$('#common_svg_defs').svg({
loadURL: 'path/filename.svg',
onLoad: function(svg, error) { run_test(svg, error);} });
}
var run_test = function(svg, error)
{
if (typeof(error) !== "undefined")
{
if (typeof(console.log) !== "undefined")
{
console.log(error);
}
}
else
{
// load your other svg files here, or just
// set a flag letting you know it's ready.
$('#first_thing').svg({
loadURL: 'path/anotherfilename.svg',
onLoad: function(svg, error) { somecallback(svg, error);} });
$('#second_thing').svg({
loadURL: 'path/anotherfilename.svg',
onLoad: function(svg, error) { somecallback(svg, error);} });
}
}
Because the id can be found in the documents scope, the SVG are capable of finding the IRI reference.
This allows you to define things once (that would not otherwise be defined in a css) and avoid id collisions.
Cheers,
Christopher Smithson

Adding hammer.js actions to a svg rectangle in a component Angular2

I’m working on an Angular 2 app and I have a component which inclundes a simple SVG rectangle, I’m trying to use Hammer.js library to be able to deplace and reform this SVG rectangle inside the view of my component,
therefore I’ve done those steps:
I’ve downloaded and copied 3 files to my project repository
hammer.js
hammer.min.js
hammer.min.map
I’ve added this script tag to my index head:
<script src="dev/jqueryLibs/hammer/hammer.js" type="text/javascript"></script>
And I get this error in the console:
Uncaught TypeError: Cannot read property 'addEventListener' of null
I’ve tried to import it in my component and add reference betwen the methode and the svg element, like this:
TS.File contents:
import {Component, ElementRef, AfterViewInit } from 'angular2/core';
import {bootstrap} from 'angular2/platform/browser';
import {FORM_DIRECTIVES} from "angular2/common";
#Component({
selector: 'content',
templateUrl: 'content.component.html',
styleUrls: ['content.component.css'],
directives: [FORM_DIRECTIVES],
})
export class ContentComponent implements AfterViewInit{
static hammerInitialized = false;
constructor(private el:ElementRef)
{}
ngAfterViewInit() {
console.log('in ngAfterViewInit');
if (!ContentComponent.hammerInitialized) {
console.log('hammer not initialised');
var myElement = document.getElementById('test1');
var hammertime = new Hammer(myElement);
hammertime.on('swiperight', function(ev) {
console.log('caught swipe right');
console.log(ev);
});
ContentComponent.hammerInitialized = true;
} else {
console.log('hammer already initialised');
}
}
View file contents:
<svg class="simulation">
<rect id="test1" x="20" y="500" height="150" width="200" style="stroke:#EC9A20;stroke-width: 15; fill: none"/>
</svg>
Therefore I still am not able to move my SVG rectangle and it seems that Hammer.js is not even running according to this console message:
hammer not initialised
Anybody can tell me where is the error or what should I do?
This was resolved: The script tag of hammer declaration
must be placed after the jquery-ui library declaration in HTML file.
<script src="./dev/resources/js/jquery.js"></script>
<script src="./dev/resources/js/jquery-ui.js"></script>
<script src="./dev/jqueryLibs/jquery-1.12.1.min.js"></script>
<script src="./dev/jqueryLibs/jquery-migrate-1.2.1.min.js"></script>
<!--importer ici la js de bootstrap-->
<script src="node_modules/bootstrap/dist/js/bootstrap.js"></script>
<!--Importer ici hammer.js-->
<script src="dev/jqueryLibs/hammer/hammer.js" type="text/javascript"></script>

Resources