目前我将图像转换为灰度,只需点击一下按钮即可。我需要能够使用相同的按钮或其他按钮删除此功能。我认为这可以通过使用if语句来实现,尽管我不知道如何做到这一点。
<html>
<body>
<script>
function greyscale(){
//get canvas
var canvas = document.getElementById("canvas");
//get the context property
var ctx = canvas.getContext('2d');
//get image
var image = document.getElementById("imgSrc");
//draw image to canvas
ctx.drawImage(image,0,0);
//get the image data
var imageData = ctx.getImageData(0,0,130,130);
//get the pixel data
var px = imageData.data;
//get entire length of pixel data
var length = px.length;
//loop and manipulate the pixels
for(var i=0;i<length;i+=4){
var redPx = px[i];
var greenPx = px[i+1];
var bluePx = px[i+2];
var alphaPx = px[i+3];
//create greyscale sub pixel
var greyscale = redPx*.3 + greenPx * .59 + bluePx * .11;
//store each subpixel as that greyscale subpixel
px[i] = greyscale;
px[i+1] = greyscale;
px[i+2] = greyscale;
}
//put the manipulated image data back into the canvas
ctx.putImageData(imageData,0,0);
}
</script><img src="flower.jpg" id="imgSrc"/>
<canvas id="canvas" width="130" height="130"></canvas>
<br>
</script>
<input id="btngreyscale" type="button" value="Greyscale" onclick="greyscale();" />
<input id="btngreyscaleoff" type="button" value="Greyscale Off" onclick="loadImage();" />
<br>
<input type="radio" name="zing" id="on" checked/>on
<input type="radio" name="zing" id="off"/>off
<script type="text/javascript">
if (document.getElementById('btngreyscale').checked) {
alert('on');
} else {
(document.getElementById('btngreyscaleoff').checked)
alert('off');
}
</script>
</body>
</html>
答案 0 :(得分:1)
正如Roman Hocke所说,你无法使用灰度将其变回彩色图像,因为你扔掉了一些信息。要返回彩色图像,您只需重新绘制第一张图像。
所以在您的代码中,这将是:
(document.getElementById('btngreyscaleoff').checked)
alert('off');
ctx.drawImage(image,0,0);
}
这可以很容易地完成,因为您已经将图像对象保存在DOM中。