Am working on a site which allows users to participate in polls and earn some points. I’d like them to be able to display their username + score + some other stuff on any website, for example their own blog, forum signatures, etc. as an image. Kindof like stackoverflow flair !
Ofcourse, since their scores and other data will keep changing, I’d like the image to be generated dynamically (I am using php). I have got to a point using canvas where the canvas-png image displays fine on my site, but if I try to use the page url as a src in an img tag, the image doesnot show up.
Below is the page which generates the canvas :
<html>
<head>
<script type="text/javascript" src="/jscripts/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
var canvas = document.getElementById("c"),
context = canvas.getContext("2d");
context.fillStyle = "rgb(155, 155, 155)";
context.fillRect(0, 0, 250, 100);
context.stroke();
var imgObj = new Image();
imgObj.onload = function ()
{
// Draw the image on the canvas
context.drawImage(imgObj, 4, 8, 32, 32);
}
imgObj.src="<?=$iUser->avatar?>";
var username = "Username from php";
context.fillStyle = "rgb(0, 0, 0)";
context.font = "18px sans-serif";
context.fillText(username, 42, 20);
var score = "CGH Score : " + "146";
context.fillStyle = "rgb(0, 0, 0)";
context.font = "14px sans-serif";
context.fillText(score, 42, 40);
var img_data=canvas.toDataURL('image/png');
var img_element="<img src=\"" + img_data + "\" />";
$("#c").remove();
$("head").html("<meta http-equiv=\"content-type\" content=\"image/png\"/>");
$("body").html(img_element);
//document.body="<img src=\"" + img_data + "\" />";
//document.write(img_data);
//var output=img_data.replace(/^data:image\/(png|jpg);base64,/, "");
//$.post("/show_img/",{image_data:output});
//window.location = canvas.toDataURL('image/png');
});
</script>
</head>
<body>
<canvas id="c"></canvas>
</body>
</html>
If you load that into an image tag, the browser will NOT interpret/execute the JS. it’ll try to figure what kind of binary image format (gif/jpg/png/etc…) the raw bytes of that page’s source are, and fail. Img tags are not a way to load a remote page/code into a page.
For this to work, you’d need to have the users insert a snippet of JS which loads the script dynamically from your site.
e.g. instead of
you’d have