Picture
drawn with rotation on the screen like this:
Html
Let's write the code in the file 1.html :
<html>
<!-- heading -->
<head>
<meta charset="utf-8">
<title>Example</title>
</head>
<!-- page -->
<body>
<!-- HTML canvas -->
<canvas id="canvas1" width='400px' height='300px'></canvas>
<!-- JavaScript Functions -->
<script>
// we upload pictures from files
function loadImages(files, callbackAllFilesLoaded)
{
// count the number of files
var countFilesToLoad = 0;
for (var fileId in files)
{
countFilesToLoad++;
}
var images = {};
for (var fileId in files)
{
// create a blank picture
images[fileId] = new Image();
// event onload
images[fileId].onload = function()
{
// when all the files are loaded, call our function callbackAllFilesLoaded to draw a picture
if ( --countFilesToLoad <= 0 )
{
callbackAllFilesLoaded(images);
}
};
// uploading a picture
images[fileId].src = files[fileId];
}
}
// drawing a picture on canvas
function MyDrawImage(context, image, x, y)
{
// drawing a picture
context.drawImage(image, x, y);
}
// we draw a picture with a rotation on canvas
function MyDrawRotateImage(context, image, x, y, angleInDegree)
{
context.save();
context.translate(x + image.width/2, y + image.height/2);
context.rotate(angleInDegree * Math.PI / 180.0);
context.scale(1, 1);
context.drawImage(image, -image.width/2, -image.height/2);
context.restore();
}
</script>
<!-- master code -->
<script>
<!-- file -->
var files = {
tree : "./tree.jpg"
};
<!-- context for drawing -->
var canvas = document.getElementById('canvas1');
var context = canvas.getContext('2d');
<!-- upload images -->
loadImages(files, function (loadedImages)
{
<!-- drawing a picture -->
MyDrawImage(context, loadedImages.tree, 180, 54);
<!-- show a picture with rotation -->
MyDrawRotateImage(context, loadedImages.tree, 250, 54, 35 /* turn 35 degrees*/);
});
</script>
</body>
</html>
tree.jpg the picture must be in the same folder as the file
1.html