-1
目前我有一個圖像轉換爲灰度,它只需點擊一下按鈕即可。我需要能夠通過使用相同的按鈕或另一個按鈕來刪除此功能。我認爲這可能通過使用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>
你最好保留兩張圖像 - 一張是彩色的,另一張是灰度的。一旦將圖像從彩色轉換爲灰度,就無法再重新構建顏色!你自願將顏色信息丟棄!所以你必須保持原始圖像能夠切換回它。 –
那麼我該怎麼去做呢?我不知道,JavaScript非常新 – user3456633