gpt4 book ai didi

javascript - 从 Canvas 元素制作图像

转载 作者:行者123 更新时间:2023-11-27 22:30:33 24 4
gpt4 key购买 nike

我知道以前有人问过这个问题,但我觉得我的有点不同......

我正在尝试从多张图片创建一个 Canvas ,其中一张是 Facebook 用户的个人资料图片(我正在保存它以解决跨域问题)但仍然得到空白的 png?

代码如下

    <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>

最佳答案

你调用 canvas.toDataURL("image/jpg", 1.0);在您的图像加载之前,因此在 Canvas 被填充之前。在执行此操作之前,您必须检查图像加载状态:

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;
};
};

关于javascript - 从 Canvas 元素制作图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18337204/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com