javascript - 将停车标志的颜色更改为蓝色?
问题描述
我的老师给了我基本的代码,我已经对其进行了一些修改(老实说可能把它搞砸了)。当您单击按钮时,它应该显示第二张图像,并且第二张图像也应该转换其颜色。我已经尝试了一切,但似乎无法获得第二张图像来显示或更改任何颜色。我将把我们应该放在下面的代码和图像放在下面。我们应该改变的颜色是整个停车标志,红色部分是蓝色。
<!DOCTYPE html>
<html>
<head>
<style>
body {
background-color: #000000;
}
</style>
</head>
<body>
<canvas id="canvas" width="849" height="565"></canvas>
<script>
var img = new Image();
img.src = "stop sign.jpg";
var canvas = document.getElementById('canvas'); // id found in the canvas id tag 'canvas'
var ctx = canvas.getContext('2d');
img.onload = function() {
ctx.drawImage(img, 0, 0); // execute drawImage statement after image is loaded
}
function convert()
{
var imageData = ctx.getImageData(0, 0, canvas.width, canvas.height); // I do not know what to put here in order to gather the data of the image that was originally made?
var data = imageData.data;
for (var i = 0; i < data.length; i +=4)
{
//# check if RED channel has pixel values in range of 200 to 255
if( ( data[i+0] >= 200) && ( data[i+0] <= 255 ) )
{
//if such pixel found in range then change that pixel color to...
data[i + 2] = data[i + 0]; //use red level as blue level
data[i + 1] = 0; //no green
data[i + 0] = 0; //no red
}
}
ctx.putImageData(imageData, 0, 0); // this is supposed to produce a second image right next to the original image, but I cannot seem to get this to function either. This image is also supposed to be manipulated to have the stop sign blue
}
</script>
<p><button onclick="convert()">Change</button></p>
</body>
</html>
解决方案
您可以通过以下方式解决您的问题:
function convert()
{
var imageData = ctx.getImageData(0,0,849,565);
var data = imageData.data;
for (var i = 0; i < data.length; i +=4)
{
//# check if RED channel has pixel values in range of 200 to 255
if( ( data[i+0] >= 200) && ( data[i+0] <= 255 ) )
{
//if such pixel found in range then change that pixel color to...
data[i + 2] = data[i + 0]; //use red level as blue level
data[i + 1] = 0; //no green
data[i + 0] = 0; //no red
}
}
ctx.putImageData(imageData, 500, 0);
}