How to display dynamically generated canvas image on other websites - php

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
<img src="http://yoursite.com/canvas.php" />
you'd have
<script src="http://yoursite.com/canvas.php" /></script>

Create these images with PHP instead.
http://php.net/manual/en/function.imagejpeg.php
Or put this page in an IFRAME if you insist to use Canvas.

Related

Flexslider image <li> dynamically generated by php. Trying to create captions using alt text

I have a vanilla flexslider installation on my site. The slider operates by cycling through list items in an unordered list. You can add captions simply by adding a caption container after the list item. This works well with hard coded images.
The problem I am facing is that my site has multiple sections, with a different slide show for each section. Instead of hard coding the li elements, I'm generating them with php, so that when a user visits a page, the php figures out which page the user is viewing, and passes that through to the slideshow. The slideshow then finds the proper image directory and loads all of the images in that directory whether there be two or twenty. It's much easier than hard coding each slideshow, and it works beautifully.
<?php
$dh = "image/slideShows/$slideShow/";
$images = glob($dh . "*.jpg");
foreach($images as $image){
?><li><img src="<?php echo $image;?>" alt="caption text" /></li><?php
}
closedir($dh);
?>
I need to get flexslider to read the alt text for each dynamically generated image, and then place it in a caption container:
<p class="caption">The alt text should show up here.</p>
I've tried using:
$(window).load(function() {
$('.flexslider').flexslider({
animation: "fade",
controlsContainer: "#slideShowContainer",
start: function(slider) {
$('.caption').html(this.alt);
},
});
});
and playing around with flexslider's current.slide to no avail. I've been searching on this all night and I can't seem to figure this one out. I'm hoping someone here can provide the missing link for me.
Thanks in advance.
EDIT: I figured this out, and it was seriously a matter of over-complication. All I had to do was call the EXIF data that I was using for the "alt" attribute inside of the caption. I have no idea why it took me so long to realize this. Thank you both for your help!
start: function(slider) {
var slideNumber = slider.currentSlide;
var alt = $('.slides img').eq(slideNumber + 1).attr('alt');
$('.caption').html('<p>' + alt + '</p>');
},
before: function(slider) {
var slideNumber = (slider.currentSlide + 1);
var alt = $('.slides img').eq(slideNumber + 1).attr('alt');
$('.caption').html('<p>' + alt + '</p>');
}
It sounds like you have only one .caption box? And you want its contents to change with each slide?
I would try something like:
before: function(slider) {
var slideNumber = slider.currentSlide;
var alt = $('.slides img').eq(slideNumber).attr('alt');
$('.caption').html('<p>' + alt + '</p>');
});
},
note that before runs at each slide transition, not just once like start
Edit
OP adjusted the above code (see comments below), but still has the "issue mentioned in the comment where the first image doesn't get a caption on it's second and subsequent scrolls"
Perhaps we should be using after instead of before? That way we don't need to do slideNumber+1 (since before was making this the previous slide.. You can perhaps remove the start function in favor of just doing this above the flexslider call
in $(window).load(function(){ or (document).ready(){:
var alt = $('.slides img').eq(0).attr('alt');
$('.caption').html('<p>' + alt + '</p>');
and within flexslider()
after:function(slider) {
var slideNumber = slider.currentSlide;
var alt = $('.slides img').eq(slideNumber).attr('alt');
$('.caption').html('<p>' + alt + '</p>');
},

How to make a simple dynamic slideshow/timelapse

I have a folder where are saved images from a webcam each X time.
I want to use these image to create a slideshow without transitions effects or music => i want to make a timelaps!
These slideshow must be dynamic (i can use php to build the list of image, each time a user want to watch the "video").
Any sugguestion and code to do this? Javascript? Php? or others??
Thanx!
That's the best way i found: simple and speedy
<HTML>
<HEAD>
<TITLE>Video</TITLE>
</HEAD>
<BODY BGCOLOR="#000000">
<img name="foto">
<SCRIPT LANGUAGE="JavaScript">
var Pic = new Array();
Pic[0] = '/images/image1.jpg'
Pic[1] = '/images/image2.jpg'
Pic[2] = '/images/image3.jpg'
//this part in real code is replaced with a PHP script that print image location dinamically
var t;
var j = 0;
var p = Pic.length;
var preLoad = new Array();
for (i = 0; i < p; i++) {
preLoad[i] = new Image();
preLoad[i].src = Pic[i];
}
//all images are loaded on client
index = 0;
function update(){
if (preLoad[index]!= null){
document.images['foto'].src = preLoad[index].src;
index++;
setTimeout(update, 1000);
}
}
update();
</script>
</BODY>
</HTML>
Have your PHP script send a meta refresh tag in the heading to reload the page with the latest image after the desired time.
NOTE: There are better, more AJAX-like ways of doing this, but this is the simplest. Using AJAX to reload just the image and not the whole page would be harder to write but a better user experience.

Getting data through a PHP file using AJAX+JQuery

I'm working on a gallery that pulls up a full image inside a tooltip when hovering over thumbnails. The problem is, these full images commonly go outside the viewfinder. To remedy this, I'm moving the tooltip if the image will go outside the window boundaries, which requires immediately knowing the images dimensions (to avoid the tooltip jumping around).
However, the images take a bit to load (.gifs) so I can't wait on DOM in order to get the dimensions. So, I'm calling a PHP script to return the the image dimensions before they load.
The problem I'm having is that there's no response from my $.get call. I know the PHP script is working fine, but I'm not getting any data back from it through jquery. Any help would be greatly appreciated. Thanks!!
hover.js:
this.imagePreview = function(){
$("a.preview").hover(function(e){
var viewHeight = $(window).height() + $(window).scrollTop();
var viewWidth = $(window).width();
var xOffset=e.pageX+40;
var yOffset=e.pageY+40;
var url = 'http://mysite.com/i/' + this.href.slice(20);
var w = 0;
var h = 0;
$("body").append("<div id='preview'><img src=" + url +" id='img'/></div>");
$.get("getDimensions.php/?img=" + url, function(data){
w = data.w;
h = data.h;
$("body").append("INFO ABOUT IMAGE DIMENSIONS TRIGGERED: " + w + h);
});
$("#preview")
.css("top",yOffset + "px")
.css("left",xOffset + "px")
.fadeIn("fast");
$('#img').load(function() {
if((e.pageX+img.width)>viewWidth) { xOffset=e.pageX-img.width-70; }
if((e.pageY+img.height)>viewHeight) { yOffset=e.pageY-img.height-70; }
$("#preview")
.css("top",yOffset + "px")
.css("left",xOffset + "px")
.fadeIn("fast");
});
},
function(){
$("#preview").remove();
});
};
// starting the script on page load
$(document).ready(function(){
imagePreview();
});
getDimensions.php:
<?php
list($width, $height, $type, $attr) = getimagesize($img);
echo json_encode(array("w"=>$width,"h"=>$height));
?>
$("body").append("<div id='preview'><img src=" + url +" id='img'/></div>");
when u append the img which have src prop,that will not fire load event any more.That's the problem is.
Have you tried..
var rand = Math.floor(Math.random()*11);
$.get("getDimensions.php/?img=" + url + "&r=" + rand, function(data){
w = data.w;
h = data.h;
$("body").append("INFO ABOUT IMAGE DIMENSIONS TRIGGERED: " + w + h);
},"json");
( Also, I would strongly recommend .ajax over .get)
Can you view what you are getting back from getDimensions.php (in firebug)?
My guess is that jQuery has no way of knowing that the data returned from getDimensions.php is JSON (as opposed to plain old text), and it isn’t trying to parse it.
What's the value of data (if you print it out to the console)?
If this is the problem, you can solve it by adding this line to the PHP script, before echo:
header('Content-Type: application/json');

javascript - Is there a way to grab these values with php?

I have this JS code which works by using the onclick method and opens an image in a new window which is the exact size of the image.
I adapted it from the BolGallery script. but the bolGallery script parses this in PHP and is able to get the the 'title','width' and 'height' values dynamically. and also the 'ImageFile' value.
My question is, is there a way to get these with php?
Im not very knowledgeable with JS
function GalleryPopup(imageFile, width, height, title){
var html = '<title>' + title + ' - Click to close </title><body leftmargin=0 topmargin=0 marginwidth=0 marginheight=0 onclick=\"javascript:window.close()\"><img src=\"' + imageFile + '\" alt=\"Click to close\"></body>';
var popup = window.open(imageFile, '_blank', 'width=' + width+ ', height=' + height + ', status=no');
popup.document.write(html);
popup.focus();
}
alternatively, if you know of any other ways to achieve what i'm going for then feel free to tell me.
For Instance i dont know what to set the variable like:
$imagetitle =
Would that work?
i also have jQuery..
in jQuery you can get size of image with:
$('img').width();
$('img').height();
// this is used to grab the source file and title:
$('img').attr('src');
$('img').attr('title');

<div> of images, retrieved by getJSON, disappear after append()

I'm working on a GMaps application to retrieve images, via getJSON(), and to populate a popup marker.
The following is the markup which I add to the marker dynamically:
<div id="images"></div>
<div id="CampWindow" style="display:none;width:550px;height:500px;">
<h4 id="camp-title"></h4>
<p>View... (all links open in new windows)</p>
<ul>
<li><a id="camp-hp-link" target="_blank" href="">camp home page</a></li>
<li>information: <a id="camp-av-link" target="_blank" href="">availability</a> | <a id="camp-vi-link" target="_blank" href="">vital information</li>
</ul>
<p id="message"></p>
I've been clawing out my eyes and woohoo for the past couple of days, trying to get the images to show inside the CampWindow . Then, I decided to think laterally and to see if the images were being retrieved at all. I then moved the images outside and sure as Bob (Hope), the images were being retrieved and refreshed with every click.
So, I decided to the keep the images outside and then once loaded, append it to the CampWindow . It's not working still; when I append the div to the main CampWindow div, the images won't show. I check in Firebug with the pointer thingy and it shows me the images as empty. I try it again with the images outside and it shows the images. I've tried before append and appendTo with no success. Am I missing something here?
I have no more woohoo to claw out. Please, please help.
marker.clicked = function(marker){
$("#images").html('');
$('#camp-title').text(this.name);
$('#camp-hp-link').attr('href', this.url);
$('#camp-av-link').attr('href', this.url + '/tourism/availability.php');
$('#camp-vi-link').attr('href', this.url + '/tourism/general.php');
// get resort images via jQuery AJAX call - includes/GetResortImages.inc.php
$.getJSON('./includes/GetResortImages.inc.php', { park: this.park_name, camp: this.camp_name }, RetrieveImages);
function RetrieveImages (data)
{
if ('failed' == data.status)
{
$('#messages').append("<em>We don't have any images for this rest camp right now!</em>");
}
else
{
if ('' != data.camp)
{
$.each(data, function(key,value){
$("<img/>").attr("src", value).appendTo('#images');
});
}
}
}
//.append($("#images"));
$("#CampWindow").show();
var windowContent = $("<html />");
$("#CampWindow").appendTo(windowContent);
var infoWindowAnchor = marker.getIcon().infoWindowAnchor;
var iconAnchor = marker.getIcon().iconAnchor;
var offset = new google.maps.Size(infoWindowAnchor.x-iconAnchor.x,infoWindowAnchor.y-iconAnchor.y);
map.openInfoWindowHtml(marker.getLatLng(), windowContent.html(), {pixelOffset:offset});
}
markers.push(marker);
});
When you add the <html> tag to your page it confuses the browser and is most likely the problem. I would suggest to either do as Pointy said and use window.open() to make a popup window (check out this tutorial), or better yet try out one of the many jQuery light box plugins.
I'm not sure what you are doing with the google maps, so I decided to just go with a basic example for you. With this script, if you click on an image inside the #image div, it'll open a popup window the same size as the image.
$(document).ready(function(){
$('#images img').click(function(){
var padding = 20;
var w = $(this).width() + padding;
var h = $(this).height() + padding;
var popup = '\
<html>\
<head>\
<link type="text/css" href="popup-style.css" rel="stylesheet" />\
<scr'+'ipt type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></scr'+'ipt>\
</head>\
<body>\
<img src="' + $(this).attr('src') + '">\
</body>\
</html>';
var pop = window.open('','Image View','toolbar=0,location=0,status=0,width=' + w + ',height=' + h + ',scrollbars=1,resizable=1');
pop.document.write(popup);
pop.document.close();
})
});
NOTE: When adding a script tag inside a string, make sure you break up the word "script" otherwise you will get an error.
Update #2:
Ok, since you want to work with what you have, try doing this:
Remove the <html> tag from your campwindow, then position your campwindow using CSS and/or javascript. Add something like:
var w = $(window).width();
var h = $(window).height();
// Add overlay and make clickable to hide popup
// you can remove the background color and opacity if you want to make it invisible
var $overlay = $('<div/>', {
'id': 'overlay',
css: {
position : 'absolute',
height : h + 'px',
width : w + 'px',
left : 0,
top : 0,
background : '#000',
opacity : 0.5,
zIndex : 99
}
}).appendTo('body');
// Position your popup window in the viewport
$('#CampWindow').css({
position: 'absolute',
top : $(window).scrollTop() + 50 + 'px',
left : w/2 - $('#CampWindow').width()/2 + 'px', // centers the popup
zIndex : 100
})
.fadeIn('slow');
// Click overlay to hide popup
$('#overlay').click(function(){
$('#CampWindow').hide();
$(this).remove(); // remove the overlay
})

Categories