如何设置改变颜色的按钮?

时间:2020-05-28 15:02:56

标签: javascript

我是js的新手,这里有一个函数changeColor(),我想在单击按钮时更改图像的颜色,但似乎该函数未定义。有人帮忙吗?

这里只是html中的一个简单按钮,我想通过单击按钮来更改img的颜色:

<script src="{% static 'js/color_change.js' %}" type="text/javascript"></script>

<div class="container">
  <div id="colorpicker"></div>
  <img src="../media/colortest2.png" id="mug" width="5000" height="5000"
       onload="getPixels(this)"/>

  <button name="color" value="#33FFBD" type="button" onclick="changeColor();">
    Change
  </button>
</div>

我的js文件,我想获取按钮的值并更改为img的指定颜色:

var canvas = document.createElement("canvas");
var ctx = canvas.getContext("2d");
var originalPixels = null;
var currentPixels = null;

function getPixels(img) {
    canvas.width = img.width;
    canvas.height = img.height;

    ctx.drawImage(img, 0, 0, img.naturalWidth, img.naturalHeight, 0, 0, img.width, img.height);
    originalPixels = ctx.getImageData(0, 0, img.width, img.height);
    currentPixels = ctx.getImageData(0, 0, img.width, img.height);

    img.onload = null;
}
function hexToRGB(hex)
{
var long = parseInt(hex.replace(/^#/, ""), 16);
return {
    R: (long >>> 16) & 0xff,
    G: (long >>> 8) & 0xff,
    B: long & 0xff
 };
}
Object.onclick = function changeColor()
{
    var mug = document.getElementById("mug");
    if(!originalPixels) return; // Check if image has loaded
    var newColor = hexToRGB(document.getElementByName("color").value);

    for(var I = 0, L = originalPixels.data.length; I < L; I += 4)
    {
        if(currentPixels.data[I + 3] > 0) // If it's not a transparent pixel
        {
            currentPixels.data[I] = originalPixels.data[I] / 255 * newColor.R;
            currentPixels.data[I + 1] = originalPixels.data[I + 1] / 255 * newColor.G;
            currentPixels.data[I + 2] = originalPixels.data[I + 2] / 255 * newColor.B;
        }
    }

    ctx.putImageData(currentPixels, 0, 0);
    mug.src = canvas.toDataURL("image/png");
}

2 个答案:

答案 0 :(得分:0)

找不到函数changeColor(),因为未声明。

你有这个:

Object.onclick = function changeColor() {...}

将其更改为可以在全局范围内找到的函数声明:

function changeColor() {...}

答案 1 :(得分:0)

更改

var newColor = hexToRGB(document.getElementByName("color").value);

收件人

var newColor = hexToRGB(document.getElementById("color").value);
相关问题