# How to blend the surface with HTML5 canvas?

I can simply blend the surface in GameMaker using these codes:

//colour with which to blend the surface.
draw_surface_ext(index, x, y, xscale, yscale, rot, colour, alpha);


or set "the Fade to a Color" property, it will looks like this:

For now I want to do the same thing with HTML5 canvas, but I don't know where to start, is there any canvas API that could do that?

This answer assumes you are using the 2d context for the canvas, not the 3d context (aka WebGL).

The 2d context for HTML5 canvas doesn't come with such neat image filtering algorithms out-of-the-box, so you have to implement them yourself.

Use context.getImageData to get an array of RGBA values, change them, and write them back with context.putImageData. Here is an example which recolors a canvas based on its greyscale values. I tried to keep this example as simple as possible. You might have to tweak this algorithm a bit to get the results which work best for you.

// "red", "green" and "blue" are expected to be in range 0.0 - 1.0
function recolorCanvas(ctx, red, green, blue) {

var imgData = ctx.getImageData(0, 0, ctx.canvas.width, ctx.canvas.height);
for (var i = 0; i < imgData.data.length; i += 4) {
var brightness = (imgData.data[i] + imgData.data[i+1] + imgData.data[i+2]) / 3;
imgData.data[i] = brightness * red;
imgData.data[i+1] = brightness * green;
imgData.data[i+2] = brightness * blue;
}
ctx.putImageData(imgData, 0, 0);

}


Keep in mind that this is a quite slow operation, because it's done entirely on the CPU. So if you can, you should avoid doing it every frame. You can do this on an invisible background canvas to keep the result in memory.

If you use the 3d context (webGL) you have the full power of pixel shaders at your disposal. That means you can program such algorithms to run on the graphics chip, which will be far faster. But that would look completely different code-wise. Shader programming is not my area of expertise. Maybe someone else would like to write a separate answer explaining how to write a simple recoloring pixel shader for unlit sprites.

• I think gamemaker used the webGL in its html5 module,but the source code was compressed. – undefined000 Apr 15 '17 at 12:25
• @undefined000 WebGL is based on OpenGL, which is the most widely supported graphics API. The GameMaker people want to support a wide variety of platforms. So it would make sense for them to use OpenGL in order to make it easier to port features to all platforms. – Philipp Apr 15 '17 at 12:40