Last active
November 26, 2019 18:51
-
-
Save Mamboleoo/770c689a73d7f158492f0105109f1aad to your computer and use it in GitHub Desktop.
Canvas Setup [2D-3D]
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
// Get the canvas element from the DOM | |
const canvas = document.getElementById('scene'); | |
// Get the canvas dimensions | |
let width = canvas.offsetWidth; // Width of the scene | |
let height = canvas.offsetHeight; // Height of the scene | |
// Store the 2D context | |
const ctx = canvas.getContext('2d'); | |
// Function called right after user resized its screen | |
function onResize () { | |
// We need to define the dimensions of the canvas to our canvas element | |
// Javascript doesn't know the computed dimensions from CSS so we need to do it manually | |
width = canvas.offsetWidth; | |
height = canvas.offsetHeight; | |
// If the screen device has a pixel ratio over 1 | |
// We render the canvas twice bigger to make it sharper (e.g. Retina iPhone) | |
if (window.devicePixelRatio > 1) { | |
canvas.width = canvas.clientWidth * 2; | |
canvas.height = canvas.clientHeight * 2; | |
ctx.scale(2, 2); | |
} else { | |
canvas.width = width; | |
canvas.height = height; | |
} | |
} | |
// Listen to resize events | |
window.addEventListener('resize', onResize); | |
// Make sure the canvas size is perfect | |
onResize(); |
@mracette There is no reason in this case and I should have used client
twice.
clientWidth
is the inner width (ie. the space inside an element including padding but excluding borders and scrollbars)
offsetWidth
is the outer width (ie. the space occupied by the element, including padding and borders)
When working with canvas, padding & border should not be taken into account when getting the canvas size :)
@Mamboleoo Sweet, thanks for the helpful reply. Just wanted to make sure there wasn't something I was missing!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
any reason for using offset (15-16) instead of client (21-22)?