Good day to all! I am writing Javascript code. The task is the following: you need to draw the image on the canvas, while first applying filters to it. Problem: FPS sags badly. The idea was this: run over all the pixels with a for loop. The values of each pixel are passed to the filter function, which converts the input data and returns the desired color. After that, for the current pixel, we change the value in the general array of pixels and pass everything onto the canvas. Something like this. FPS sags just the same when passing pixel values.
Here is a sample code:
for (var y = 0; y < this.canvas.height; y++) { for (var x = 0; x < this.canvas.width; x++) { var index = getIndex(x, y); *//Проседает в этой части* var pix = { r: imgData.data[index], g: imgData.data[index + 1], b: imgData.data[index + 2] }; var color = calcGrayScale(pix); this.setPixel(index, color); } } function getIndex (x, y) { return y * canvas.width * 4 + x * 4; } function setPixel (index, color) { imgData.data[index] = color.r; imgData.data[index + 1] = color.g; imgData.data[index + 2] = color.b; imgData.data[index + 3] = 255; } function calcGrayScale(pix) { var color = (pix.r + pix.g + pix.b) / 3; return { r: color, g: color, b: color }; } An example of another code:
var color = { r: 0, g: 0, b: 0 }; for (var i = 0; i < data.data.length; i += 4) { color.r = data.data[i]; color.g = data.data[i + 1]; color.b = data.data[i + 2]; color.r = color.b = color.g = (color.r + color.g + color.b) / 3; data.data[i] = color.r; data.data[i + 1] = color.g; data.data[i + 2] = color.b; } this.ctx.putImageData(data, 0, 0); This code also applies the Gray filter, but the FPS no longer sags. Question: what should I do if I prefer the first option?
Here is an example of work: (First, the desired image is drawn, and then we manipulate the pixels)
