开发者

Is there any way in JQuery to change part of an image?

开发者 https://www.devze.com 2023-04-01 22:42 出处:网络
if i have an image (jpg, png, gif.doesn\'t really matter ) and i want to have some javascript code change part of an image.

if i have an image (jpg, png, gif .doesn't really matter ) and i want to have some javascript code change part of an image.

for example, lets say i have this picture of a cookie like here.

and i have a color picker that lets a person select a color. I want to change the color of part of the image (in this case, lets say the color of the chocolate chips) to the color t开发者_开发问答hat is picked.

is that possible to do in javascript / jquery ?


Its possible with Javascript and the canvas element by directly manipulating the pixel data. The below example turns blue into red.

Live Demo

var canvas = document.getElementById("canvas"),
    ctx = canvas.getContext("2d"),
    image = document.getElementById("testImage");

canvas.height = canvas.width = 45;
ctx.drawImage(image,0,0);

var imgd = ctx.getImageData(0, 0, 45, 45),
    pix = imgd.data;

for (var i = 0, n = pix.length; i <n; i += 4) {
    if(pix[i + 2] > 20){ // Blue threshold
        // Swap red and blue component values.

        var redVal = pix[i]; // Copy the current red component value
        pix[i] = pix[i + 2]; // Assign the current blue component value to red
        pix[i+2] = redVal; // Assign the old red value to blue.
    }
}

ctx.putImageData(imgd, 0, 0);

Its not very fast to do it this way however, and for larger images you would see a noticeable performance drop depending on the browser. AS for jQuery, there is nothing related to this that jQuery provides that would help.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号