So I’m trying to create canvas elements using the information passed back by “The Loop”. The following is my code. It works, but only kind of, and only on the last canvas created by the loop.
<?php
query_posts(array('number_posts'=>5, 'orderby'=>'rand'));
while ( have_posts() ) : the_post(); ?>
<canvas class="post" id="<?=the_ID()?>">
<script type="text/javascript">
window.onload = function () {
var cur_post = document.getElementById('<?PHP echo $post->ID; ?>');
if (cur_post && cur_post.getContext) {
var context = cur_post.getContext('2d');
if (context) {
var img = new Image();
(function(img) {
img.src = "<?php
$args = array(
'post_type' => 'attachment',
'numberposts' => -1,
'post_status' => null,
'post_parent' => $post->ID
);
$attachments = get_posts( $args );
if ( $attachments ) {
$image_src_array = wp_get_attachment_image_src( $attachments[0]->ID, 'large' );
$image_src = $image_src_array[0];
echo $image_src;
}; ?>";
img.onload = function() {
img.width = parseInt(cur_post.offsetWidth);
var resize_quotient = img.width/img.naturalWidth;
img.height = img.naturalHeight*resize_quotient;
context.drawImage(img, 0, -(img.naturalHeight/2), img.width, img.height);
};
})(img);
};
};
};
</script>
<div class="post" style="background: url(<?php
$args = array(
'post_type' => 'attachment',
'numberposts' => -1,
'post_status' => null,
'post_parent' => $post->ID
);
$attachments = get_posts( $args );
if ( $attachments ) {
$image_src_array = wp_get_attachment_image_src( $attachments[0]->ID, 'large' );
$image_src = $image_src_array[0];
echo $image_src;
} ?>
) no-repeat center center;">
<p class="post_excerpt" style="clear: both"><?PHP the_excerpt() ?></p>
<div class="post_content">
<h2 class="post_title"><a href="<?php the_permalink() ?>"><?PHP the_title(); ?></a></h2>
<h3 class="post_category"><?php the_category() ?></h3>
</div>
</div>
</canvas>
<?php endwhile;
?>
Am I missing something obvious? I’ve tried logging everything I can think of, and I get unique values for each item, but only the last canvas has anything drawn on it. I even tried using a self-referencing anonymous function as I saw this was a fix on another related page. Also, even when it does place the image on the last canvas, it doesn’t resize the image at all when it draws it.
Help?
I needed to wrap the entire first if statement after cur_post in a self-referencing anonymous function. I had one deeper in the code, it just needed to move up so that it was referencing each individual canvas and not just the last one: