D3
OG
Old school D3 from simpler times
All examples
By author
By category
About
biovisualize
Full window
Github gist
Resizing canvas preserving antialiasing
<!DOCTYPE HTML> <html> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <style> canvas{ border: silver 1px solid; } </style> </head> <body> <div id="original"><canvas></canvas></div> <div id="wrong"></div> <div id="correct"></div> <script> // Modified from https://stackoverflow.com/a/17862644/537080 function cloneCanvasNoAliasing(oldCanvas, _w, _h) { var w = _w || oldCanvas.width; var h = _h || oldCanvas.height; var newCanvas = document.createElement('canvas'); var context = newCanvas.getContext('2d'); newCanvas.width = w; newCanvas.height = h; context.drawImage(oldCanvas, 0, 0, oldCanvas.width, oldCanvas.height, 0, 0, w, h); return newCanvas; } function cloneCanvas(oldCanvas, _w, _h) { var w = _w || oldCanvas.width; var h = _h || oldCanvas.height; var offlineCanvas = document.createElement('canvas'); offlineCanvas.width = oldCanvas.width; offlineCanvas.height = oldCanvas.height; var offlineCanvasCtx = offlineCanvas.getContext('2d'); offlineCanvasCtx.fillStyle = 'white'; offlineCanvasCtx.fillRect(0, 0, oldCanvas.width, oldCanvas.height); offlineCanvasCtx.drawImage(oldCanvas, 0, 0, offlineCanvas.width, offlineCanvas.height); var divisionCountW = Math.round(Math.log(oldCanvas.width/w)/Math.log(2)); var divisionCountH = Math.round(Math.log(oldCanvas.height/h)/Math.log(2)); var i; for(i=0; i<divisionCountW; i++){ offlineCanvasCtx.drawImage(offlineCanvas, 0, 0, offlineCanvas.width/2, offlineCanvas.height); } for(i=0; i<divisionCountH; i++){ offlineCanvasCtx.drawImage(offlineCanvas, 0, 0, offlineCanvas.width, offlineCanvas.height/2); } var newCanvas = document.createElement('canvas'); newCanvas.width = w; newCanvas.height = h; var newCanvasContext = newCanvas.getContext('2d'); newCanvasContext.drawImage(offlineCanvas, 0, 0, offlineCanvas.width, offlineCanvas.height); return newCanvas; } var width = 800; var height = 200; var dataCount = 100; var canvas = document.querySelector('#original canvas'); canvas.width = width; canvas.height = height; var ctx = canvas.getContext('2d'); ctx.strokeStyle = '#0055EE'; ctx.beginPath(); var i, points = [], rnd, step = width/dataCount; for(i = 0; i <= width; i+=step){ rnd = Math.random()*height; points.push(rnd); ctx.lineTo(i, rnd); } ctx.stroke(); document.querySelector('#wrong').appendChild(cloneCanvasNoAliasing(canvas, width / 4, height / 2)); document.querySelector('#correct').appendChild(cloneCanvas(canvas, width / 4, height / 2)); </script> </body> </html>