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);
}
function MyDrawText(context, text, color, font, x, y)
{
context.font = font;
context.fillStyle = color;
context.fillText(text, x, y);
}
</script>
<!-- master code -->
<script>
<!-- Files -->
var files = {
tree : "./tree.jpg"
};
<!-- context for drawing -->
var canvas = document.getElementById('canvas1');
var context = canvas.getContext('2d');
<!-- uploading a picture -->
loadImages(files, function (loadedImages)
{
<!-- drawing a picture -->
MyDrawImage(context, loadedImages.tree, 80, 20);
<!-- drawing text -->
MyDrawText(context, "Hello", "blue", "40pt Calibri", 150, 50);
MyDrawText(context, "world!", "green", "20pt Calibri", 150, 80);
});
</script>
</body>
</html>
Picture
tree.jpg must be in the same folder as the file
1.html