Resizing your canvas drawings properly using repaint
This post will be a short one attending a problem I briefly touched upon in my previous post on animation using canvas. We live in a "mobile first" world and need to pay attention to responsive designing.
Try as you might resizing your canvas using CSS you are in for a disappointing surprise. Especially if you are rendering text, it will look all chunky and broken. My solution to this problem is to calculate a factor value based on the window and canvas width. Using this value, I can multiply it with all xes and ys and lengths and widths and so on and keep the relative positions all these shapes have to each other.
Try as you might resizing your canvas using CSS you are in for a disappointing surprise. Especially if you are rendering text, it will look all chunky and broken. My solution to this problem is to calculate a factor value based on the window and canvas width. Using this value, I can multiply it with all xes and ys and lengths and widths and so on and keep the relative positions all these shapes have to each other.
var ic = window.innerWidth / (canvas.width * 1.2) > 1 ? 1 : window.innerWidth / (canvas.width * 1.2);
When adding objects I apply the factor to keep the relative positions.
var customShapes = []; // Figures - Balls customShapes.push({ x: ic * (canvas.width / 2 - 58), minRadius: 0, maxRadius: ic * (3), y: ic * (canvas.height / 4 - 152), borderThickness: ic * (11), borderColor: ringBlue, color: ringBlue, runAnimation: !0, speed: 2.4 }); customShapes.push({ x: ic * (canvas.width / 2 - 117), minRadius: 0, maxRadius: ic * (3), y: ic * (canvas.height / 4 - 102), borderThickness: ic * (3), borderColor: ringBlue, color: ringBlue, runAnimation: !0, speed: 3 }); customShapes.push({ x: ic * (canvas.width / 2 + 43), minRadius: 0, maxRadius: ic * (3), y: ic * (canvas.height / 4 - 150), borderThickness: ic * (7), borderColor: ringBlue, color: ringBlue, runAnimation: !0, speed: 1 }); ... ... ...Now, make sure to use the windows.resize event to kick off the rerendering of your canvas. The result is a world apart from the CSS approach.
Comments
Post a Comment