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);
}
// Draw pattern
function MyDrawPattern(context, pattern, x, y, width, height)
{
context.rect(x, y, width, height);
context.fillStyle = pattern;
context.fill();
}
</script>
<!-- master code -->
<script>
<!-- Files -->
var files = {
tree : "./tree.jpg",
my_pattern : "./my_pattern.png"
};
<!-- context for drawing -->
var canvas = document.getElementById('canvas1');
var context = canvas.getContext('2d');
<!-- upload images -->
loadImages(files, function (loadedImages)
{
<!-- Create pattern -->
var pattern = context.createPattern(loadedImages.my_pattern, 'repeat');
<!-- Draw pattern -->
MyDrawPattern(context, pattern, 10, 5, 370, 290)
<!-- drawing a picture -->
MyDrawImage(context, loadedImages.tree, 80, 20);
});
</script>
</body>
</html>
and
tree.jpg and
my_pattern.png the pictures must be in the same folder as the file
1.html