Pie chart to image

Pie chart to image

by Dwarakesh pallagolla

HTML

<script id="sap-ui-bootstrap"
    src="https://sapui5.hana.ondemand.com/resources/sap-ui-core.js"
    data-sap-ui-theme="sap_bluecrystal"
    data-sap-ui-xx-bindingSyntax="complex"
    data-sap-ui-libs="sap.m, sap.ui.commons"></script>

<script id="view1" type="ui5/xmlview">
    <mvc:View 
      controllerName="view1.initial"
      xmlns="sap.m"
      xmlns:viz="sap.viz.ui5.controls"
      xmlns:core="sap.ui.core"
      xmlns:mvc="sap.ui.core.mvc" >
      <Panel height="450px">
			<viz:VizFrame xmlns="sap.viz" id="idVizFrame" vizType="pie"/>			
		 </Panel>
              <Button text="Download image" press="onDownloadImage" />
                  
    </mvc:View>
</script>

<div id="uiArea"></div>

JavaScript

sap.ui.controller("view1.initial", {
    onInit: function(oEvent) {
        this.bindChart();
    },
    bindChart: function() {
    var oVizFrame = this.getView().byId("idVizFrame");
		
		var oModel = new sap.ui.model.json.JSONModel();
		var data = {
			'Sales' : [{
				  "DrugName": "Cranberry Cream",
				  "Revenue": "7.37"
				}, {
				  "DrugName": "Wart Remover Liquid",
				  "Revenue": "9.54"
				}, {
				  "DrugName": "Hydrochlorothiazide",
				  "Revenue": "6.57"
				}, {
				  "DrugName": "Terazosin Hydrochloride",
				  "Revenue": "5.41"
				}, {
				  "DrugName": "Topiramate",
				  "Revenue": "8.69"
				}]};
		oModel.setData(data);
   
		var oDataset = new sap.viz.ui5.data.FlattenedDataset({
			dimensions : [{
			        name : 'Drug Name',
				value : "{DrugName}"}],
			               
			measures : [{
				name : 'Revenue',
				value : '{Revenue}'} ],
			             
			data : {
				path : "/Sales"
			}
		});		
		oVizFrame.setDataset(oDataset);
		oVizFrame.setModel(oModel);	
		
		oVizFrame.setVizProperties({
			title:{
				text : "Revenue"
			},
            plotArea: {
            	colorPalette : d3.scale.category20().range(),
            	drawingEffect: "glossy"
                }});
		
		var feedSize = new sap.viz.ui5.controls.common.feeds.FeedItem({
		      'uid': "size",
		      'type': "Measure",
		      'values': ["Revenue"]
		    }), 
		    feedColor = new sap.viz.ui5.controls.common.feeds.FeedItem({
		      'uid': "color",
		      'type': "Dimension",
		      'values': ["Drug Name"]
		    });
		oVizFrame.addFeed(feedSize);
		oVizFrame.addFeed(feedColor);
    },
    onDownloadImage: function() {
			debugger;
      var vizFrame = this.getView().byId("idVizFrame");
      var svg = vizFrame.getDomRef().getElementsByTagName("svg")[0];
      var canvas = document.createElement("canvas");
      canvas.setAttribute("width", svg.clientWidth);
      canvas.setAttribute("height", svg.clientHeight);
      var context = canvas.getContext("2d");
      var...