How to make a responsive character using HTML5 Canvas and JS - javascript

I have created a character using HTML5 Canvas and Javascript, following this tutorial: http://www.williammalone.com/articles/create-html5-canvas-javascript-game-character/1/
Although, I am now struggling to make the character responsive, I have tried this:
function resize(){
$("#canvasDiv").outerHeight($(window).height()-$("#canvasDiv").offset().top- Math.abs($("#canvasDiv").outerHeight(true) - $("#canvasDiv").outerHeight()));
}
$(document).ready(function(){
var myWidth = $(window).width()-$("#canvasDiv").offset().top- Math.abs($("#canvasDiv").outerWidth(true) - $("#canvasDiv").outerWidth());
var myHeight = $(window).height()-$("#canvasDiv").offset().top- Math.abs($("#canvasDiv").outerHeight(true) - $("#canvasDiv").outerHeight());
prepareCanvas(document.getElementById("canvasDiv"), myWidth, myHeight);
$(window).on("resize", function(){
var newWidth = $(window).width()-$("#canvasDiv").offset().top- Math.abs($("#canvasDiv").outerWidth(true) - $("#canvasDiv").outerWidth());
var newHeight = $(window).height()-$("#canvasDiv").offset().top- Math.abs($("#canvasDiv").outerHeight(true) - $("#canvasDiv").outerHeight());
$( "#canvasDiv" ).empty();
prepareCanvas(document.getElementById("canvasDiv"), newWidth, newHeight);
});
});
But this just seems to cut the image instead of resizing it.
Here is a demo: https://jsfiddle.net/cjdygegh/

This is because you are just resizing the canvas, the images inside are staying the same size and therefore go outside the bounds of the canvas. You need to use the scale function to scale the scene on the canvas by the current width and height divided by the desired width and height:
context.scale(x, y); // Where x and y are ratios (1 being 100%).
Things to consider:
If you want the aspect ratio to be kept? If so you will need to use the minimum ratio of width or height.
If you want to scale up, above 100%.

Related

Resizing window to maintain aspect ratio

I have an interesting problem for a little program I have been developing.
Basically what I wish to create is a window which I can resize but still maintain a 16:9 aspect ratio (note this is for a native application using NWJS). I am also using the easelJS libraries to manipulate the canvas.
The program below basically resizes the canvas to be the same size as the window and does it's job perfectly. But I've been stuck trying to figure out exactly how to maintain the aspect ratio of the window itself.
var stage, w, h;
window.addEventListener('resize', resizeCanvas);
function resizeCanvas() {
w = window.innerWidth;
h = window.innerHeight;
stage.canvas.width = w;
stage.canvas.height = h;
Exactly what sort of calculations do I need to do to force this setting? I'm not as knowledgeable when it comes to things such as aspect ratios.
You should base your calculation on one axis only, and get the new height and width from it.
For a 16/9 ratio
w = window.innerWidth;
h = 9*window.innerWidth/16;

HTML Canvas Not Displaying Correctly When Resized to Fit Parent Div with 'offsetWidth'

I'm working on a sketchpad application using html canvas and javascript (trying to stay away from jQuery). The canvas needs to be responsive and I've found several methods to do so, but each one stretches out the canvas and makes the sketchpad unusable. It's hard to explain without seeing the problem. Here's the CodePen. Try drawing inside the canvas and you'll see what I'm talking about. The current method I'm using to resize the canvas incorporates offsetWidth and offsetHeight like so:
var sketchpadContainer = [
document.getElementById('container').offsetWidth,
document.getElementById('container').offsetHeight]
var canvas = document.getElementById('sketchpad');
canvas.style.height = sketchpadContainer[1] + "px";
canvas.style.width = sketchpadContainer[0] + "px";
Is there a way to make the canvas responsive while at the same time keeping the dimensions of the sketch intact?
The CSS width and height properties are NOT the same as the width and height attributes on a Canvas element.
If you absolutely need to use css to set width/height, keep a scale factor of your default canvas size, then multiple the target x and y positions of your mouse position by the inverse of the x/y scale factors (or just divide the target position by them).
Using css to resize your canvas is a bit too hacky imo (and will leave your lines blurry), I highly recommend you instead simlpy change with width/height attributes of your canvas and use CanvasRenderingContext2D.scale() to change the size of your lines (A scale factor will still need to be used to calculate your true mouse pos, however)
Simply change
canvas.style.height = sketchpadContainer[1] + "px";
canvas.style.width = sketchpadContainer[0] + "px";
to
canvas.height = sketchpadContainer[1];
canvas.width = sketchpadContainer[0];
Apply CanvasRenderingContext2D.scale() when you first get your context, and then do as I mentioned above. (ctx.lineTo(x,y); -> ctx.lineTo(x/scaleFactorX,y/scaleFactorY); & lastX=x; -> lastX=x/scaleFactorX;)
I.E See HERE

Make canvas responsive only when resizing window and not when zooming

I have a 960px width and 960px height html5 canvas game. I use Javascript to resize the canvas and rescale its content proportionally to always fit the window vertically (and horizontally too) so the bottom is never cut off since many screens are less than 960px high and some users don't even know they can zoom out with a desktop browser to fit the content. The code is:
var w = stage.canvas.width;
var h = stage.canvas.height;
var scaleFactor;
window.addEventListener('resize', resizeCanvas, false);
function resizeCanvas() {
scaleFactor = Math.min(window.innerWidth / w, window.innerHeight / h);
stage.canvas.width = scaleFactor * w;
stage.canvas.height = scaleFactor * h;
stage.scaleY = scaleFactor;
stage.scaleX = scaleFactor;
}
My problem is the game also resizes itself when I zoom either in a desktop or in a mobile browser since zooming also changes window.innerWidth and window.innerHeight values. HOWEVER, I want the game to only resize itself when the window is resized but still be able to be zoomed (especially in small mobile screens) for people whose eyes are not so perfect.
I've been searching and trying different methods for weeks now, but I still haven't found any solutions. I would be very happy if someone could come up with a not-so-complicated solution since I'm relatively a beginner.
When zooming in and out, the devicePixelRatio value does change.
So you can save this value at init and check if it has changed in the resize event to determine if the event was triggered by an actual resizing of the window, or by zooming.
let dpr = window.devicePixelRatio;
onresize = e => {
if(window.devicePixelRatio !== dpr){
log.textContent = 'zoom event';
dpr = window.devicePixelRatio
}
else{
log.textContent = 'resize event';
}
};
<pre id="log">Please see in full-page.
Then, either zoom or resize the window</pre>
Or as a fiddle.

How to scale my canvas in reason, with the zoom scale?

I am working on a multiple web game using JavaScript. My canvas is currently set to the width and the height of my screen.
html
<canvas id = "canvas"></canvas>
javascript
var c=document.getElementById("canvas");
var ctx = c.getContext("2d");
//Making canvas scale;
c.width = window.innerWidth;
c.height = window.innerHeight;
function resize(){
//Add some code
}
My problem is, I do not want my players to zoom out, well not by default. It will make the game look bad and give the players an edge over everyone else. So I need to add some code to go into the resize method, that regardless of scale, the canvas will not be zoomed out. If the end result is something blurry at 300%+ that is fine.
IMPORTANT: the resize function cannot remove or reset the canvas back to default.
There are various ways to scale a canvas.
First off, there are 2 main parameters for the canvas size:
-Canvas Pixel Count. Set via canvas.width = 1000
-Canvas Display Pixel Size. Set via canvas.style.width = '1000px'
If you want all players to see a 1000x1000 region but displaying it fullscreen:
canvas.width = 1000;
canvas.height = 1000;
canvas.style.width = window.innerWidth + 'px';
canvas.style.height = window.innerHeight + 'px';
There is also another option with canvas.style.transform = 'scale(2,2)'.
This method is the closest thing to the browser zoom done via Ctrl+ or Ctrl-.
The big advantage of transform is that the scaling is applied to all DOM children elements. If your game is using HTML for its interface, then this is the way to go. (By applying the scaling on the div containing the canvas + HTML interface.

Resizing the canvas

I'm trying to design a web using flex-boxes in order to fit it to any kind of screen size. My main screen has a canvas, so... which is the best way to resize the canvas during the inizialitation?
I have tried these two ways. My first way was to use CSS and set a percentage for its size. For example, width=100% and height=100%. Despite the design worked, I found that there were a lot of issues when playing with the coords of my canvas. For example, when dragging an item, my mouse coords where amplified by ten times or so.
Despite I could manage that, I think it's not the best approach.
The second way was to set a fixed size when the onload and onresize events when they are fired. I was doing something like this:
window.initHeight = window.screen.height;
window.initWidth = window.screen.width;
/*The height of the navbar.*/
navbar.height = document.getElementById('navbar').offsetHeight;
canvas = document.getElementById('canvasStage');
canvas.width = window.initWidth;
canvas.height = window.initHeight - navbar.height;
canvas.setAttribute("width", canvas.width);
canvas.setAttribute("height", canvas.height);
The problem is that the height seems to be too big:
http://i.imgur.com/WI0jGH2.png
How could I fit the screen exactly through this way?
The third way, but I'll try to avoid it, is to set a fixed size and let the small screens to scroll on the page.
Thanks!
UPDATED:
This is my JSFiddle:
http://i.imgur.com/NRTykLv.png
window.screen.width and window.screen.height returns the width and height of the screen which includes all bars (evrything you see on your screen).So you have to use window.innerHeight and window.innerWidth in order to get the view port height and width
Replace
window.initHeight = window.screen.height;
window.initWidth = window.screen.width;
with
window.initHeight = window.innerHeight;
window.initWidth = window.innerWidth;

Categories

Resources