Reputation: 10946
I want to draw multiple canvases on a single canvas using drawImage()
method but it is not working
Code
<html>
<head>
<script>
window.onload = function() {
var context1= document.getElementById("canvas1").getContext("2d");
var context2 = document.getElementById("canvas2").getContext("2d");
var context3 = document.getElementById("canvas3").getContext("2d");
context1.font = "20pt Calibri";
context1.fillStyle = "blue";
context1.fillText("Hello ", 50, 25);
context2.font = "20pt Calibri";
context2.fillStyle = "red";
context2.fillText("World!", 100, 25);
var imageObj = new Image();
imageObj.onload = function() {
context3.drawImage(context1.canvas, 50, 25);
context3.drawImage(context2.canvas, 100, 25);
};
};
</script>
</head>
<body>
<canvas id="canvas1" class="canvas" width="200" height="50"></canvas>
<canvas id="canvas2" class="canvas" width="200" height="50"></canvas>
<canvas id="canvas3" class="canvas" width="200" height="50"></canvas>
</body>
</html>
JS Fiddle http://jsfiddle.net/4xT2j/2/
Upvotes: 1
Views: 13678
Reputation: 382464
Your images have no source. Add one if you want to see something. The onload function cannot be called as long as you don't have a src.
And you must provide the image to the drawImage function :
var imageObj = new Image();
imageObj.onload = function() {
context3.drawImage(imageObj, 50, 25);
context3.drawImage(imageObj, 100, 25);
};
imageObj.src = "someFile.png";
If what you're trying to do is draw canvas1 and canva2 on context3, simply do all this outside the imageObj.onload function which is never called : http://jsfiddle.net/KCyvE/
A precision following a question in comment :
My code in the fiddle uses context1.canvas
. This works because The context is an instance of CanvasRenderingContext2D and thus has a property named canvas
which is a "Back-reference to the canvas element for which this context was created".
Upvotes: 6
Reputation: 12367
Your imageObj.onload
function is somewhat wrong. This is what you want: http://jsfiddle.net/4xT2j/3/
Please observe there isn't necessarily a reason to write canvas3 to an image object since it already is an image object.
Upvotes: 1