summaryrefslogtreecommitdiffstats
path: root/dom/html/reftests/toblob-todataurl/dataurl.js
blob: 8ffba1fa8edfca3c3a330dc6bb2fb0a1794bf1a2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
function init() {
  function end() {
    document.documentElement.className = '';
  }

  function next() {
    compressAndDisplay(original, end);
  }

  var original = getImageFromDataUrl(sample);
  setImgLoadListener(original, next);
}

function compressAndDisplay(image, next) {
  var canvas = document.createElement('canvas');
  canvas.width = image.naturalWidth;
  canvas.height = image.naturalHeight;
  var ctx = canvas.getContext('2d');
  ctx.drawImage(image, 0, 0);

  var dataUrl;
  // I want to test passing undefined as well
  if ('quality' in window) {
    dataUrl = canvas.toDataURL('image/jpeg', quality);
  } else {
    dataUrl = canvas.toDataURL('image/jpeg');
  }

  var img = getImageFromDataUrl(dataUrl);
  setImgLoadListener(img, next);
  document.body.appendChild(img);
}

function setImgLoadListener(img, func) {
  if (img.complete) {
    func.call(img, { target: img});
  } else {
    img.addEventListener('load', func);
  }
}

function naturalDimensionsHandler(e) {
  var img = e.target;
  img.width = img.naturalWidth;
  img.height = img.naturalHeight;
}

function getImageFromDataUrl(url) {
  var img = document.createElement('img');
  img.src = url;
  setImgLoadListener(img, naturalDimensionsHandler);

  return img;
}

init();