oakmac / chessboardjs

JavaScript chessboard
https://chessboardjs.com
MIT License
1.98k stars 408 forks source link

Cache images #55

Open Zolmeister opened 10 years ago

Zolmeister commented 10 years ago

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]
...
cocosistemas commented 10 years ago

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 !

steinitz-zz commented 9 years ago

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.

oakmac commented 8 years ago

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