SHARE
TWEET

Untitled

a guest Feb 22nd, 2019 63 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function getTextOffset(fontSize, font, textBaseline) {
  2.         var text = 'test',
  3.             canvas = document.createElement('canvas'),
  4.             width = 300,
  5.             height = parseFloat(fontSize) * 2;
  6.  
  7.         canvas.width = width;
  8.         canvas.height = height;
  9.  
  10.         var cctx = canvas.getContext('2d');
  11.         cctx.textBaseline = textBaseline || 'middle';
  12.         cctx.font = font;
  13.         cctx.fillStyle = 'red';
  14.         cctx.fillText(text, 0, 0);
  15.  
  16.         var imgdata = cctx.getImageData(0, 0, width, height);
  17.         var d = imgdata.data;
  18.  
  19.         var offsetX = 10000000,
  20.             offsetY = offsetX;
  21.  
  22.         for (var y = 0; y < height; y++) {
  23.             for (var x = 0; x < width; x++) {
  24.                 var n = (y * width + x) * 4;
  25.                 if (d[n + 3] > 0) {
  26.                     if (y < offsetY) {
  27.                         offsetY = y;
  28.                     }
  29.                     if (x < offsetX) {
  30.                         offsetX = x;
  31.                     }
  32.                 }
  33.             }
  34.         }
  35.  
  36.         return { x: offsetX, y: offsetY };
  37.     }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
Not a member of Pastebin yet?
Sign Up, it unlocks many cool features!
 
Top