Skip to content

Instantly share code, notes, and snippets.

@mientjan
Created July 23, 2013 12:07
Show Gist options
  • Save mientjan/6061878 to your computer and use it in GitHub Desktop.
Save mientjan/6061878 to your computer and use it in GitHub Desktop.
Make Chrome scroll smooth with large images that are moving
function makeChromeSmoothReplaceImage(img, maximumSize){
var canvas = document.createElement('canvas');
var ctx = canvas.getContext('2d');
var newImg = new Image();
newImg.onload = function(){
var width = parseInt(this.width),
height = parseInt(this.height);
if( width > maximumSize || height > maximumSize )
{
// one = true;
canvas.width = this.width;
canvas.height = this.height;
ctx.drawImage(this, 0, 0);
var div = $(document.createElement('div'))
.attr('id', $(img).attr('id'))
.attr('class', $(img).attr('class'));
$(img).replaceWith(div);
var rx = Math.ceil(width/maximumSize),
ry = Math.ceil(height/maximumSize),
tempCanvas = document.createElement('canvas'),
tempCtx = null;
tempCanvas.width = maximumSize;
tempCanvas.height = maximumSize;
var s = maximumSize,
ox = width % maximumSize,
oy = height % maximumSize;
for(var x = 1;x<=rx;++x)
{
for(var y = 1;y<=ry;++y)
{
var newX = x*s-s;
var newY = y*s-s;
var newWidth = Math.min(width - (x*s-s), s);
var newHeight = Math.min(height - (y*s-s), s);
tempCanvas = document.createElement('canvas');
tempCanvas.width = newWidth + 2;
tempCanvas.height = newHeight + 2;
tempCtx = tempCanvas.getContext('2d');
tempCtx.putImageData(
ctx.getImageData(
newX,
newY,
newWidth + 2,
newHeight + 2
), 0, 0
);
tempCanvas.style['-webkit-transform'] = 'translate3d('+[newX,newY,0].join('px,')+'px)';
div.append(tempCanvas);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment