Related
I am able to clip my canvas to a shape if I hardcode the SVG when the canvas initially loads. Now I am trying to do this with a click function. The challenge is that since everything has loaded, when I click on it and load the clipping function, it clears my canvas and leaves just the shape and background. I'm looking for ideas on how to implement this. I only know how to load the opts in a new fabric.canvas function. I suspect I will have to get the current canvas data and then apply the opts parameter to it, but I am not sure the best way to do it. Here is my code:
var canvas = new fabric.Canvas('imageCanvas');
$('#shape').on('click', function(){
var clipPath = new fabric.Path("M161.469,0.007 C161.469,0.007 214.694,96.481 214.694,96.481 C214.694,96.481 322.948,117.266 322.948,117.266 C322.948,117.266 247.591,197.675 247.591,197.675 C247.591,197.675 261.269,306.993 261.269,306.993 C261.269,306.993 161.469,260.209 161.469,260.209 C161.469,260.209 61.667,306.993 61.667,306.993 C61.667,306.993 75.346,197.675 75.346,197.675 C75.346,197.675 -0.010,117.266 -0.010,117.266 C-0.010,117.266 108.242,96.481 108.242,96.481 C108.242,96.481 161.469,0.007 161.469,0.007", ),
opts = {
controlsAboveOverlay: true,
backgroundColor: 'rgb(255,255,255)',
clipTo: function (ctx) {
if (typeof backgroundColor !== 'undefined') {
ctx.fillStyle = backgroundColor;
ctx.fillRect(0, 0, 900, 900);
}
clipPath.render(ctx);
}
}
//obviously this is not going to work
var reloadShape = JSON.stringify(canvas);
canvas.loadFromJSON(reloadShape);
new fabric.Canvas('imageCanvas', opts);
});
You should initialize canvas just once in your application, otherwise you will loose content of it.
Later when you choose your clipping path create and assign your clipTo function.
if not needed any other processing you could also do just
canvas.clipTo = clipPath._render;
without creating the new function.
//do this once on your application:
var opts = {
controlsAboveOverlay: true,
backgroundColor: 'rgb(255,255,255)',
},
canvas = new fabric.Canvas('imageCanvas', opts);
$('#shape').on('click', function(){
var clipPath = new fabric.Path("M161.469,0.007 C161.469,0.007 214.694,96.481 214.694,96.481 C214.694,96.481 322.948,117.266 322.948,117.266 C322.948,117.266 247.591,197.675 247.591,197.675 C247.591,197.675 261.269,306.993 261.269,306.993 C261.269,306.993 161.469,260.209 161.469,260.209 C161.469,260.209 61.667,306.993 61.667,306.993 C61.667,306.993 75.346,197.675 75.346,197.675 C75.346,197.675 -0.010,117.266 -0.010,117.266 C-0.010,117.266 108.242,96.481 108.242,96.481 C108.242,96.481 161.469,0.007 161.469,0.007", );
canvas.clipTo = function (ctx) {
if (typeof backgroundColor !== 'undefined') {
ctx.fillStyle = backgroundColor;
ctx.fillRect(0, 0, 900, 900);
//for clipping _render would be enough.
// but .render() will allow you to position the path where you want with top and left
clipPath.render(ctx);
}
// display new canvas clipped.
canvas.renderAll();
});
I am working on a Web Application for a client and it has lots of graphs to show data about multiple things.
Currently I am working on a graph that will show skills for each Work item, since work items get added and changed all the time I can't have the chart setup like this...
var workName1 = {
labels : graphWork['New Work']['labels'],
datasets : [
{
fillColor : "rgba(151,187,205,0.5)",
highlightFill : "rgba(151,187,205,0.75)",
data: graphWork['New Work']['values']
}
]
}
window.onload = function(){
var ctx = document.getElementById("canvas").getContext("2d");
window.myBar = new Chart(ctx).Bar(workName1, {
// invertXY: true
// responsive : true,
});
}
Doing it this way would be too static and also because I will have a drop down that functions kind of like this,
$( "#typeUser" ).change(function() {
window.myBar.destroy();
chartType = $('#typeUser').val();
if(chartType == "Random Work"){
var ctx = document.getElementById("canvas").getContext("2d");
window.myBar = new Chart(ctx).Bar(randomWork, {
// responsive : true,
invertXY: true
});
}else if(chartType == "New Work"){
var ctx = document.getElementById("canvas").getContext("2d");
window.myBar = new Chart(ctx).Bar(workName1, {
// responsive : true,
invertXY: true
});
}
});
Again that is also very static and wouldn't allow for dynamic changes if new work gets added.
Question:
What can I do to set this up dynamically. I have thought about doing a $.each on graphWork and then some how creating the variable sets that way but then I dunno how I would do the change function or if that is the correct way to go about doing this?
I have setup a JSFiddle that is pulling data and can be used for testing and to see what I am doing. https://jsfiddle.net/L6396hsq/1/
u can with .draw() to new draw the canvaselement if u filled it with new data.
And with .reflow() u bring the start-motion back ;D
Maybe try this:
window.myBar.draw();
window.myBar.reflow();
I am using Highcharts in my application (without any internet connection)
I have multiple charts on a html page, and I want to generate a PDF report that contains all the charts from this page.
How can I do this without sending the data to any server on the internet ?
I will be thankful for any help or any example you can provide.
Thank you in advance :)
Yes this is possible but involves a few different libraries to get working. The first Library is jsPDF which allows the creation of PDF in the browser. The second is canvg which allows for the rendering and parsing of SVG's, the bit that is really cool though is it can render an svg on to canvas element. Lastly is Highcharts export module which will allow us to send the svg to the canvg to turn into a data URL which can then be given to jsPDF to turn into your pdf.
Here is an example http://fiddle.jshell.net/leighking2/dct9tfvn/ you can also see in there source files you will need to include in your project.
So to start highcharts provides an example of using canvg with it's export to save a chart as a png. because you want all the iamges in a pdf this has been slightly altered for our purpose to just return the data url
// create canvas function from highcharts example http://jsfiddle.net/highcharts/PDnmQ/
(function (H) {
H.Chart.prototype.createCanvas = function (divId) {
var svg = this.getSVG(),
width = parseInt(svg.match(/width="([0-9]+)"/)[1]),
height = parseInt(svg.match(/height="([0-9]+)"/)[1]),
canvas = document.createElement('canvas');
canvas.setAttribute('width', width);
canvas.setAttribute('height', height);
if (canvas.getContext && canvas.getContext('2d')) {
canvg(canvas, svg);
return canvas.toDataURL("image/jpeg");
}
else {
alert("Your browser doesn't support this feature, please use a modern browser");
return false;
}
}
}(Highcharts));
Then for the example i have set up export on a button click. This will look for all elements of a certain class (so choose one to add to all of your chart elements) and then call their highcharts.createCanvas function.
$('#export_all').click(function () {
var doc = new jsPDF();
// chart height defined here so each chart can be palced
// in a different position
var chartHeight = 80;
// All units are in the set measurement for the document
// This can be changed to "pt" (points), "mm" (Default), "cm", "in"
doc.setFontSize(40);
doc.text(35, 25, "My Exported Charts");
//loop through each chart
$('.myChart').each(function (index) {
var imageData = $(this).highcharts().createCanvas();
// add image to doc, if you have lots of charts,
// you will need to check if you have gone bigger
// than a page and do doc.addPage() before adding
// another image.
/**
* addImage(imagedata, type, x, y, width, height)
*/
doc.addImage(imageData, 'JPEG', 45, (index * chartHeight) + 40, 120, chartHeight);
});
//save with name
doc.save('demo.pdf');
});
important to note here that if you have lots of charts you will need to handle placing them on a new page. The documentation for jsPDF looks really outdated (they do have a good demos page though just not a lot to explain all the options possible), there is an addPage() function and then you can just play with widths and heights until you find something that works.
the last part is to just setup the graphs with an extra option to not display the export button on each graph that would normally display.
//charts
$('#chart1').highcharts({
navigation: {
buttonOptions: {
enabled: false
}
},
//this is just normal highcharts setup form here for two graphs see fiddle for full details
The result isn't too bad i'm impressed with the quality of the graphs as I wasn't expecting much from this, with some playing of the pdf positions and sizes could look really good.
Here is a screen shot showing the network requests made before and after the export, when the export is made no requests are made http://i.imgur.com/ppML6Gk.jpg
here is an example of what the pdf looks like http://i.imgur.com/6fQxLZf.png (looks better when view as actual pdf)
quick example to be tried on local https://github.com/leighquince/HighChartLocalExport
You need to setup your own exporting server, locally like in the article
Here is an example using the library pdfmake:
html:
<div id="chart_exchange" style="width: 450px; height: 400px; margin: 0 auto"></div>
<button id="export">export</button>
<canvas id="chart_exchange_canvas" width="450" height="400" style="display: none;"></canvas>
javascript:
function drawInlineSVG(svgElement, canvas_id, callback) {
var can = document.getElementById(canvas_id);
var ctx = can.getContext('2d');
var img = new Image();
img.setAttribute('src', 'data:image/svg+xml;base64,' + btoa(unescape(encodeURIComponent(svgElement))));
img.onload = function() {
ctx.drawImage(img, 0, 0);
callback(can.toDataURL("image/png"));
}
}
full working code:
https://jsfiddle.net/dimitrisscript/f6sbdsps/
Maybe this link can help you out.
http://bit.ly/1IYJIyF
Try refer to the exporting properties (fallbackToExportServer: false) and the necessary file that need to be include (offline-exporting.js).
Whereas for the export all at once part, currently I myself also still trying. Will update here if any.
This question is a bit old but was something i was working on myself recently and had some trouble with it.
I used the jsPDF library: https://github.com/MrRio/jsPDF
Issues i ran into involved jsPDF not supporting the SVG image exported by the high chart + images being blurry and low quality.
Below is the solution I used to get two charts into one pdf document:
function createPDF() {
var doc = new jsPDF('p', 'pt', 'a4'); //Create pdf
if ($('#chart1').length > 0) {
var chartSVG = $('#chart1').highcharts().getSVG();
var chartImg = new Image();
chartImg.onload = function () {
var w = 762;
var h = 600;
var chartCanvas = document.createElement('canvas');
chartCanvas.width = w * 2;
chartCanvas.height = h * 2;
chartCanvas.style.width = w + 'px';
chartCanvas.style.height = h + 'px';
var context = chartCanvas.getContext('2d');
chartCanvas.webkitImageSmoothingEnabled = true;
chartCanvas.mozImageSmoothingEnabled = true;
chartCanvas.imageSmoothingEnabled = true;
chartCanvas.imageSmoothingQuality = "high";
context.scale(2, 2);
chartCanvas.getContext('2d').drawImage(chartImg, 0, 0, 762, 600);
var chartImgData = chartCanvas.toDataURL("image/png");
doc.addImage(chartImgData, 'png', 40, 260, 250, 275);
if ($('#chart2').length > 0) {
var chart2SVG = $('#chart2').highcharts().getSVG(),
chart2Img = new Image();
chart2Img.onload = function () {
var chart2Canvas = document.createElement('canvas');
chart2Canvas.width = w * 2;
chart2Canvas.height = h * 2;
chart2Canvas.style.width = w + 'px';
chart2Canvas.style.height = h + 'px';
var context = chart2Canvas.getContext('2d');
chart2Canvas.webkitImageSmoothingEnabled = true;
chart2Canvas.mozImageSmoothingEnabled = true;
chart2Canvas.imageSmoothingEnabled = true;
chart2Canvas.imageSmoothingQuality = "high";
context.scale(2, 2);
chart2Canvas.getContext('2d').drawImage(chart2Img, 0, 0, 762, 600);
var chart2ImgData = chart2Canvas.toDataURL("image/png");
doc.addImage(chart2ImgData, 'PNG', 300, 260, 250, 275);
doc.save('ChartReport.pdf');
}
chart2Img.src = "data:image/svg+xml;base64," + window.btoa(unescape(encodeURIComponent(chart2SVG)));
}
}
chartImg.src = "data:image/svg+xml;base64," + window.btoa(unescape(encodeURIComponent(chartSVG)));
}
}
scripts to include:
<script src="http://code.highcharts.com/highcharts.js"></script>
<script src="http://code.highcharts.com/modules/exporting.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.2.61/jspdf.min.js"></script>
I'm using Chartjs to display a Line Chart and this works fine:
// get line chart canvas
var targetCanvas = document.getElementById('chartCanvas').getContext('2d');
// draw line chart
var chart = new Chart(targetCanvas).Line(chartData);
But the problem occurs when I try to change the data for the Chart. I update the graph by creating a new instance of a Chart with the new data points, and thus reinitializing the canvas.
This works fine. However, when I hover over the new chart, if I happen to go over specific locations corresponding to points displayed on the old chart, the hover/label is still triggered and suddenly the old chart is visible. It remains visible while my mouse is at this location and disappears when move off that point. I don't want the old chart to display. I want to remove it completely.
I've tried to clear both the canvas and the existing chart before loading the new one. Like:
targetCanvas.clearRect(0,0, targetCanvas.canvas.width, targetCanvas.canvas.height);
and
chart.clear();
But none of these have worked so far. Any ideas about how I can stop this from happening?
I had huge problems with this
First I tried .clear() then I tried .destroy() and I tried setting my chart reference to null
What finally fixed the issue for me: deleting the <canvas> element and then reappending a new <canvas> to the parent container
My specific code (obviously there's a million ways to do this):
var resetCanvas = function(){
$('#results-graph').remove(); // this is my <canvas> element
$('#graph-container').append('<canvas id="results-graph"><canvas>');
canvas = document.querySelector('#results-graph');
ctx = canvas.getContext('2d');
ctx.canvas.width = $('#graph').width(); // resize to parent width
ctx.canvas.height = $('#graph').height(); // resize to parent height
var x = canvas.width/2;
var y = canvas.height/2;
ctx.font = '10pt Verdana';
ctx.textAlign = 'center';
ctx.fillText('This text is centered on the canvas', x, y);
};
I have faced the same problem few hours ago.
The ".clear()" method actually clears the canvas, but (evidently) it leaves the object alive and reactive.
Reading carefully the official documentation, in the "Advanced usage" section, I have noticed the method ".destroy()", described as follows:
"Use this to destroy any chart instances that are created. This will
clean up any references stored to the chart object within Chart.js,
along with any associated event listeners attached by Chart.js."
It actually does what it claims and it has worked fine for me, I suggest you to give it a try.
var myPieChart=null;
function drawChart(objChart,data){
if(myPieChart!=null){
myPieChart.destroy();
}
// Get the context of the canvas element we want to select
var ctx = objChart.getContext("2d");
myPieChart = new Chart(ctx).Pie(data, {animateScale: true});
}
This is the only thing that worked for me:
document.getElementById("chartContainer").innerHTML = ' ';
document.getElementById("chartContainer").innerHTML = '<canvas id="myCanvas"></canvas>';
var ctx = document.getElementById("myCanvas").getContext("2d");
We can update the chart data in Chart.js V2.0 as follows:
var myChart = new Chart(ctx, data);
myChart.config.data = new_data;
myChart.update();
I had the same problem here... I tried to use destroy() and clear() method, but without success.
I resolved it the next way:
HTML:
<div id="pieChartContent">
<canvas id="pieChart" width="300" height="300"></canvas>
</div>
Javascript:
var pieChartContent = document.getElementById('pieChartContent');
pieChartContent.innerHTML = ' ';
$('#pieChartContent').append('<canvas id="pieChart" width="300" height="300"><canvas>');
ctx = $("#pieChart").get(0).getContext("2d");
var myPieChart = new Chart(ctx).Pie(data, options);
It works perfect to me... I hope that It helps.
This worked very well for me
var ctx = $("#mycanvas");
var LineGraph = new Chart(ctx, {
type: 'line',
data: chartdata});
LineGraph.destroy();
Use .destroy this to destroy any chart instances that are created. This will clean up any references stored to the chart object within Chart.js, along with any associated event listeners attached by Chart.js. This must be called before the canvas is reused for a new chart.
It's best to use Chart.js specific functionalities to initially check for the existing chart instance and then perform destroy or clear in order to reuse the same canvas element for rendering another chart, instead of handlding HTML elements from within JS.
ChartJs's getChart(key) - finds the chart instance from the given key.
If the key is a string, it is interpreted as the ID of the Canvas element for the Chart.
The key can also be a CanvasRenderingContext2D or an HTMLDOMElement.
Note: This will return undefined if no Chart is found. If the instance of the chart is found, it signifies that the chart must have previously been created.
// JS - Destroy exiting Chart Instance to reuse <canvas> element
let chartStatus = Chart.getChart("myChart"); // <canvas> id
if (chartStatus != undefined) {
chartStatus.destroy();
//(or)
// chartStatus.clear();
}
//-- End of chart destroy
var chartCanvas = $('#myChart'); //<canvas> id
chartInstance = new Chart(chartCanvas, {
type: 'line',
data: data
});
<!-- HTML -Line Graph - Chart.js -->
<div class="container-fluid" id="chartContainer">
<canvas id="myChart" width="400" height="150"> </canvas>
</div>
This approach would save you from remove - create - append a Canvas element into DIV from inside JS.
Simple edit for 2020:
This worked for me. Change the chart to global by making it window owned (Change the declaration from var myChart to window myChart)
Check whether the chart variable is already initialized as Chart, if so, destroy it and create a new one, even you can create another one on the same name. Below is the code:
if(window.myChart instanceof Chart)
{
window.myChart.destroy();
}
var ctx = document.getElementById('myChart').getContext("2d");
Hope it works!
Complementing Adam's Answer
With Vanilla JS:
document.getElementById("results-graph").remove(); //canvas
div = document.querySelector("#graph-container"); //canvas parent element
div.insertAdjacentHTML("afterbegin", "<canvas id='results-graph'></canvas>"); //adding the canvas again
Using CanvasJS, this works for me clearing chart and everything else, might work for you as well, granting you set your canvas/chart up fully before each processing elsewhere:
var myDiv= document.getElementById("my_chart_container{0}";
myDiv.innerHTML = "";
I couldn't get .destroy() to work either so this is what I'm doing. The chart_parent div is where I want the canvas to show up. I need the canvas to resize each time, so this answer is an extension of the above one.
HTML:
<div class="main_section" >
<div id="chart_parent"></div>
<div id="legend"></div>
</div>
JQuery:
$('#chart').remove(); // this is my <canvas> element
$('#chart_parent').append('<label for = "chart">Total<br /><canvas class="chart" id="chart" width='+$('#chart_parent').width()+'><canvas></label>');
When you create one new chart.js canvas, this generate one new iframe hidden, you need delete the canvas and the olds iframes.
$('#canvasChart').remove();
$('iframe.chartjs-hidden-iframe').remove();
$('#graph-container').append('<canvas id="canvasChart"><canvas>');
var ctx = document.getElementById("canvasChart");
var myChart = new Chart(ctx, { blablabla });
reference:
https://github.com/zebus3d/javascript/blob/master/chartJS_filtering_with_checkboxs.html
This worked for me.
Add a call to clearChart, at the top oF your updateChart()
`function clearChart() {
event.preventDefault();
var parent = document.getElementById('parent-canvas');
var child = document.getElementById('myChart');
parent.removeChild(child);
parent.innerHTML ='<canvas id="myChart" width="350" height="99" ></canvas>';
return;
}`
Since destroy kind of destroys "everything", a cheap and simple solution when all you really want is to just "reset the data". Resetting your datasets to an empty array will work perfectly fine as well. So, if you have a dataset with labels, and an axis on each side:
window.myLine2.data.labels = [];
window.myLine2.data.datasets[0].data = [];
window.myLine2.data.datasets[1].data = [];
After this, you can simply call:
window.myLine2.data.labels.push(x);
window.myLine2.data.datasets[0].data.push(y);
or, depending whether you're using a 2d dataset:
window.myLine2.data.datasets[0].data.push({ x: x, y: y});
It'll be a lot more lightweight than completely destroying your whole chart/dataset, and rebuilding everything.
If you are using chart.js in an Angular project with Typescript, the you can try the following;
Import the library:
import { Chart } from 'chart.js';
In your Component Class declare the variable and define a method:
chart: Chart;
drawGraph(): void {
if (this.chart) {
this.chart.destroy();
}
this.chart = new Chart('myChart', {
.........
});
}
In HTML Template:
<canvas id="myChart"></canvas>
What we did is, before initialization of new chart, remove/destroy the previews Chart instance, if exist already, then create a new chart, for example
if(myGraf != undefined)
myGraf.destroy();
myGraf= new Chart(document.getElementById("CanvasID"),
{
...
}
Hope this helps.
First put chart in some variable then history it next time before init
#Check if myChart object exist then distort it
if($scope.myChart) {
$scope.myChart.destroy();
}
$scope.myChart = new Chart(targetCanvas
You should save the chart as a variable.
On global scope, if its pure javascript, or as a class property, if its Angular.
Then you'll be able to use this reference to call destroy().
Pure Javascript:
var chart;
function startChart() {
// Code for chart initialization
chart = new Chart(...); // Replace ... with your chart parameters
}
function destroyChart() {
chart.destroy();
}
Angular:
export class MyComponent {
chart;
constructor() {
// Your constructor code goes here
}
ngOnInit() {
// Probably you'll start your chart here
// Code for chart initialization
this.chart = new Chart(...); // Replace ... with your chart parameters
}
destroyChart() {
this.chart.destroy();
}
}
For me this worked:
var in_canvas = document.getElementById('chart_holder');
//remove canvas if present
while (in_canvas.hasChildNodes()) {
in_canvas.removeChild(in_canvas.lastChild);
}
//insert canvas
var newDiv = document.createElement('canvas');
in_canvas.appendChild(newDiv);
newDiv.id = "myChart";
Chart.js has a bug:
Chart.controller(instance) registers any new chart in a global property Chart.instances[] and deletes it from this property on .destroy().
But at chart creation Chart.js also writes ._meta property to dataset variable:
var meta = dataset._meta[me.id];
if (!meta) {
meta = dataset._meta[me.id] = {
type: null,
data: [],
dataset: null,
controller: null,
hidden: null, // See isDatasetVisible() comment
xAxisID: null,
yAxisID: null
};
and it doesn't delete this property on destroy().
If you use your old dataset object without removing ._meta property, Chart.js will add new dataset to ._meta without deletion previous data. Thus, at each chart's re-initialization your dataset object accumulates all previous data.
In order to avoid this, destroy dataset object after calling Chart.destroy().
for those who like me use a function to create several graphics and want to update them a block too, only the function .destroy() worked for me, I would have liked to make an .update(), which seems cleaner but ... here is a code snippet that may help.
var SNS_Chart = {};
// IF LABELS IS EMPTY (after update my datas)
if( labels.length != 0 ){
if( Object.entries(SNS_Chart).length != 0 ){
array_items_datas.forEach(function(for_item, k_arr){
SNS_Chart[''+for_item+''].destroy();
});
}
// LOOP OVER ARRAY_ITEMS
array_items_datas.forEach(function(for_item, k_arr){
// chart
OPTIONS.title.text = array_str[k_arr];
var elem = document.getElementById(for_item);
SNS_Chart[''+for_item+''] = new Chart(elem, {
type: 'doughnut',
data: {
labels: labels[''+for_item+''],
datasets: [{
// label: '',
backgroundColor: [
'#5b9aa0',
'#c6bcb6',
'#eeac99',
'#a79e84',
'#dbceb0',
'#8ca3a3',
'#82b74b',
'#454140',
'#c1502e',
'#bd5734'
],
borderColor: '#757575',
borderWidth : 2,
// hoverBackgroundColor : '#616161',
data: datas[''+for_item+''],
}]
},
options: OPTIONS
});
// chart
});
// END LOOP ARRAY_ITEMS
}
// END IF LABELS IS EMPTY ...
just declare let doughnut = null before creating your chart
const doughnutDriverStatsChartCanvas = $('#dougnautChartDriverStats').get(0).getContext('2d')
const doughnutOptionsDriverStats = {
maintainAspectRatio: false,
responsive: true,
}
let doughnut = null
doughnut = new Chart(doughnutDriverStatsChartCanvas, {
type: 'doughnut',
data: doughnutChartDriverStats,
options: doughnutOptionsDriverStats
})
I'm developing an application that uses Google Maps API v3. I want to make custom overlays that are squares exactly 1000km on each side (each overlay is actually a 1000x1000 transparent png, with each pixel representing 1 square km). My current implementation is this:
function PngOverlay(map,loc) {
this._png = null;
this._location = loc; //lat,lng of the square's center
this.setMap(map);
}
PngOverlay.prototype = new google.maps.OverlayView();
PngOverlay.prototype.onAdd = function() {
this._png = new Element('image',{ //using mootools
'src': pngForLoc(this._location),
'styles': {
'width': 1000,
'height': 1000,
'position': 'absolute'
}
});
var panes = this.getPanes();
panes.overlayLayer.appendChild(this._png);
}
PngOverlay.prototype.onRemove = function() {
this._png.parentNode.removeChild(this._png);
this._png = null;
}
PngOverlay.prototype.draw = function() {
var dp = this.getProjection().fromLatLngToDivPixel(this._location);
var ps = this._png.getSize();
var t = dp.y - (ps.y / 2);
this._png.setStyle('top',t);
var l = dp.x - (ps.x / 2);
this._png.setStyle('left',l);
}
My question is this: what, if anything, do I need to do to account for Google Maps' projection? My limited understanding of Mercator is that it preserves horizontal distance but not vertical. How can I appropriately transform() my png to account for that?
There isn't really enough information, but you might find the open source proj4js library useful as this can perform various projection transformations, eg. To Google's Spherical Mercator projection system.