javascript - Which scenarios might make Chart.js's canvas element resize? -
question, in scenarios might canvas element resize?
i'm trying save canvas image generated chart.js, via sending .tobase64image() output server, problem images being saved in different sizes. did create separate invisible canvas no animation , fixed height , width, took account window.devicepixelratio (that possible make element resize) element still resizing in scenarios escape sight :/
relevant code:
var canvas = $('<canvas/>'); canvas[0].width = 680; canvas[0].height = 480; // mobile devices higher devicepixelratio cause chart.js resize // canvas, temporally modifying window.devicepixelratio avoid it. var originaldevicepixelratio = window.devicepixelratio; window.devicepixelratio = 0; window.myradar = new chart(canvas[0].getcontext("2d")).radar(radarchartdata, { animation: false, showscale: false, scaleshowlabels: false, showtooltips: false, scalelinewidth: 2, pointlabelfontfamily: "open sans", pointlabelfontcolor: "#666", pointlabelfontsize : 14, pointlabelfontstyle : "600", onanimationcomplete: function () { radar = this; $.ajax({ type: "post", url: submiturl, data: {'image': radar.tobase64image()}, datatype: "json", success: function(data){ radar.destroy(); // dont need radar anymore. } }); window.devicepixelratio = originaldevicepixelratio; }, });
i've read code , thing found retinascale() function resizing according window.devicepixelratio.. solved forcing value 0.
what i'm trying achieve here saving canvas image in server standart size. there optimal or recommended way this? come invisible canvas, maybe there better way..
thanks in advance! cheers.
as you've discovered, chartjs resizes canvas feels necessary. might change width, height, both or neither shape of final canvas unpredictable.
one option might set limit resizing is:
responsive: false,
i guess best can draw chartjs canvas canvas desired size.
here's function let draw chartjs canvas new canvas without causing chart cropped in process. warning--untested code may need tweeking!
// create new canvas of specified size function resize(chartcanvas,newwidth,newheight){ var newcanvas=document.createelement('canvas'); var newctx=newcanvas.getcontext('2d'); var cw=newcanvas.width=newwidth; var ch=newcanvas.height=newheight; var iw=chartcanvas.width; var ih=chartcanvas.height; var scale=scalepreserveaspectratio(iw,ih,cw,ch); newctx.drawimage(chartcanvas,0,0,iw,ih,0,0,iw*scale,ih*scale); return(newcanvas); } // calculate scaling factor preserves // original aspect ratio function scalepreserveaspectratio(imgw,imgh,maxw,maxh){ return(math.min((maxw/imgw),(maxh/imgh))); }
Comments
Post a Comment