PutImageData - "darkening" the image

I have two canvases. In the first canvas, I draw an image, and in the second canvas, I copy the image from the first canvas and paste it into the second canvas using "getImageData" e "putImageData"

The following code is a small piece of code that I have in my application. I cut off the parts that weren't causing the problem and combined it. [Please note that the image present in javascript must exist "image3.jpg"].

var canvasLocal = document.getElementById('c'),
	context = canvasLocal.getContext('2d'),
	canvasToRender1 = document.getElementById('c2'),
	ctx = canvasLocal.getContext("2d"),
	canvasToRender1Ctx = canvasToRender1.getContext('2d'),
	base_image = new Image();

base_image.src = 'imagem3.jpg';
base_image.onload = function() {
	canvasLocal.width = canvasToRender1.width = base_image.width;
	canvasLocal.height = canvasToRender1.height = base_image.height;
	
	context.drawImage(base_image, 0, 0);
		
	var imgData = ctx.getImageData(0, 0, base_image.width, base_image.height);

	
	canvasToRender1Ctx.putImageData(imgData,0,0);
}
      

<html>
<head>
	<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
	
</head>
<body>
	
<canvas id="c"></canvas>
<canvas id="c2"></canvas>
<script src="javascript.js"></script>
</body>
</html>
      

Run codeHide result


The problem is that the image on the second canvas looks darker than the original:

enter image description here

I've tested multiple browsers, but the only thing I could see in this question is chrome for android, which android version is equal to or greater than 6.0.1. (The chrome version was 57.0.2987.132 for all phones we tested).

UPDATE: I am already reporting the issue on chrome. Check it out at this link: https://bugs.chromium.org/p/chromium/issues/detail?id=713632#

+3


source to share


2 answers


The current solution is to use drawImage instead of putImageData.

Runs the code with the issue fixed:



var canvasLocal = document.getElementById('c'),
context = canvasLocal.getContext('2d'),
canvasToRender1 = document.getElementById('c2'),
ctx = canvasLocal.getContext("2d"),
canvasToRender1Ctx = canvasToRender1.getContext('2d'),
base_image = new Image();

base_image.src = 'imagem3.jpg';
base_image.onload = function() {
     canvasLocal.width = canvasToRender1.width = base_image.width;
     canvasLocal.height = canvasToRender1.height = base_image.height;

     context.drawImage(base_image, 0, 0);

}

      

0


source


The resolution is found for the case when pixel change is required. You can use ImageBitmap

.



return createImageBitmap(imageData).then(function(bitmap){
    var canvas = document.createElement('canvas');
    canvas.width = bitmap.width;
    canvas.height = bitmap.height;
    canvas.getContext('2d').drawImage(bitmap, 0, 0);
});

      

+1


source







All Articles