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>
Related
I'm trying out Babylon.js. I want to set my floor texture but it doesn't work. I get the following error:
"Uncaught TypeError: _this.getScene is not a function" (for google search)
I really don't get this, the youtube tutorial made it seem so easy.
Source code:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
<style>
#canvas {
width: 100%;
height: 100%;
}
</style>
</head>
<body>
<canvas id="canvas"></canvas>
<script src="https://cdn.babylonjs.com/babylon.max.js"></script>
<script>
window.addEventListener('DOMContentLoaded', function () {
var canvas = document.getElementById('canvas');
var engine = new BABYLON.Engine(canvas, true);
var createScene = function () {
var scene = new BABYLON.Scene(engine);
scene.clearColor = new BABYLON.Color3.White();
var floor = BABYLON.MeshBuilder.CreateBox("floor", { height: 25, width: 800, depth: 900 }, scene);
floor.position.y = -162.5;
floor.position.x = 100;
floor.position.z = 400;
var camera = new BABYLON.ArcRotateCamera(
'camera1',
BABYLON.Tools.ToRadians(45),
BABYLON.Tools.ToRadians(45),
1000.0,
new BABYLON.Vector3(0, 50, 400),
scene);
camera.attachControl(canvas, true);
var light = new BABYLON.PointLight("pointlight", new BABYLON.Vector3(800, 700, 1000), scene);
light.diffuse = new BABYLON.Color3(1, 1, 1);
var floormaterial = new BABYLON.StandardMaterial("floormaterial", scene);
floormaterial.diffuseTexture = BABYLON.Texture("floor.png", scene);
floor.material = floormaterial;
return scene;
};
var scene = createScene();
engine.runRenderLoop(function () {
scene.render();
});
});
</script>
</body>
</html>
If I remove the "floormaterial.diffuseTexture = BABYLON.Texture("floor.png", scene);" line everything works perfectly.
you are missing the new before the texture. the line should be:
floormaterial.diffuseTexture = new BABYLON.Texture("floor.png", scene);
I am trying to display a high resolution image in browser using openlayers 5. I found an example on how to use zoomify to create image tiles and render it using openlayers map. But I am unable to use it for my own image. I am completely new to this. The question I ask may be very trivial. Please bear my ignorance.
Example code - This is the example from openlayers website. I am trying to do the same with this image.
I tried replacing the zoomifyUrl and iipUrl with my image url but it didn't work.
import Map from 'ol/Map.js';
import View from 'ol/View.js';
import TileLayer from 'ol/layer/Tile.js';
import Zoomify from 'ol/source/Zoomify.js';
var imgWidth = 799;
var imgHeight = 586;
var zoomifyUrl = 'https://live.staticflickr.com/8173/7993440342_5d9c68faec_c.jpg';
var iipUrl = 'https://live.staticflickr.com/8173/7993440342_5d9c68faec_c.jpg' + '&JTL={z},{tileIndex}';
var layer = new TileLayer({
source: new Zoomify({
url: zoomifyUrl,
size: [imgWidth, imgHeight],
crossOrigin: 'anonymous'
})
});
var extent = [0, -imgHeight, imgWidth, 0];
var map = new Map({
layers: [layer],
target: 'map',
view: new View({
// adjust zoom levels to those provided by the source
resolutions: layer.getSource().getTileGrid().getResolutions(),
// constrain the center: center cannot be set outside this extent
extent: extent
})
});
map.getView().fit(extent);
var control = document.getElementById('zoomifyProtocol');
control.addEventListener('change', function(event) {
var value = event.currentTarget.value;
if (value === 'iip') {
layer.setSource(new Zoomify({
url: iipUrl,
size: [imgWidth, imgHeight],
crossOrigin: 'anonymous'
}));
} else if (value === 'zoomify') {
layer.setSource(new Zoomify({
url: zoomifyUrl,
size: [imgWidth, imgHeight],
crossOrigin: 'anonymous'
}));
}
});
I want to achieve something like the demo in openseadragon website. After making the above code change, I get a a grid with a portion of image repeated.
To use Zoomify you need a server which supports the image served as tiles. The url you are using is a static image on flickr which OpenLayers would need to process as ImageStatic. Here is the code using the highest resolution image from flickr
var extent = [0, 0, 10000, 7328];
var resolutions = [64, 32, 16, 8, 4, 2, 1];
var layer = new ol.layer.Image({
source: new ol.source.ImageStatic({
url: 'https://live.staticflickr.com/8173/7993440342_6a1f281898_o_d.jpg',
imageExtent: extent
})
});
var map = new ol.Map({
layers: [layer],
target: 'map',
view: new ol.View({
// adjust zoom levels to those provided by the source
resolutions: resolutions,
// constrain the center: center cannot be set outside this extent
extent: extent
})
});
map.getView().fit(extent);
html, body, .map {
margin: 0;
padding: 0;
width: 100%;
height: 100%;
}
<link href="https://cdn.rawgit.com/openlayers/openlayers.github.io/master/en/v5.3.0/css/ol.css" rel="stylesheet" />
<script src="https://cdn.rawgit.com/openlayers/openlayers.github.io/master/en/v5.3.0/build/ol.js"></script>
<div id="map" class="map"></div>
Alternatively you could link to the url being used by OpenSeadragon. Sttrangely the zoom levels run from 8 to 14, with one tile at level 8 and a 55 x 41 grid at level 14 where the tiles in the rightmost column are 206px wide and in the bottom row 41px high. Zoomify can be used but a custom tile url function is needed to add 8 to the zoom level expected by OpenLayers.
var imgWidth = 54*256 + 206;
var imgHeight = 40*256 + 41;
var zoomifyUrl = 'https://openseadragon.github.io/example-images/duomo/duomo_files/{z}/{x}_{y}.jpg';
var layer = new ol.layer.Tile({
source: new ol.source.Zoomify({
url: zoomifyUrl,
size: [imgWidth, imgHeight],
crossOrigin: 'anonymous'
})
});
layer.getSource().setTileUrlFunction(function(tileCoord) {
return zoomifyUrl.replace(
'{z}', tileCoord[0]+8
).replace(
'{x}', tileCoord[1]
).replace(
'{y}', -(tileCoord[2]+1)
);
});
var extent = [0, -imgHeight, imgWidth, 0];
var map = new ol.Map({
layers: [layer],
target: 'map',
view: new ol.View({
// adjust zoom levels to those provided by the source
resolutions: layer.getSource().getTileGrid().getResolutions(),
// constrain the center: center cannot be set outside this extent
extent: extent
})
});
map.getView().fit(extent);
html, body, .map {
margin: 0;
padding: 0;
width: 100%;
height: 100%;
}
<link href="https://cdn.rawgit.com/openlayers/openlayers.github.io/master/en/v5.3.0/css/ol.css" rel="stylesheet" />
<script src="https://cdn.rawgit.com/openlayers/openlayers.github.io/master/en/v5.3.0/build/ol.js"></script>
<div id="map" class="map"></div>
Looking at the result from that attempt it is apparent some tiles are only 255px instead of the standard 256 which is causing white lines to appear on the output. I added a custom tile load function to stretch 255px widths or heights to 256 (but it must not stretch tiles at the right and bottom edges which can be less than 255px).
var imgWidth = 54*256 + 206;
var imgHeight = 40*256 + 41;
var zoomifyUrl = 'https://openseadragon.github.io/example-images/duomo/duomo_files/{z}/{x}_{y}.jpg';
var layer = new ol.layer.Tile({
source: new ol.source.Zoomify({
url: zoomifyUrl,
size: [imgWidth, imgHeight],
crossOrigin: 'anonymous'
})
});
layer.getSource().setTileUrlFunction(function(tileCoord) {
return zoomifyUrl.replace(
'{z}', tileCoord[0]+8
).replace(
'{x}', tileCoord[1]
).replace(
'{y}', -(tileCoord[2]+1)
);
});
var tileSize = ol.size.toSize(layer.getSource().getTileGrid().getTileSize(0));
layer.getSource().setTileLoadFunction(function(imageTile, src) {
var img = document.createElement('img');
img.onload = function() {
var width = img.naturalWidth >= tileSize[0]-1 ? tileSize[0] : img.naturalWidth;
var height = img.naturalHeight >= tileSize[1]-1 ? tileSize[1] : img.naturalHeight;
var canvas = document.createElement('canvas');
canvas.width = width;
canvas.height = height;
var ctx = canvas.getContext('2d');
ctx.drawImage(img, 0, 0, width, height);
imageTile.getImage().src = canvas.toDataURL();
};
img.crossOrigin = 'anonymous';
img.src = src;
});
var extent = [0, -imgHeight, imgWidth, 0];
var map = new ol.Map({
layers: [layer],
target: 'map',
view: new ol.View({
// adjust zoom levels to those provided by the source
resolutions: layer.getSource().getTileGrid().getResolutions(),
// constrain the center: center cannot be set outside this extent
extent: extent
})
});
map.getView().fit(extent);
html, body, .map {
margin: 0;
padding: 0;
width: 100%;
height: 100%;
}
<link href="https://cdn.rawgit.com/openlayers/openlayers.github.io/master/en/v5.3.0/css/ol.css" rel="stylesheet" />
<script src="https://cdn.rawgit.com/openlayers/openlayers.github.io/master/en/v5.3.0/build/ol.js"></script>
<div id="map" class="map"></div>
Using a dzi XML parser:
var map = new ol.Map({
target: 'map',
logo: false
});
var layer = dzi.loadUrl(
'https://openseadragon.github.io/example-images/duomo/duomo.dzi',
{ attributions: 'Image © 2012, Dario Morelli' }
);
layer.on('change:source', function(evt) {
map.setView(
new ol.View({
resolutions: layer.getSource().getTileGrid().getResolutions(),
extent: layer.getExtent()
})
);
map.getView().fit(layer.getExtent(), { size: map.getSize() });
});
map.addLayer(layer);
html, body, .map {
margin: 0;
padding: 0;
width: 100%;
height: 100%;
}
<link href="https://cdn.rawgit.com/openlayers/openlayers.github.io/master/en/v5.3.0/css/ol.css" rel="stylesheet" />
<script src="https://cdn.rawgit.com/openlayers/openlayers.github.io/master/en/v5.3.0/build/ol.js"></script>
<script>
dzi = function() {
function loadUrl ( url,
opt_options // attributions (defaults to undefined), crossOrigin (defaults to 'anonymous')
) {
var options = opt_options || {};
var crossOrigin = options.crossOrigin === undefined ? 'anonymous' : options.crossOrigin;
var layer = new ol.layer.Tile();
var last = url.lastIndexOf('.');
var path = url.slice(0, last);
var xhr = new XMLHttpRequest();
xhr.open('GET', url);
xhr.onload = function() {
var parser = new DOMParser();
var xmlDoc = parser.parseFromString(xhr.responseText,'text/xml');
var elements = xmlDoc.getElementsByTagName('Image');
var tileSize = Number(elements[0].getAttribute('TileSize'));
var format = elements[0].getAttribute('Format');
var width = Number(elements[0].getElementsByTagName('Size')[0].getAttribute('Width'));
var height = Number(elements[0].getElementsByTagName('Size')[0].getAttribute('Height'));
var url = path + '_files/{z}/{x}_{y}.' + format;
var source = new ol.source.Zoomify({
attributions: options.attributions,
url: url,
size: [width, height],
tileSize: tileSize,
crossOrigin: crossOrigin
});
var offset = Math.ceil(Math.log(tileSize)/Math.LN2);
source.setTileUrlFunction(function(tileCoord) {
return url.replace(
'{z}', tileCoord[0] + offset
).replace(
'{x}', tileCoord[1]
).replace(
'{y}', -(tileCoord[2]+1)
);
});
layer.setExtent([0, -height, width, 0]);
layer.setSource(source);
}
xhr.send();
return layer;
}
return {
"loadUrl" : loadUrl
}
} ();
</script>
<div id="map" class="map"></div>
The above answer has two issues:
lack of support for deepzoom in zoomify
white lines in between the tiles.
I was able to figure it out. Answer: Deepzoom into OpenLayers images using zoomify
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
I'm trying to follow the example in this videos:
https://www.youtube.com/watch?v=wqPGFs0cqxI
It's about drawing path with D3.js into Google Maps API. The console shows me the error Uncaught TypeError: Object#<PolylineContext>" has no method 'setCurrent'.
The index.html
<head>
<title>App</title>
<style type="text/css">
html { height: 100% }
body { height: 100%; margin: 0; padding: 0 }
#map-canvas { height: 100%; }
</style>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false">
</script>
<script src="http://d3js.org/d3.v3.js" charset="utf-8"></script>
<script src="polyline_context.js"></script>
<script type="text/javascript">
var map;
var polyline;
function initialize() {
var mapOptions = {
center: new google.maps.LatLng(53.567, 9.944),
zoom: 2,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map-canvas"),
mapOptions);
polyline = new google.maps.Polyline({
map: map
});
d3init();
}
var context;
var width;
var height;
var path;
var graticule;
var equator;
var projection;
function d3init() {
width = map.getDiv().offsetWidth;
height = map.getDiv().offsetHeight;
projection = d3.geo.equirectangular()
.translate([0, 0])
.scale(52.29578)
.precision(2)
context = new PolylineContext();
path = d3.geo.path().projection(projection).context(context);
equator = {type: 'LineString', coordinates: [[-180, 20], [-90, 0], [0, -20], [90, 0], [180, 20]]};
render();
}
function render() {
polyline.setOptions({
strokeColor: 'red',
strokeWeight: 2
});
context.setCurrent(polyline.getPath());
path(equator);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="map-canvas">
</div>
</body>
The Polyline_context.js
'use strict';
function PolylineContext () {
this.currentPath = null;
this.currentIndex = 0;
}
PolylineContext.prototype.beginPath = function() {};
PolylineContext.prototype.moveTo = function(x, y) {
if (this.currentPath) {
var latLng = new google.maps.LatLng(y, x);
this.currentPath.setAt(this.currentIndex, latLng);
this.currentIndex++;
}
};
PolylineContext.prototype.lineTo = function(x, y) {
if (this.currentPath) {
var latLng = new google.maps.LatLng(y, x);
this.currentPath.setAt(this.currentIndex, latLng);
this.currentIndex++;
}
};
PolylineContext.prototype.arc = function(x, y, radius, startAngle, endAngle) {};
PolylineContext.prototype.closePath = function() {};
Any ideas of what's wrong in here?
Fairly old question. But just getting started with the same topic. Just in case somebody else stumbles upon this. Just put this inside the polyline_context.js file and see it come to live:
PolylineContext.prototype.setCurrent = function (path) {
this.currentPath = path;
};
What was shown in the video and what needs to be implemented is not necessarily in sync.
To set the path just use this code instead:
context.currentPath = polyline.getPath();
By default, Kineticjsv4.0.5 does not support image border, therefore .showBorder() and .hideBorder() would result in error saying
Uncaught TypeError: Object # has no method 'showBorder'
But when I included the Image Plugin v1.0.1 javascript file, my game did not appear at all while FireBug reported no errors at all.
I have also started an issue on github.
Regards,
Try this code
<!DOCTYPE HTML>
<html>
<head>
<script src="http://www.html5canvastutorials.com/libraries/kinetic-v4.0.5.js"></script>
<script>
window.onload = function() {
var stage = new Kinetic.Stage({
container: "container",
width: 578,
height: 200
});
var layer = new Kinetic.Layer();
var imageObj = new Image();
imageObj.onload = function() {
var yoda = new Kinetic.Image({
x: 140,
y: stage.getHeight() / 2 - 59,
image: imageObj,
width: 106,
height: 118,
stroke:"Red",
strokeWidth:5
});
// add the shape to the layer
layer.add(yoda);
// add the layer to the stage
stage.add(layer);
yoda.on('mouseover', function() {
yoda.setStrokeWidth("Transparent");
yoda.setStroke(0);
layer.draw();
});
};
imageObj.src = "http://www.html5canvastutorials.com/demos/assets/yoda.jpg";
};
</script>
</head>
<body>
<div id="container"></div>
</body>
</html>