Canvas- Copy and Draw Image

Written by @m_k_amin 18 June 2013

HTML5 Canvas gives you ability to manipulate the images in your page. You can use an image and redraw it on the Canvas context; it is also possible to use the canvas itself as an image source for filling an HTML image element. HTML5 Canvas Draw Image feature is also used for cropping an image and also shrinking or magnifying it. In the following example we have cut part of an image and redrawn it. The redrawn image is zoomed in; so we have designed some kind of magnifier here!

Code Snippet:

                                                
                                                <!-- this script is provided by https://www.html5freecode.com coded by: Kerixa Inc. -->

<!-- This Script is from www.html5freecode.com, Coded by: Kerixa Inc-->
<canvas id="myCanvas" width="400" height="250"></canvas>
<img src="http://www.html5freecode.com/files/krishna.jpg" id="img" style="display:none"  />
<script>
	window.addEventListener('load', loaded, false)

function loaded(){	
    var cnv = document.getElementById('myCanvas')
    var ctx = cnv.getContext('2d')

	var img= document.getElementById('img')
	ctx.drawImage(img, 0, 0, 150, 220)
	ctx.strokeStyle= "red"
	ctx.strokeRect(39, 27, 30, 35)
	ctx.drawImage(cnv, 39, 27, 30, 35, 200, 50, 90, 105)

	ctx.beginPath()
	ctx.moveTo(39+30, 27)
	ctx.lineTo(200, 51)
	ctx.moveTo(39+30, 27+35)
	ctx.lineTo(200, 50+104)
    ctx.lineWidth= 2
    ctx.stroke()
}	
</script>
<div style="text-align: left"><font face="Tahoma"><a target="_blank" href="http://www.html5freecode.com"><span style="font-size: 8pt; text-decoration: none">HTML5 Free Code</span></a></font></div><a target='_blank' href='https://www.html5freecode.com' style='font-size: 8pt; text-decoration: none'>Html5 Free Codes</a>                                                
                                            

Example:


About @m_k_amin

This user is pending a biography.

M

Comments


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

0 / 300

TRENDING POST
1
2
3
4
5
VISITORS
Online Users: 12
Recent Members: Afzal, FOTPU
advertisement 2