I want to add a modified SVG object to a map instead of the original file.
$.ajax({
method: 'get',
url: 'zones.svg',
dataType: 'html'
}).then(function (value) {
var svg = $(value);
var width = svg.attr("width");
var height = svg.attr("height");
var zoneBounds = [[-height, 0], [0, width]];
L.imageOverlay('zones.svg', zoneBounds, {
opacity: 0.5
}).addTo(mymap);
});
Is there a way to override the original imageOverlay() method to accept an object instead of an URL of the file?
Or is there another built-in method?
You can draw some inspiration from the VideoOverlay class : extend ImageOverlay and override _initImage to create a SVG node instead of an image.
Your class definition could look like this
var SVGOverlay = L.ImageOverlay.extend({
options: {
},
_initImage: function () {
var wasElementSupplied = this._url.tagName.toLowerCase() === 'svg';
var svg = this._image = wasElementSupplied ? this._url : L.DomUtil.create('svg');
}
});
and based on your example, you could set it up like this
var svgdomnode = svg.get(0); // your svg looks like a jQuery object, let's use a DOM node
var overlay = new SVGOverlay(svgdomnode, zoneBounds).addTo(mymap);
And a demo where an SVG node is inserted as a layer and modified when you click on a button.
var SVGOverlay = L.ImageOverlay.extend({
options: {
},
_initImage: function () {
var wasElementSupplied = this._url.tagName.toLowerCase() === 'svg';
var svg = this._image = wasElementSupplied ? this._url : L.DomUtil.create('svg');
}
});
var map = L.map('map').setView([37.8, -96], 4);
L.tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png').addTo(map);
var bounds = L.latLngBounds([[ 32, -130], [ 13, -100]]);
map.fitBounds(bounds);
var svg = document.getElementById('src').content.querySelector('svg');
var overlay = new SVGOverlay(svg, bounds).addTo(map);
var n = 0;
document.querySelector('button').addEventListener('click', function() {
var rect = document.createElementNS("http://www.w3.org/2000/svg", 'rect');
rect.setAttribute('x', 20*n);
rect.setAttribute('width', 20);
rect.setAttribute('height', 20);
rect.setAttribute('fill', '#0000ff');
svg.appendChild(rect);
n++;
});
html, body {
height: 100%;
margin: 0;
}
#svg {
width: 100%;
height: 100%;
}
#map {
width: 100%;
height: 100%;
}
button {position: absolute; left:100px; top: 0;z-index:10000}
<link rel="stylesheet" href="https://unpkg.com/leaflet#1.2.0/dist/leaflet.css" integrity="sha512-M2wvCLH6DSRazYeZRIm1JnYyh22purTM+FDB5CsyxtQJYeKq83arPe5wgbNmcFXGqiSH2XR8dT/fJISVA1r/zQ==" crossorigin=""/>
<script src="https://unpkg.com/leaflet#1.2.0/dist/leaflet.js" integrity="sha512-lInM/apFSqyy1o6s89K4iQUKg6ppXEgsVxT35HbzUupEVRh2Eu9Wdl4tHj7dZO0s1uvplcYGmt3498TtHq+log==" crossorigin=""></script>
<template id='src'>
<svg xmlns="http://www.w3.org/2000/svg" width='100' height='100'>
<rect width="100%" height="100%" fill="red"/>
<circle cx="50%" cy="50%" r="30%" fill="green"/>
</svg>
</template>
<div id='map'></div>
<button>Click to add a square</button>
Release 1.5.0 includes this approach as layer type SVGOverlay.
Related
I would like to save my openlayers map as PDF.
Unfortunately all the options I tried don't work.
The first option, I guess the easiest one was here:
https://jsfiddle.net/Ljnya5gp/1/
from which I developed something like this:
function createPdf() {
var doc = new jsPDF();
source = $('#map')[0];
specialElementHandlers = {
'#map': function (element, renderer) {
return true
}
};
doc.fromHTML(
source,
15,
15,
{
'width': 170,
'elementHandlers': specialElementHandlers
}
);
doc.save('Area 5 map - alterations.pdf')
but the script downloads only blank document for me.
I want to have this section downloaded (from index.html)
<div id="map">
<div id="popup" class="ol-popup">
<div id="popup-content"></div>
</div>
</div>
Why the output PDF document is blank? Is it caused by Map script, which is embedded into the HTML file?
My <div id="map"> refers to the script attached to the HTML file as the:
The jsfiddle can be found here:
https://jsfiddle.net/rjetdvyo/
Is it something which causes the problem too?
UPDATE:
Based on the answer below I formed something like this:
function createPdf() {
var mapElement = $("#map");
html2canvas(mapElement, {
useCORS: true,
onrendered: function (canvas) {
var img = canvas.toDataURL("image/jpeg,1.0");
var pdf = new jsPDF();
pdf.addImage(img, 'JPEG', 15, 40, 180, 180);
pdf.save('a4.pdf')
}
});
}
var map = (document.getElementById('map'), createPdf);
The printpdf button only refreshes the page.
I think everything is ok, it was showing blank because you didn't write any text into div. Have a look:
function createPdf() {
var doc = new jsPDF();
source = $('#map')[0];
specialElementHandlers = {
'#map': function (element, renderer) {
return true
}
};
doc.fromHTML(
source,
15,
15,
{
'width': 170,
'elementHandlers': specialElementHandlers
}
);
doc.save('Area 5 map - alterations.pdf')
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"
integrity="sha512-bLT0Qm9VnAYZDflyKcBaQ2gg0hSYNQrJ8RilYldYQ1FxQYoCLtUjuuRuZo+fjqhx/qtq/1itJ0C2ejDxltZVFg=="
crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.5.3/jspdf.min.js"></script>
<div id="map">
<div id="popup" class="ol-popup">
Hello
<div id="popup-content"><h1>Hello, this is a H1 tag</h1></div>
</div>
</div>
<button onclick="createPdf()">generate PDF</button>
Update:
By using jsPDF and html2canvas both, you can achieve your goal.
html2canvas creates a canvas object from the DOM element. From canvas, you can create an image and finally convert that image into pdf by jsPDF. Have a look at the code below:
function createPdf() {
var mapElement = $("#map-canvas");
html2canvas(mapElement, {
useCORS: true,
onrendered: function (canvas) {
var img = canvas.toDataURL("image/jpeg,1.0");
var pdf = new jsPDF();
pdf.addImage(img, 'JPEG', 15, 40, 180, 180);
pdf.save('a4.pdf')
}
});
}
// if HTML DOM Element that contains the map is found...
if (document.getElementById('map-canvas')) {
// Coordinates to center the map
var myLatlng = new google.maps.LatLng(52.525595, 13.393085);
// Other options for the map, pretty much selfexplanatory
var mapOptions = {
zoom: 14,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
// Attach a map to the DOM Element, with the defined settings
var map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
}
#map-canvas {
width: 500px;
height: 400px;
}
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false" type="text/javascript"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"
integrity="sha512-bLT0Qm9VnAYZDflyKcBaQ2gg0hSYNQrJ8RilYldYQ1FxQYoCLtUjuuRuZo+fjqhx/qtq/1itJ0C2ejDxltZVFg=="
crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.5.3/jspdf.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/0.4.1/html2canvas.min.js"
integrity="sha512-s/XK4vYVXTGeUSv4bRPOuxSDmDlTedEpMEcAQk0t/FMd9V6ft8iXdwSBxV0eD60c6w/tjotSlKu9J2AAW1ckTA=="
crossorigin="anonymous"></script>
<button onclick="createPdf()">generate PDF</button>
<div id="map-canvas"></div>
Update 2:
I don't know which ways you're following. Just follow these steps to get the job done:
Follow these steps first.
Replace your index.js code by this:
import 'ol/ol.css';
import { Map, View } from 'ol';
import TileLayer from 'ol/layer/Tile';
import OSM from 'ol/source/OSM';
const map = new Map({
target: 'map',
layers: [
new TileLayer({
source: new OSM()
})
],
view: new View({
center: [0, 0],
zoom: 0
})
});
var exportButton = document.getElementById('export-pdf');
exportButton.addEventListener(
'click',
function () {
exportButton.disabled = true;
document.body.style.cursor = 'progress';
// var format = [297, 210];
var resolution = 72; // The term 72 dpi(dots per inch) is used to express the resolution of a screen
var dim = [297, 210]; // a4 size's dimension
var width = Math.round((dim[0] * resolution) / 25.4);
var height = Math.round((dim[1] * resolution) / 25.4);
var size = map.getSize();
var viewResolution = map.getView().getResolution();
map.once('rendercomplete', function () {
var mapCanvas = document.createElement('canvas');
mapCanvas.width = width;
mapCanvas.height = height;
var mapContext = mapCanvas.getContext('2d');
Array.prototype.forEach.call(
document.querySelectorAll('.ol-layer canvas'),
function (canvas) {
if (canvas.width > 0) {
var opacity = canvas.parentNode.style.opacity;
mapContext.globalAlpha = opacity === '' ? 1 : Number(opacity);
var transform = canvas.style.transform;
// Get the transform parameters from the style's transform matrix
var matrix = transform
.match(/^matrix\(([^\(]*)\)$/)[1]
.split(',')
.map(Number);
// Apply the transform to the export map context
CanvasRenderingContext2D.prototype.setTransform.apply(
mapContext,
matrix
);
mapContext.drawImage(canvas, 0, 0);
}
}
);
var pdf = new jsPDF('landscape');
pdf.addImage(
mapCanvas.toDataURL('image/jpeg'),
'JPEG',
0,
0,
dim[0],
dim[1]
);
pdf.save('map.pdf');
// Reset original map size
map.setSize(size);
map.getView().setResolution(viewResolution);
exportButton.disabled = false;
document.body.style.cursor = 'auto';
});
// Set print size
var printSize = [width, height];
map.setSize(printSize);
var scaling = Math.min(width / size[0], height / size[1]);
map.getView().setResolution(viewResolution / scaling);
},
false
);
Replace your index.html by this:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Using Parcel with OpenLayers</title>
<style>
#map {
width: 400px;
height: 250px;
}
</style>
</head>
<body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.5.3/jspdf.min.js"></script>
<button id="export-pdf" >Export PDF</button>
<div id="map"></div>
<script src="./index.js"></script>
</body>
</html>
I follow the Documentation that Konva have.
https://konvajs.github.io/docs/select_and_transform/Basic_demo.html
and
https://konvajs.github.io/docs/sandbox/Image_Resize.html
But the problem is they only have transform demo for rectangle shape. My plan is to have it on image. But so far I cant get it right. Here's my example code.
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://rawgit.com/konvajs/konva/master/konva.min.js"></script>
<meta charset="utf-8">
<title>Konva Image Resize Demo</title>
<style>
body {
margin: 0;
padding: 0;
overflow: hidden;
background-color: #F0F0F0;
}
</style>
</head>
<body class="col-md-12">
<div id="container" class="col-md-10">
</div>
<script>
var width = window.innerWidth;
var height = window.innerHeight;
function testFunction() {
addCanvas();
}
function update(activeAnchor) {
var group = activeAnchor.getParent();
var topLeft = group.get('.topLeft')[0];
var topRight = group.get('.topRight')[0];
var bottomRight = group.get('.bottomRight')[0];
var bottomLeft = group.get('.bottomLeft')[0];
var image = group.get('Image')[0];
var anchorX = activeAnchor.getX();
var anchorY = activeAnchor.getY();
// update anchor positions
switch (activeAnchor.getName()) {
case 'topLeft':
topRight.setY(anchorY);
bottomLeft.setX(anchorX);
break;
case 'topRight':
topLeft.setY(anchorY);
bottomRight.setX(anchorX);
break;
case 'bottomRight':
bottomLeft.setY(anchorY);
topRight.setX(anchorX);
break;
case 'bottomLeft':
bottomRight.setY(anchorY);
topLeft.setX(anchorX);
break;
}
image.position(topLeft.position());
var width = topRight.getX() - topLeft.getX();
var height = bottomLeft.getY() - topLeft.getY();
if (width && height) {
image.width(width);
image.height(height);
}
}
var stage = new Konva.Stage({
container: 'container',
width: width,
height: height
});
var layer = new Konva.Layer();
stage.add(layer);
// darth vader
var darthVaderImg = new Konva.Image({
width: 200,
height: 137,
name: 'imgs'
});
// yoda
var yodaImg = new Konva.Image({
width: 93,
height: 104,
name: 'imgs'
});
var darthVaderGroup = new Konva.Group({
x: 180,
y: 50,
draggable: true,
id: 'test1',
name: 'Imgs'
});
var num = 0;
function addCanvas() {
var test = new Konva.Group({
x: 200,
y: 100,
draggable: true
});
var testImg = new Konva.Image({
width: 93,
height: 104
});
layer.add(test);
test.add(testImg);
console.log('test');
var imageObjs = new Image();
imageObjs.onload = function() {
testImg.image(imageObjs);
layer.draw();
};
imageObjs.src = './pic/test2.png';
}
layer.add(darthVaderGroup);
darthVaderGroup.add(darthVaderImg);
var yodaGroup = new Konva.Group({
x: 20,
y: 110,
draggable: true,
id: 'Imgs',
});
layer.add(yodaGroup);
yodaGroup.add(yodaImg);
var imageObj1 = new Image();
imageObj1.onload = function() {
darthVaderImg.image(imageObj1);
layer.draw();
};
imageObj1.src = './pic/test2.png';
var imageObj2 = new Image();
imageObj2.onload = function() {
yodaImg.image(imageObj2);
layer.draw();
};
imageObj2.src = './pic/test1.jpg';
stage.on('click', function(e) {
if (e.target === stage) {
stage.find('Transformer').destroy();
layer.draw();
return;
}
// do nothing if clicked NOT on our rectangles
if (!e.target.hasName('imgs')) {
return;
}
// remove old transformers
// TODO: we can skip it if current rect is already selected
stage.find('Transformer').destroy();
// create new transformer
var tr = new Konva.Transformer();
layer.add(tr);
tr.attachTo(e.target);
layer.draw();
});
function addTrans(e) {
}
</script>
</body>
</html>
The output
Here's the output. Whenever I click the image the transform will be out of place and will on stay in 1 place.
I finally figure it out. Turn out I place the draggable in the wrong place. I put the draggable into the Konva.Image instead in the group.
Thanks
<!DOCTYPE html>
<html>
<head>
<title>D3.js GoogleMap Voronoi Diagram</title>
<script src="http://d3js.org/d3.v3.min.js"></script>
<script src="http://shimz.me/example/d3js/geo_example/geo_template/topojson.v0.min.js"> </script>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js? sensor=false"></script>
<style type="text/css">
html, body{
margin: 0px;
padding: 0px;
}
html, body, #map_canvas {
width: 100%;
height: 100%;
}
.SvgOverlay {
position: relative;
width: 900px;
height: 600px;
}
.SvgOverlay svg {
position: absolute;
top: -4000px;
left: -4000px;
width: 8000px;
height: 8000px;
}
</style>
</head>
<body>
<div id="map_canvas"></div>
<br>
<script type="text/javascript">
d3.json('bus-stops.json', function(pointjson){
main(pointjson);
});
function main(pointjson) {
//Google Map
var map = new google.maps.Map(document.getElementById('map_canvas'), {
zoom: 14,
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: new google.maps.LatLng(1.290270,103.851959),
});
var overlay = new google.maps.OverlayView(); //OverLay
overlay.onAdd = function () {
var layer = d3.select(this.getPanes().overlayLayer).append("div").attr("class", "SvgOverlay");
var svg = layer.append("svg");
var svgoverlay = svg.append("g").attr("class", "AdminDivisions");
overlay.draw = function () {
var markerOverlay = this;
var overlayProjection = markerOverlay.getProjection();
//Google Map
var googleMapProjection = function (coordinates) {
var googleCoordinates = new google.maps.LatLng(coordinates[1], coordinates[0]);
var pixelCoordinates = overlayProjection.fromLatLngToDivPixel(googleCoordinates);
return [pixelCoordinates.x + 4000, pixelCoordinates.y + 4000];
}
var pointdata = pointjson.lat;
console.log(pointdata);
var positions = [];
pointdata.forEach(function(d) {
positions.push(googleMapProjection(d.lat,d.lng));
});
var polygons = d3.geom.voronoi(positions);
var pathAttr ={
"d":function(d, i) { return "M" + polygons[i].join("L") + "Z"},
stroke:"red",
fill:"none"
};
svgoverlay.selectAll("path")
.data(pointdata)
.attr(pathAttr)
.enter()
.append("svg:path")
.attr("class", "cell")
.attr(pathAttr)
var circleAttr = {
"cx":function(d, i) { return positions[i][0]; },
"cy":function(d, i) { return positions[i][1]; },
"r":2,
fill:"red"
}
svgoverlay.selectAll("circle")
.data(pointdata)
.attr(circleAttr)
.enter()
.append("svg:circle")
.attr(circleAttr)
};
};
overlay.setMap(map);
};
</script>
</body>
</html>
The data file is of the structure:
[{"no":"10009","lat":"1.28210155945393","lng":"103.81722480263163",
"name":"Bt Merah Int"},
{"no":"10011","lat":"1.2777380589964","lng":"103.83749709165197",
"name":"Opp New Bridge Rd Ter"}]
It is also giving an error in console:
TypeError: pointdata is undefined. I am trying to plot using the example: http://bl.ocks.org/shimizu/5610671
I am getting undefined for pointjson using console.log(). Please suggest how do I get the co-ordinate values in pointjson
I am loading an svg into Fabric which has child elements. I'm grouping them using groupSVGElements().
I need to be able select each child element - that is an onclick event that allows me to select a child object.
I've thrown together this fiddle http://jsfiddle.net/AnQW5/2/
Although I can list out the child objects of the group via getObjects, theres no way that I can see to determine which object was clicked. So :
canvas.observe('object:selected', function(e) {
console.log(e.target.getObjects());
// ???
});
Any ideas?
You can use
canvas.add.apply instead groupSVGElements, so you can :
have each element to manipulate
var shapesSvg = '<?xml version="1.0" encoding="UTF-8" standalone="no"?><svg version="1.1" xmlns:svg="http://www.w3.org/2000/svg" xmlns="http://www.w3.org/2000/svg" width="320" height="240" viewBox="0 0 320 240"><rect id="rect" x="5" y="50" width="100" height="100" style="fill: rgb(255,0,0);"></rect> <circle id="circle" cx="165" cy="100" r="50" style="fill: rgb(0,255,0);"/></svg>';
var canvas = new fabric.Canvas('canvas');
canvas.setHeight($(window).height());
canvas.setWidth($(window).width());
fabric.loadSVGFromString(shapesSvg, function(objects, options) {
canvas.add.apply(canvas, objects);
canvas.renderAll();
});
html,
body {
margin: 0;
padding: 0;
width: 100%;
height: 100%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.5.0/fabric.min.js"></script>
<canvas id="canvas"></canvas>
Description
The following code detects any object on the screen by it's color, not the best thought.
Code
var $canvas = {
activePaths: []
};
// Bind to `onMouseDown` event.
function onMouseDown = function (options) {
var mousePos = canvas.getPointer(options.e);
mousePos.x = parseInt(mousePos.x);
mousePos.y = parseInt(mousePos.y);
var width = canvas.getWidth();
var height = canvas.getHeight();
var pixels = canvas.getContext().getImageData(0, 0, width, height);
var pixel = (mousePos.x + mousePos.y * pixels.width) * 4;
var activePathsColor = new fabric['Color']('rgb(' + pixels.data[pixel] + ',' + pixels.data[pixel + 1] + ',' + pixels.data[pixel + 2] + ')');
var colorHex = '#' + activePathsColor.toHex().toLowerCase();
var activeObject = canvas.getActiveObject();
var activePath = [];
// Check if active objects are type of `group`, if so push the selected path.
if(activeObject.type == 'group') {
for (var i = 0; i < activeObject.getObjects().length; i++) {
var path = activeObject.getObjects()[i];
if (path.getFill().toLowerCase() == colorHex) {
$canvas.activePaths.push(path);
}
}
}
}
References
Events: http://fabricjs.com/events/
I render an inline SVG in a website, and have to enable the user to add and modify texts in that SVG, in a WYSIWYG manner. Basically I need something that works like svg-edit. However I don't need a fully WYSIWYG editor, but just the inline text editing part. I have looked at svg-edit's source code and it seems to be very hard to extract only that part of it.
So what I am looking for is an easy way (maybe with a third-party library) to implement inline SVG text editing. I already thought about replacing the SVG text with an HTML text input when focused, but the text must be rendered when in edit-mode exactly as it is rendered in the resulting SVG.
I made a fiddle that created editable text wherever you click in an SVG. A final step would be to grab the HTML text and put it in an SVG element.
http://jsfiddle.net/brx3xm59/
Code follows:
var mousedownonelement = false;
window.getlocalmousecoord = function (svg, evt) {
var pt = svg.createSVGPoint();
pt.x = evt.clientX;
pt.y = evt.clientY;
var localpoint = pt.matrixTransform(svg.getScreenCTM().inverse());
localpoint.x = Math.round(localpoint.x);
localpoint.y = Math.round(localpoint.y);
return localpoint;
};
window.createtext = function (localpoint, svg) {
var myforeign = document.createElementNS('http://www.w3.org/2000/svg', 'foreignObject')
var textdiv = document.createElement("div");
var textnode = document.createTextNode("Click to edit");
textdiv.appendChild(textnode);
textdiv.setAttribute("contentEditable", "true");
textdiv.setAttribute("width", "auto");
myforeign.setAttribute("width", "100%");
myforeign.setAttribute("height", "100%");
myforeign.classList.add("foreign"); //to make div fit text
textdiv.classList.add("insideforeign"); //to make div fit text
textdiv.addEventListener("mousedown", elementMousedown, false);
myforeign.setAttributeNS(null, "transform", "translate(" + localpoint.x + " " + localpoint.y + ")");
svg.appendChild(myforeign);
myforeign.appendChild(textdiv);
};
function elementMousedown(evt) {
mousedownonelement = true;
}
$(('#thesvg')).click(function (evt) {
var svg = document.getElementById('thesvg');
var localpoint = getlocalmousecoord(svg, evt);
if (!mousedownonelement) {
createtext(localpoint, svg);
} else {
mousedownonelement = false;
}
});
Edit: Update sample to work with Edge. Attributes of client bounding box are different there - it may be the issue with older IPads and Safari reported below. I have tested this on Edge, Chrome, FF ,Safari (Mac) and Chrome, FF, Safari(IPad). On Edge, the cursor is broken but editing still works.
I realize this is an old question, but the contentEditable trick is still all we have if, you don't want to implement your own input element behavior. If you use a single svg text node (as opposed to HTML foreign object) as an overlay to the text under edit, you can get true WSYWIG in that you can use the same font etc. as the original text. You can also choose which elements can be edited. Yes the cursor is weird in Safari. A fiddle that demonstrates this can be found here:
https://jsfiddle.net/AaronDavidNewman/ta0jhw1q/
HTML/SVG:
<div id="yyy">
<div id="xxx">
<svg width="500" height="500" viewBox="0 0 500 500">
<text x="0" y="25" id="target1" font-size="1.8em">Change me</text>
<text x="0" y="50" id="targetx" font-size="1.8em">You can't edit me</text>
<text x="0" y="75" id="target2" font-size="1.8em">Edit me</text>
<text x="0" y="100" id="targety" font-size="1.8em">You can't edit me</text>
<text x="0" y="125" id="target3" font-size="1.8em">Improve me</text>
</svg>
</div>
<div id="aaa" contentEditable="true" class="hide">
<svg width="500" height="50" viewBox="0 0 500 50">
<text x="0" y="50" id="input-area" font-size="1.8em"></text>
</svg>
</div>
</div>
Javascript:
// Create in-place editable text elements in svg. Click inside the element
// to edit it, and away to stop editing and switch to another element
var editing = false;
var svgns = "http://www.w3.org/2000/svg";
$('body').css('overflow','hidden');
// Poll on changes to input element. A better approach might be
// to update after keyboard events
var editElement = function(aaa, xxx) {
setTimeout(function() {
xxx.textContent = aaa.textContent;
if (editing) {
editElement(aaa, xxx);
}
}, 250);
}
// Make sure the input svg element is placed directly over the
// target element
var fixOffset = function(aaa, xxx) {
var svg = $('#xxx').find('svg')[0];
$('.underEdit').remove();
var rect = xxx.getBoundingClientRect();
var offset = aaa.getBoundingClientRect();
$('#aaa').css('left', rect.left + (rect.left - offset.left));
$('#aaa').css('top', rect.top + (rect.top - offset.top));
var bb = xxx.getBBox();
var margin = 10;
}
// Based on a click in the element svg area, edit that element
var editId = function(id) {
var aaa = document.getElementById('input-area');
var xxx = document.getElementById(id);
var rect = xxx.getBoundingClientRect();
$('#aaa').css('left', rect.left);
$('#aaa').css('top', rect.top);
setTimeout(function() {
fixOffset(aaa, xxx);
}, 1);
aaa.textContent = xxx.textContent;
editing = true;
editElement(aaa, xxx);
}
// see if a click intersects an editable element
var getIntersection = function(objs, point) {
var rv = null;
$(objs).each(function(ix, obj) {
var i1 = point.x - obj.box.x;
var i2 = point.y - obj.box.y;
// If inside the box, we have an element to edit
if (i1 > 0 && i1 < obj.box.width && i2 > 0 && i2 < obj.box.height) {
rv = obj;
return false;
} else if (i1 > -10 && i1 < obj.box.width + 10 && i2 > -10 && i2 < obj.box.height + 10) {
// edit a nearby click, if a better match isn't found
rv = obj;
}
});
return rv;
}
// bind editable elements to mouse click
var bind = function(texts) {
var objs = [];
// find geometry of each editable element
texts.forEach((id) => {
var el = document.getElementById(id);
var bbox = el.getBoundingClientRect();
bbox = { x: bbox.left, y: bbox.top, width: bbox.width, height: bbox.height };
objs.push({id: id, box: bbox });
});
// bind click event globally, then try to find the intersection.
$(document).off('click').on('click', function(ev) {
var point = {x: ev.clientX, y: ev.clientY };
console.log('x:' + point.x + 'y:' + point.y);
var obj = getIntersection(objs, point);
if (obj && !editing) {
$('#aaa').removeClass('hide');
editing = true;
console.log('start edit on ' + obj.id);
editId(obj.id);
} else if (!obj) {
{
$('#aaa').addClass('hide');
editing = false;
$('.underEdit').remove();
console.log('stop editing');
}
}
});
}
bind(['target1', 'target2', 'target3']);
CSS:
#yyy {
position: relative;
width: 500px;
height: 500px;
}
#xxx {
position: absolute;
left: 100px;
top: 100px;
z-index: 1;
}
#aaa {
position: absolute;
left: 100px;
top: 100px;
z-index: 2;
overflow:hidden;
}
.hide {
display: none;
}
Here is an example where you can get and change the text from a textnode. I suggest to write a JavaScript function that puts an editable div or something like that in place of the textnode and when saved replaces the textnode with the innerHTML of the div.
Please post the final code here when you succeed.
<html>
<head>
<script>
function svgMod(){
var circle1 = document.getElementById("circle1");
circle1.style.fill="blue";
}
function svgMod2(){
var circle1 = document.getElementById("circle1");
t1.textContent="New content";
}
</script>
</head>
<body>
<svg id="svg1" xmlns="http://www.w3.org/2000/svg" style="width: 800; height: 1000">
<circle id="circle1" r="100" cx="134" cy="134" style="fill: red; stroke: blue; stroke-width: 2"/>
<text id="t1" x="50" y="120" onclick="alert(t1.textContent)">Example SVG text 1</text>
</svg>
<button onclick=circle1.style.fill="yellow";>Click to change to yellow</button>
<button onclick=javascript:svgMod();>Click to change to blue</button>
<button onclick=javascript:svgMod2();>Click to change text</button>
</body>
</html>
Here is a demo, which can edit text that already exists (instead of creating new text entries):
https://jsfiddle.net/qkrLy9gu
<!DOCTYPE html>
<html>
<body>
<svg height="100" width="200">
<circle cx="50" cy="50" r="40" fill="red"/>
<text x="50" y="50" onclick="edittext(this)">a circle [click to edit]</text>
</svg>
<script>
function edittext(svgtext){
var input = document.createElement("input");
input.value = svgtext.textContent
input.onkeyup = function(e){
if (["Enter", "Escape"].includes(e.key)) {this.blur(); return};
svgtext.textContent = this.value
}
input.onblur = function(e){
myforeign.remove()
}
var myforeign = document.createElementNS('http://www.w3.org/2000/svg', 'foreignObject')
myforeign.setAttribute("width", "100%");
myforeign.setAttribute("height", "100%");
myforeign.append(input);
svg = svgtext.parentNode
svg.append(myforeign);
input.focus()
}
</script>
</body>
</html>