Reputation: 386
I know this question has been asked before but mine is a little different I think...
I am trying to create a canvas from several images one being a facebook users profile picture (which i'm saving to get around the cross domain issue) but still getting a blank png back?
heres the code
<canvas id="canvas" width="500px" height="500px"></canvas>
<img id="canvasImg" src=""/>
<?php
$username = $user_profile['username'];
$image = file_get_contents("https://graph.facebook.com/$username/picture?type=large"); // sets $image to the contents of the url
file_put_contents("_assets/img/users/$username.gif", $image); // places the contents in the file /path/image.gif
?>
<script>
function drawCanvas() {
var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');
var imageObj2 = new Image();
imageObj2.src = "_assets/img/users/<?php echo $username; ?>.gif";
imageObj2.onload = function() {
context.drawImage(imageObj2, 0, 0);
context.font = "20pt Calibri";
context.fillStyle = 'ffffff';
context.fillText("My TEXT 2!", 70, 120);
};
var imageObj1 = new Image();
imageObj1.src = "_assets/img/bg_main.jpg";
imageObj1.onload = function() {
context.drawImage(imageObj1, 150, 150);
context.font = "20pt Calibri";
context.fillStyle = 'ffffff';
context.fillText("My TEXT!", 70, 60);
};
var dataURL = canvas.toDataURL("image/jpg", 1.0);
document.getElementById('canvasImg').src = dataURL;
}
</script>
<script>
$(document).ready(function(){
drawCanvas();
});
</script>
Upvotes: 2
Views: 259
Reputation: 1636
You call canvas.toDataURL("image/jpg", 1.0); before your image are loaded, and so before the canvas is filled. You must check image loading state before doing that:
imageObj2.onload = function() {
context.drawImage(imageObj2, 0, 0);
context.font = "20pt Calibri";
context.fillStyle = 'ffffff';
context.fillText("My TEXT 2!", 70, 120);
var imageObj1 = new Image();
imageObj1.src = "_assets/img/bg_main.jpg";
imageObj1.onload = function() {
context.drawImage(imageObj1, 150, 150);
context.font = "20pt Calibri";
context.fillStyle = 'ffffff';
context.fillText("My TEXT!", 70, 60);
var dataURL = canvas.toDataURL("image/jpg", 1.0);
document.getElementById('canvasImg').src = dataURL;
};
};
Upvotes: 3