chessboardjs icon indicating copy to clipboard operation
chessboardjs copied to clipboard

Cache images

Open Zolmeister opened this issue 12 years ago • 3 comments

Images are re-requested every animation update. This may also be the cause of #52 My solution was to cache the images in base64 url strings, which is implemented here: http://queens.zolmeister.com/

It looks like this:

var imgCache = {}
function cacheImages() {
  var pieces = ['wK', 'wQ', 'wR', 'wB', 'wN', 'wP', 'bK', 'bQ', 'bR', 'bB', 'bN', 'bP'];
  pieces.forEach(function(piece) {
    var img = new Image()
    img.onload = function() {
      imgCache[piece] = getBase64Image(img)
    }
    img.src = buildPieceImgSrc(piece)
  })

  function getBase64Image(img) {
    var canvas = document.createElement("canvas");
    canvas.width = img.width;
    canvas.height = img.height;
    var ctx = canvas.getContext("2d");
    ctx.drawImage(img, 0, 0);
    var dataURL = canvas.toDataURL("image/png");
    return dataURL;     
  }
}

function buildPieceImgSrc(piece) {
  if(imgCache[piece]) return imgCache[piece]
...

Zolmeister avatar Nov 24 '13 07:11 Zolmeister

Hello! I code this cache method in the library and the difference is really really great! no more flicker on pieces. Now I have a question: I must do a pull request with the modification? (Really the work and the idea is from @Zolmeister )

Note: Thanks @Zolmeister !

cocosistemas avatar Jul 03 '14 17:07 cocosistemas

I confirm that this works. A note to anyone trying this -- to get it working, I had to create imgCache and call cacheImages() at the top of the Window init as follows:

window['ChessBoard'] = window['ChessBoard'] || function (containerElOrId, cfg)
    {
        'use strict';
        var imgCache = {};
        cacheImages ();

I put the rest of the code near buildPieceImgSrc() per Zolmeister's helpful instructions.

steinitz-zz avatar Aug 10 '15 04:08 steinitz-zz

FYI - Issue #113 has a neat solution for this using a data-uri

oakmac avatar Nov 26 '15 19:11 oakmac