Reputation: 97
I would like to generate a image from first canvas and then draw in the another canvas, but i have a problem because i don't know why i don't see nothing in the other canvas. It's my code:
<canvas id="gameCanvas" width="704" height="608" />
<script type='text/javascript'>
// prepaire our game canvas
var canvas = document.getElementById("gameCanvas");
var context = canvas.getContext("2d");
var ctx = document.createElement("canvas").getContext("2d");
ctx.canvas.width = 2048;
ctx.canvas.height = 2048;
var rows = 64;
var columns = 64;
this.image = new Image();
var imageObject = document.createElement("img");
var me = this;
/// need this as loading is async
imageObject.onload = function() {
for (var i = 0; i < rows; i++) {
for (var j=0; j <columns; j++) {
ctx.drawImage(this, i*32,j*32,32,32);
}
}
// store the generate map as this image texture
me.image.src = ctx.canvas.toDataURL("image/jpg");
}
imageObject.src='ground.jpg';
this.image.src = ctx.canvas.toDataURL("image/jpg");
context.drawImage(this.image, 0, 0, 300, 300, 0, 0, 300,300);
</script>
Please for advice why it doesn't work?
Upvotes: 1
Views: 2887
Reputation: 951
After creating DOM element, you should append it on the other element to display it.
Try this
script:
var canvas = document.getElementById("gameCanvas");
var ctx = canvas.getContext("2d");
var image=document.createElement("img");
image.onload=function(){
canvas.width = image.width;
canvas.height=image.height;
ctx.drawImage(image,0,0);
var tcanvas = document.createElement('canvas');
var tctx = tcanvas.getContext('2d');
tcanvas.width = 8*image.width;
tcanvas.height = 8*image.height;
for(var i=0;i<8;i++){
for(var j=0;j<8;j++){
tctx.drawImage(image, i*image.width,j*image.height);
document.body.appendChild(tcanvas);
}
}
}
image.src="https://lh4.googleusercontent.com/-L1cr04d6ONc/RsRykgOl9zI/AAAAAAAABIE/WqBGOdiJnys/s128/Finishes.Flooring.Tile.Square.Blue.bump.jpg";
Upvotes: 1
Reputation: 69773
context.drawImage
can work with a <canvas>
just like it can work with an <img>
. You can use your background canvas (the canvas itself, not the context) as a source just like you can use an image.this.image.src
to the dataUrl of the canvas, and then you use that image for context.drawImage
. At that point, the canvas will likely still be empty, so the data-url will also be that of an empty image.Solution: Put the last line of your code into the onload-function.
Upvotes: 0