简体   繁体   中英

Tumblr and HTML5 - Canvas for Square Grid?

I am trying to add HTML5 to a tumblr theme to generate 250px by 250px crops of the image posts found on a blog and use them in place of the normal 500px image. I am currently using the following code to load the images within the photo posts:

  <canvas id="myCanvas" width="250" height="250"></canvas>
  <script>
  var canvas = document.getElementById('myCanvas');
  var context = canvas.getContext('2d');
  var imageObj = new Image();

  imageObj.onload = function() {
    // draw cropped image
    var sourceX = 150;
    var sourceY = 0;
    var sourceWidth = 250;
    var sourceHeight = 250;
    var destWidth = sourceWidth;
    var destHeight = sourceHeight;
    var destX = canvas.width / 2 - destWidth / 2;
    var destY = canvas.height / 2 - destHeight / 2;

    context.drawImage(imageObj, sourceX, sourceY, sourceWidth, sourceHeight, destX, destY, destWidth, destHeight);
  };
  imageObj.src = '{PhotoURL-500}';
  </script>

With the above code, I am given a 250x250 crop of the last photo that would be loaded on the page in the position of the first photo post which can be seen here . I've done some research and from what I understand, the issue lies within imageObj.onload but I am not sure what alterations are necessary to make the code properly display the photos.

Any ideas of what I can do to fix this?

All of your canvas id's are the same, which is a no no, and explains why the only canvas with anything drawn to it is the first one. I'm not really sure why you have so much repeating code (multiple script blocks which are completely identical aside from the image url), but as long as you ensure each canvas has a unique id referenced appropriately in its corresponding script block as well as unique Image objects, it should work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM