<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Using image</title>
<style type="text/css">
* {
box-sizing: border-box;
}
canvas {
}
</style>
</head>
<body>
<canvas id="canvas"></canvas>
<canvas id="mirror"></canvas>
<div>
<input type="file" accept="image/*" />
</div>
<script type="text/javascript">
window.onload = (event) => {
main()
}
function main() {
const canvas = document.getElementById("canvas");
const mirror = document.getElementById("mirror");
const ctx = canvas.getContext("2d");
const mirrorCtx = mirror.getContext("2d");
const inputFile = document.querySelector("input[type=file]");
inputFile.onchange = (event) => {
const files = event.target.files;
if (files.length > 0) {
const file = files[0];
console.log(file);
const image = new Image();
image.src = URL.createObjectURL(file);
image.onload = function(event) {
URL.revokeObjectURL(this.src);
canvas.width = image.width;
canvas.height = image.height;
mirror.width = image.width;
mirror.height = image.height;
ctx.drawImage(image, 0, 0);
const emptyImageData = ctx.createImageData(canvas.width, canvas.height);
const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
console.log(imageData.data[0]);
for(let h = 0; h < imageData.height; h++) {
for(let w = 0; w < imageData.width; w++) {
const pixel = getPixel(imageData, h, imageData.width - w - 1);
setPixel(emptyImageData, h, w, pixel);
}
}
mirrorCtx.putImageData(emptyImageData, 0, 0);
console.log(imageData, emptyImageData);
function getPixel(imageData, row, column) {
const uint8ClampedArray = imageData.data;
const width = imageData.width;
const height = imageData.height;
const pixel = [];
for(let i = 0; i < 4; i++) {
pixel.push(uint8ClampedArray[row * width * 4 + column * 4 + i]);
}
return pixel;
}
function setPixel(imageData, row, column, pixel) {
const uint8ClampedArray = imageData.data;
const width = imageData.width;
const height = imageData.height;
for(let i = 0; i < 4; i++) {
uint8ClampedArray[row * width * 4 + column * 4 + i] = pixel[i];
}
}
}
}
}
}
</script>
</body>
</html>
参考
Web technology for developers > Web APIs > Canvas API > Canvas tutorial > Pixel manipulation with canvas
|