文章目录
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/e3c5a9c948af1c50e104ea675112e2b1.png#pic_center)
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Canvas</title>
<style type="text/css">
* {
/* margin: 0;
padding: 0; */
box-sizing: border-box;
}
canvas {
/* border-width: 1px;
border-color: #000000;
border-style: solid; */
}
input, label {
cursor: pointer;
}
</style>
</head>
<body>
<canvas id="canvas"></canvas>
<div>
<input type="radio" id="original" name="color" checked />
<label for="original">Original</label>
<input type="radio" id="red" name="color" />
<label for="red">Red</label>
<input type="radio" id="green" name="color" />
<label for="green">Green</label>
<input type="radio" id="blue" name="color" />
<label for="blue">Blue</label>
</div>
<script type="text/javascript">
window.onload = (event) => {
console.log(event)
main()
}
function main() {
const canvas = document.getElementById("canvas")
const ctx = canvas.getContext("2d")
const image = new Image()
image.onload = (event) => {
console.log(event, image.width, image.height)
canvas.width = image.width
canvas.height = image.height
ctx.drawImage(image, 0, 0)
const originalImageData = ctx.getImageData(0, 0, image.width, image.height)
document.getElementById("original").onchange = (event) => {
ctx.putImageData(originalImageData, 0, 0)
}
document.getElementById("red").onchange = (event) => {
const imageData = ctx.createImageData(originalImageData)
for (let i = 0; i < originalImageData.data.length; i += 4) {
imageData.data[i] = originalImageData.data[i] // Red
imageData.data[i + 3] = originalImageData.data[i + 3] // Alpha
}
ctx.putImageData(imageData, 0, 0)
}
document.getElementById("green").onchange = (event) => {
const imageData = ctx.createImageData(originalImageData)
for (let i = 0; i < originalImageData.data.length; i += 4) {
imageData.data[i + 1] = originalImageData.data[i + 1] // Green
imageData.data[i + 3] = originalImageData.data[i + 3] // Alpha
}
ctx.putImageData(imageData, 0, 0)
}
document.getElementById("blue").onchange = (event) => {
const imageData = ctx.createImageData(originalImageData)
for (let i = 0; i < originalImageData.data.length; i += 4) {
imageData.data[i + 2] = originalImageData.data[i + 2] // Blue
imageData.data[i + 3] = originalImageData.data[i + 3] // Alpha
}
ctx.putImageData(imageData, 0, 0)
}
}
image.src = "img/0.png"
}
</script>
</body>
</html>
参考
Web technology for developers > Web APIs > Canvas API > Canvas tutorial > Using images