Last active
January 18, 2017 12:21
-
-
Save dei-biz/ba93fd989093e370d12162ecb561f907 to your computer and use it in GitHub Desktop.
scale a region of a canvas to the whole canvas given a boundaries object
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| var scaleCanvas = function(canvas, bb){ | |
| var retina = window.devicePixelRatio; | |
| var width = canvas.width; | |
| var height = canvas.height; | |
| var newWidth = bb.xMax - bb.xMin; | |
| var newHeight = bb.yMax - bb.yMin; | |
| var aspectCanvas = width/height; | |
| var aspectBB = newWidth/newHeight; | |
| var offsetX = 0; | |
| var offsetY = 0; | |
| var scale = 1; | |
| var tempCanvas = document.createElement('canvas'); | |
| tempCanvas.width = newWidth; | |
| tempCanvas.height = newHeight; | |
| tempCanvas.getContext('2d').drawImage(canvas, bb.xMin, bb.yMin, newWidth, newHeight, 0,0,newWidth, newHeight); | |
| canvas.getContext('2d').clearRect(0,0,width, height); | |
| if (aspectBB > aspectCanvas){ | |
| //el conteniddo es más horizontal que el canvas | |
| scale = width/newWidth; | |
| offsetY = (height-newHeight*scale)/2; | |
| height = newHeight * scale; | |
| }else{ | |
| scale = height/newHeight; | |
| offsetX = (width-newWidth*scale)/2; | |
| width = newWidth * scale; | |
| } | |
| canvas.getContext('2d').drawImage(tempCanvas, offsetX/retina,offsetY/retina,width/retina, height/retina); | |
| delete(tempCanvas); | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment