Reputation: 337
hi this is my picture:
i write the function for changing the color of selected image and draw it on canvas . in this function i get the positionx,positiony,width,height as State for drawing image on canvas. but when first picture drawn on canvas and user want to select another image and draw it on another position the previous image(that drawed on canvas) will be cleared and second picture draw on canvas . my function is :
function takePicture(event) { // get image src
setImgSRC(event.target.src);
}
function DrawPicture() {
setCountClick(CountClick + 1);
var Se_image = new Image();
Se_image.src = ImgSRC;
Se_image.onload = function () {
if (CountClick === 2) {// I want to execute this condition by double clicking
ctxRef.current.drawImage(Se_image, POx1, POY1, widthSize, heightSize);// I have already received these four states
ctxRef.current.globalCompositeOperation = "source-in";//****
ctxRef.current.fillStyle = "#09f";
ctxRef.current.fillRect( POx1, POY1, widthSize, heightSize);
ctxRef.current.globalCompositeOperation = "source-over";
setCountClick(1);
}
}
}
if i change the (source-in) to (source-over) .(On the line I marked with the * comment) . when function run it gives me alwayes a blue rect . and my previous draw remain. and Now I can ask you my question in another way : how can i change the image color on canvas in source-over Mood ? or how can i change the image color on canvas in source-in Mood ?whithout losing data on canvas
it's result of source-in Mood and i want changing color like this :
and this is my source-over Mood result:
Upvotes: 1
Views: 291
Reputation: 384
I don't think that you will get the answer from the way you chose you should use DataImg and i think this is your solution:
// get the canvas object
var canvas = canvasRef.current
var ctx = canvas.getContext('2d'); //get the 2d context
var img = Se_image // get the test image
ctx.drawImage(img, POx1, POY1, widthSize, heightSize);
// get the pixel data
var imageData = ctx.getImageData(POx1, POY1, widthSize, heightSize);
var data = imageData.data;
// we manipulate the pixel data here in order to make the image lighter
console.log(lineColor);
const r = parseInt(lineColor.substr(1,2), 16)
const g = parseInt(lineColor.substr(3,2), 16)
const b = parseInt(lineColor.substr(5,2), 16)
var changeColor = function () {
for (var i = 0; i < data.length; i += 4) { // we are jumping every 4 values of RGBA for every pixel
data[i] = r // the red color channel
data[i + 1] = g // the green color channel
data[i + 2] = b // the blue color channel
}
ctx.putImageData(imageData, POx1, POY1);
};
changeColor();
Upvotes: 1