Position Image over Chart

In this tutorial we are going to describe how to position custom images over a chart.

Here are the steps:

Step1:

Create a basic chart with required options and call chart.render() method to render the chart.

var chart = new CanvasJS.Chart("chartContainer",{
	title :{
		text: "Position Image over chart"
	},
	data: [{
		type: "column",
		dataPoints : [
			{ label: "apple",  y: 10  },
			{ label: "orange", y: 15  },
			{ label: "banana", y: 25  },
			{ label: "mango",  y: 30  },
			{ label: "grape",  y: 28  }
		]
	}]
});
chart.render();

Step2:

Append images to the Div element with class “canvasjs-chart-container”. This is a div created dynamically by CanvasJS inside the chartContainer created in Step 1. It holds all the Chart elements including canvas, tooltip, buttons etc.

$('img').attr('src', url)
        .attr("class", label)
        .css({"display": "none"})
        .appendTo($('#chartContainer>.canvasjs-chart-container'));

Step3:

Get pixel co-ordinates where the images have to be placed using convertValueToPixel method. Once you have co-ordinates, images can be positioned relative to the div.

imageBottom = chart.axisX[0].bounds.y1;
imageCenter = chart.axisX[0].convertValueToPixel(chart.data[0].dataPoints[0].x);

image.css({"position": "absolute", 
           "display": "block",
           "top": imageBottom  - fruit.height(),
           "left": imageCenter - fruit.width()/2
         });  

Finalising

To summarize, you should first render the chart and then calculate pixel co-ordinates where images have to be placed (using convertValuetoPixel method) and then set top & left css properties of images.

Below is the compilation of final code.

Try it Yourself by Editing the Code below.


If you have any questions, please feel free to ask in our forums.Ask Question