Skip to content

Instantly share code, notes, and snippets.

@okunokentaro
Last active December 6, 2018 10:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save okunokentaro/b0152b019f2a7a490b3f357e3e4a666c to your computer and use it in GitHub Desktop.
Save okunokentaro/b0152b019f2a7a490b3f357e3e4a666c to your computer and use it in GitHub Desktop.
const prepareRetina = (el, dpr) => {
el.width *= dpr;
el.height *= dpr;
el.style.width = `${el.width / dpr}px`;
el.style.height = `${el.height / dpr}px`;
};
const render = () => {
const canvasEl = document.querySelector('canvas');
const dpr = window.devicePixelRatio;
prepareRetina(canvasEl, dpr);
canvasEl.width *= dpr;
canvasEl.height *= dpr;
canvasEl.style.width = `${canvasEl.width / dpr}px`;
canvasEl.style.height = `${canvasEl.height / dpr}px`;
const context = canvasEl.getContext('2d');
const [w, h] = [200, 200];
const borderWidth = 1;
const [nw, nh] = [w, h].map(v => v * dpr);
const nBorderWidth = borderWidth * dpr;
context.fillRect(0, 0, nw, nh);
context.clearRect(
nBorderWidth,
nBorderWidth,
nw - nBorderWidth * 2,
nh - nBorderWidth * 2
);
context.fillStyle = 'green';
context.fillRect(0 * dpr, 0 * dpr, 10 * dpr, 10 * dpr);
context.fillRect(40 * dpr, 40 * dpr, 10 * dpr, 10 * dpr);
};
render();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment