通过Javascript更改图像颜色 [英] Changing Image colour through Javascript

查看:91
本文介绍了通过Javascript更改图像颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在试图使用单击事件时更改图像的颜色.

I have been looking to change the colour of an image when a click event is used.

我碰到了这篇文章,马克杯的第一个也是主要的回应确实很好.

I Came across this post, which the first and main response with the Mug works really well.

但是,我需要使用类而不是ID,因为我需要更改多个图像的颜色.当我将代码更改为getElementsByClassName而不是byID时,它将不再起作用.

However, I need to use class, rather than ID, as I need to change the colour of more than one image. When I change the code to getElementsByClassName, instead of byID, it no longer works.

我当然将ID = mug更改为class = mug.

I of course change the ID=mug to class=mug.

我在代码中的其他任何地方都看不到会引起问题的信息,因此我们将不胜感激.

I can't see anywhere else in the code that would cause a problem, so any help would be appreciated.

我无法在原始照片上发布,因此请在此处添加.原始链接是:如何使用jquery更改图像的颜色

I can't post on the original so adding here. Original link is: How to change color of an image using jquery

这是代码:

<img src="mug.png" id="mug" width="25%" height="25%" onload="getPixels(this)" />
<input type="text" id="color" value="#6491ee" />
<input type="button" value="change color" onclick="changeColor()">

<script type="text/javascript">
    var mug = document.getElementById("mug");
    var canvas = document.createElement("canvas");
    var ctx = canvas.getContext("2d");
    var originalPixels = null;
    var currentPixels = null;

    function HexToRGB(Hex)
    {
        var Long = parseInt(Hex.replace(/^#/, ""), 16);
        return {
            R: (Long >>> 16) & 0xff,
            G: (Long >>> 8) & 0xff,
            B: Long & 0xff
        };
    }

    function changeColor()
    {
        if(!originalPixels) return; // Check if image has loaded
        var newColor = HexToRGB(document.getElementById("color").value);

        for(var I = 0, L = originalPixels.data.length; I < L; I += 4)
        {
            if(currentPixels.data[I + 3] > 0)
            {
                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");
    }

    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;
    }
</script>

谢谢

推荐答案

好,花了一些时间,但通过给出的建议和额外的搜索,找到了满足我需求的解决方案.

OK, has taken some time but through a combination of the suggestions given and extra searching have found a solution for my needs.

到目前为止,每个建议都使我受益,但是我需要的特定功能存在一些问题,因此请发布此建议,以防其他人受到帮助.

Each of the suggestions got me so far but there were some issues for the specific functionality I needed, so am posting this in case it helps others.

我正在使用<svg>元素:

I am using the < svg > element:

我需要一个主图像,并且它们上面有一些较小的图像,如果单击该图像或单击主图像外部的按钮,它们会更改颜色.

I required a main image, and them some smaller images on top that would change colour if the image was clicked on, or if a button outside the main image is clicked.

<div style="position: absolute; top: 0px; left: 0px;"><svg version="1.1" xmlns="http://www.w3.org/2000/svg" width="0px" height="0px"><defs><filter id="desaturate"> <feColorMatrix 
  type="matrix"
  values="0.5 0 0 0 0
          0.2 0 0 0 0
          0.9 0 0 0 0
          0 0 0 1 0" /></filter></defs></svg></div>

这些值设置颜色变化.这是反复试验的atm,因为我还没有找到关于颜色的好指南,但是周围有足够的余地.

The values set the colour change. It is trial and error atm as I haven't found a good guide to the colours yet but there are enough around to get by.

由于使用<svg>元素.因此,我将其放入了绝对定位的潜水中,并将元素的大小设置为"0""0",因此它不占用空间并且不会影响页面上的其他任何内容.

I had a problem with random spaces and positioning caused by using the < svg > element. So I have put it inside a dive that is absolutely positioned and set the size of the element to '0' '0' so it takes up no space and doesn't affect anything else on the page.

ID指定此特定颜色.然后,您可以根据需要将这种颜色更改应用于尽可能多的图像:

The ID specifies this particular colour. You can then apply this colour change to as many images as you like as follows:

<div style="position: relative; top: 000px; left: 000px; z-index: 1; display: inline;">
<svg class="svgClass" version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="450px" height="900px">
<image xlink:href="main_image.png" width="450" height="900" />
<image xlink:href="small_image1.png" class="ChangeImageColour ChangeImageColourClick" width="79" height="198" x="110px" y="100px" />
<image xlink:href="small_image2.png" class="ChangeImageColour ChangeImageColourClick" width="79" height="198" x="150px" y="130px" /></svg></div>

同样,为了避免SVG的位置和间距问题,我设置了<svg>元素,使图像的大小与主图像的大小相同,并将它们全部放在<div>,然后可以将其放置在页面上的正确位置.如果您希望图像以这种方式重叠,则需要使所有图像都在同一<svg>元素,否则在某些浏览器中可能会出现显示位置和间距问题.

Again, to avoid position and spacing issues with SVG, I have set the size of the < svg > element for the images to the same size of the main image, and placed them all within a < div > that can then be positioned in the right place on the page. If you want images overlapping in this way, you will need to have all the images within the same < svg > element or you may get display position and spacing issues in some browsers.

您可以使用'x'和'y'将每个图像分别放置在主图像的顶部.您还必须指定图像的高度和宽度.

You can the position each image individually over the top of the main image using 'x' and 'y'. You must also specify the height and width of the image.

一旦您拥有<svg>指定颜色,而<svg>图像的元素,您现在只需要使用class和ID属性以及以下代码将该颜色应用到您想要的图像上即可:

Once you have your < svg > to specify the colour, and your < svg > element for the images, you now just need to apply that colour to the images you want using class and ID attributes and the following code:

<script>
  var $shape = $( '.ChangeImageColour' );
$( '.ChangeImageColourClick' ).click(function() {
          if ( $shape.attr( 'filter' ) )
     $shape.removeAttr( 'filter' );
  else
     $shape.attr( 'filter', 'url(#desaturate)' );
});
</script>

我希望颜色发生在图像或按钮上的单击事件以太之后.只需创建一个具有匹配点击"次数的按钮,在本例中为"ChangeImageColourClick".因此,您可以创建任何要单击的内容,并将更改颜色.单击可添加要更改的设置颜色的ID(#desaturate).如果任何匹配的元素已经具有ID,则将其删除.

I want the colour change to happen after a click event ether on an image or a button. Just create a button with the matching 'click' calss, in this case 'ChangeImageColourClick'. So you can create anything to be clicked on and will change the colour. This click adds the ID of the set colour to change (#desaturate). If any matching element already has the ID, it is removed.

这会产生切换颜色变化的效果.它将更改同一类别的任何匹配图像的颜色.

This creates the effect of toggling the colour change. It will change the colour of any matching image of the same class.

如果不需要,您当然不能使用click事件,也可以先将颜色更改为"on",然后单击以将其删除.

You can of course not use a click event if not required, or start with the colour change 'on' and click to remove etc.

注意:您可以有多个<svg>包含图像的元素,并应用相同的颜色更改.只要确保您设置了<svg>元素尺寸精确到您想要的尺寸,即使它为0.如果将其保留为空白,则会遇到一些间距问题.

Note: You can have multiple < svg > elements with images in and apply the same colour change. Just make sure you set the < svg > element dimensions to the exact ones you want, even if it is 0. If you leave it blank then you'll get some spacing issues.

我需要将这些图像放在相同的<svg>,因为它们是在页面上占据相同空间的png图像.如果图像不重叠,则应使用单独的<svg>元素或每个图像或图像集,并设置<svg>元素到该图像的大小,在某些浏览器中,奇数间距和位置应该不会有任何问题.

I need to have the images in the same < svg > as they are png images that are occupying the same space on the page. If your images are not overlapping you should use separate < svg > elements or each image or image set, and set the dimensions of the < svg > element to the size of that image and you shouldn't have any issues with odd spacing and positioning in some browsers.

我认为这足以说明一切.

I think that about explains it all.

它可以很好地满足我的需要,并且代码相当简洁,尤其是您只需设置一次颜色并应用于多张图像时就可以了.

It works pretty well for what I need, and is a fairly concise bit of coding, especially as you only have to set the colour once and apply to multiple images.

请小心我所写的一些笔记,以确保它可以根据需要显示.

Just be careful of some of the notes I've put to make sure it displays as you need.

感谢所有帮助,如果有任何要添加的内容,将进行更新.

Thanks for all the help, will update if there is anything relevant to add.

如果您有任何问题,请在此处发布.我不是专家,但现在已经对此进行了相当多的研究,并且可能已经尝试并测试了大多数陷阱

If you are having any problems then post on here. I'm not an expert but have looked at this a fair bit now and have probably tried and tested most pitfalls

这篇关于通过Javascript更改图像颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆