DAY 7
2
Modern Web

## Day 07 - 直方圖顯示

### 算法

``````export const calculateBrightness = pixelData => {
const result = []
for (let i = 0; i < pixelData.length; i += 4) {
const red = pixelData[i]
const green = pixelData[i + 1]
const blue = pixelData[i + 2]
const brightness = 0.299 * red + 0.587 * green + 0.114 * blue
result.push(Math.round(brightness))
// 可嘗試替代之前灰階算法
// pixelData[i] = brightness
// pixelData[i + 1] = brightness
// pixelData[i + 2] = brightness
}
return result
}

``````

### 顯示

``````<div ref="echart" style="width: 200px;height:80px;"></div>
``````

`````` editImageData(pixelData) {
const canvas = this.\$refs.drawCanvas
const context = canvas.getContext('2d')
context.putImageData(pixelData, 0, 0)
this.\$root.\$emit('imgChange', pixelData)
}
``````

``````methods: {
calcuateHistogram(pixelData) {
const result = filter.calculateBrightness(pixelData.data)
this.echart.setOption({
xAxis: {
min: 0,
max: 255,
splitLine: {
show: false
},
axisTick: {
show: false
},
axisLabel: {
show: false
}
},
yAxis: {
show: false
},
grid: {
left: 0,
top: 0,
right: 0,
bottom: 10
},
series: [{
type: 'bar',
data: result,
large: true
}]
}, true, true)
}
},
mounted() {
this.echart = echarts.init(this.\$refs.echart, {})
this.\$root.\$on('imgChange', this.calcuateHistogram)
}
``````