Canvas- Compositing and Mixing Images

Written by @m_k_amin 21 June 2013

It is important to set how the images formats must be when two or more ones are drawn on each other. HTML5 Canvas Composition is a parameter which sets whether the destination (background) image must be at top or the source one. It is also possible to mix them or ignore the parts which are out side of the specific image area. By combining this feature and alpha value for the transparency, you can achieve beautiful picture effects. Note that this feature is not just for images which have an external source; you can act with your own HTML5 Canvas drawn element as an image, too (refer to previous posts). See the following example to figure out more about these Canvas settings; be aware that all features may not be available for all browsers.

Code Snippet:

                                                <!-- this script is provided by coded by: Kerixa Inc. -->
<!-- This Script is from, Coded by: Kerixa Inc-->

<select name="Slc" id="slc" onchange="redraw()">

	<option selected="selected" >Choose one . . .</option>










	<option >source-over</option>



Transparency (src):&nbsp;&nbsp;	

<input name="Alp1" id="alpB" type="range" style="width: 100px" value="1" max="1" min="0" step="0.1" onchange="redraw()"><br>

Transparency (dst):&nbsp;&nbsp;	

<input name="Alp2" id="alpF" type="range" style="width: 100px" value="1" max="1" min="0" step="0.1" onchange="redraw()"><br>

<canvas id="myCanvas" width="400" height="200"></canvas>

<img src="
html5-canvas-compositing.jpg" id="Bimg" style="display:none"/>

<img src="
html5-canvas-drawimage.jpg" id="Fimg" style="display:none"/>


    var cnv = document.getElementById('myCanvas')

    var ctx = cnv.getContext('2d')


	var bimg= document.getElementById('Bimg')

	var fimg= document.getElementById('Fimg')

	var comp= document.getElementById('slc')

	var alphab= document.getElementById('alpB')

	var alphaf= document.getElementById('alpF')	

	window.addEventListener('load', loaded, false)

function loaded(){



function redraw(){


	ctx.globalAlpha= alphab.value	

	ctx.drawImage(bimg, 0, 0, 200, 200)

	ctx.globalAlpha= alphaf.value

	ctx.globalCompositeOperation = comp.value

	ctx.drawImage(fimg, 70, 40, 200, 150)	


function reset(){

	ctx.globalCompositeOperation = 'source-over'

	ctx.globalAlpha= 1

	ctx.drawImage(bimg, 0, 0, 200, 200)

	ctx.drawImage(fimg, 70, 40, 200, 150)	



<div style="text-align: left"><font face="Tahoma"><a target="_blank" href=""><span style="font-size: 8pt; text-decoration: none">HTML5 Free Code</span></a></font></div><a target='_blank' href='' style='font-size: 8pt; text-decoration: none'>Html5 Free Codes</a>                                                


About @m_k_amin

This user is pending a biography.



Here you can leave us commments. Let us know what you think about this code tutorial!

0 / 300

Online Users: 12
Recent Members: Afzal, FOTPU
advertisement 2