Skip to content

Instantly share code, notes, and snippets.

@nbtacksaito
Last active November 30, 2020 04:55
Show Gist options
  • Save nbtacksaito/fb1fe087e5078ccfc5d3bfd1224815e9 to your computer and use it in GitHub Desktop.
Save nbtacksaito/fb1fe087e5078ccfc5d3bfd1224815e9 to your computer and use it in GitHub Desktop.
chartJSで描画後のイベントhook.html
<!DOCTYPE html>
<html lang="ja">
<head>
<title>chartJS試してみたよ</title>
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/chart.js@2.9.4/dist/Chart.min.js"></script>
<script>
const overwriteCanvas = function () {
console.log("overwriteCanvas");
const targetCanvas = document.getElementById("targetCanvas");
const targetCanvasContext = targetCanvas.getContext('2d');
const {width, height} = targetCanvas;
const mainImgData = targetCanvasContext.getImageData(0, 0, width, height);
const mainData = mainImgData.data;
//各ピクセル
for (let i = 0, len = width * height; i < len; i++) {
if (width * 180 < i && i < width * 305) {
const p = i * 4;
// RGB(54, 162, 235)を RGB(255, 99, 132) (赤) に変える。
if (mainData[p] === 54 && mainData[p + 1] === 162 && mainData[p + 2] === 235) {
mainData[p] = 255;
mainData[p + 1] = 99;
mainData[p + 2] = 132;
}
}
}
targetCanvasContext.putImageData(mainImgData, 0, 0);
}
const config = {
type: 'line',
data: {
labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July'],
datasets: [{
label: '緑な値',
backgroundColor: 'rgb(75, 192, 192)',
borderColor: 'rgb(75, 192, 192)',
data: [10, 20, 30, 40, 79, 52, 42,],
fill: false,
}, {
label: '青い値',
fill: false,
backgroundColor: 'rgb(54, 162, 235)',
borderColor: 'rgb(54, 162, 235)',
data: [9,7,88,4,43,53,42],
}]
},
options: {
responsive: false,
title: {
display: true,
text: 'Chart.js Line Chart'
},
tooltips: {
mode: 'index',
intersect: false,
},
hover: {
mode: 'nearest',
intersect: true
},
scales: {
xAxes: [{
display: true,
scaleLabel: {
display: true,
labelString: '月'
}
}],
yAxes: [{
display: true,
scaleLabel: {
display: true,
labelString: '何かの値'
},
ticks: {
beginAtZero: true,
min: 0,
max: 100,
}
}]
}
},
plugins: [{
afterUpdate: function () {
console.log('afterUpdate');
overwriteCanvas();
},
afterRender: function() {
console.log('afterRender');
overwriteCanvas();
}
}]
};
window.addEventListener('load', () => {
const ctx = document.getElementById('targetCanvas').getContext('2d');
window.myLine = new Chart(ctx, config);
};
</script>
</head>
<body>
<canvas id="targetCanvas" width="800px" ></canvas>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment