I placed an image with a line inside a chart like below
To do this I used draw
function of Chart.helpers.extend
like below
let originalLineDraw = Chart.controllers.line.prototype.draw;
const base_image = new Image();
base_image.src="https://cdn0.iconfinder.com/data/icons/classic-icons/512/087.png";
Chart.helpers.extend(Chart.controllers.line.prototype, {
draw: function () {
originalLineDraw.apply(this, arguments);
let chart = this.chart;
let ctx = chart.chart.ctx;
let xaxis = chart.scales['x-axis-0'];
let yaxis = chart.scales['y-axis-0'];
ctx.save();
ctx.beginPath();
ctx.moveTo(xaxis.getPixelForValue(undefined, index), yaxis.top+40);
ctx.strokeStyle = '#000';
ctx.lineTo(xaxis.getPixelForValue(undefined, index), yaxis.bottom);
ctx.lineWidth = 2;
ctx.globalCompositeOperation = 'destination-over';
ctx.drawImage(base_image, xaxis.getPixelForValue(undefined, index) - 15, 50, 30, 30);
ctx.stroke();
ctx.restore();
}
});
Up until this point it was a bit challenging but big challenge is controlling the visibility of inserted all images and drawn black lines via button(like legend filter buttons of chartJs).
I thought that I might use clearRect()
to clear what I drew but problem is having more images and lines due to dynamic data.
How can I solve this?
JSFiddle = https://jsfiddle.net/xazpjqb2/1/
ED?T
I came up with an answer about wrapping chart render function with a global varibal to get control of it.Then Chart.update() does the trick.
Here my solution : https://jsfiddle.net/1nwbv5k9/
question from:
https://stackoverflow.com/questions/65918200/how-to-control-visibility-of-canvas-image-via-button-outside-the-canvaschartjs 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…