I'm working on a small project in Javascript, using Pixi.js as the rendering engine. However, I've only found a few methods of scaling the canvas to full window that seem to work best for the current version. It does have a caveat, however, in that it produces letterboxes on the sides based on the orientation.
Is it possible to avoid the letterboxing at all with Pixi?
This is the code that I have so far, as it relates to the scaling:
var application = null;
var GAME_WIDTH = 1060;
var GAME_HEIGHT = 840;
var ratio = 0;
var stage = null;
application = new PIXI.Application(
{
width: GAME_WIDTH,
height: GAME_HEIGHT,
backgroundColor: 0x00b4f7,
view: document.getElementById("gwin")
});
stage = new PIXI.Container(true);
window.addEventListener("resize", rescaleClient);
function rescaleClient()
{
ratio = Math.min(window.innerWidth / GAME_WIDTH, window.innerHeight /
GAME_HEIGHT);
stage.scale.x = stage.scale.y = ratio;
application.renderer.resize(Math.ceil(GAME_WIDTH * ratio), Math.ceil(GAME_HEIGHT * ratio));
}
My goal with this is to achieve a similar full screen/window effect to Agar.io/Slither.io, however I have not discovered a satisfactory method that allows it easily. There do seem to be examples that use Pixi to achieve this, but the code is more then often closed source, and they seem to use external tools such as Ionic and Phonegap.
I finally found the answer. I was close to the right track, but a few more things needed to be applied.
application.renderer.view.style.position = "absolute";
application.renderer.view.style.display = "block";
application.renderer.autoResize = true;
application.renderer.resize(window.innerWidth, window.innerHeight);
This sets some additional things internally, while a minor modification to the resize script...
ratio = Math.min(window.innerWidth / GAME_WIDTH, window.innerHeight / GAME_HEIGHT);
stage.scale.x = stage.scale.y = ratio;
renderer.resize(window.innerWidth, window.innerHeight);
configures things correctly, so that the related Renderer window now fills the screen without squashing the content.
This was not easy to discover. So many tutorials just leave it at the first half, and assume that is what people wish to do.
var application;
//var GAME_WIDTH = window.screen.width-20;
var GAME_WIDTH = window.innerWidth;
//var GAME_WIDTH = document.body.clientWidth;
var GAME_HEIGHT = window.innerHeight;
var ratiox = 0;
var ratioy = 0;
var container;
application = new PIXI.Application(
{
width: GAME_WIDTH,
height: GAME_HEIGHT,
backgroundColor: 0x00b4f7,
view: document.getElementById("gwin")
});
//document.body.appendChild(application.view);
container = new PIXI.Container(true);
application.stage.addChild(container);
window.addEventListener("resize", rescaleClient);
function rescaleClient()
{
//ratiox = Math.min(window.innerWidth / GAME_WIDTH, window.innerHeight / GAME_HEIGHT);
application.stage.scale.x = ratiox = window.innerWidth / GAME_WIDTH
application.stage.scale.y = ratioy = window.innerHeight / GAME_HEIGHT;
application.renderer.resize(Math.ceil(GAME_WIDTH * ratiox), Math.ceil(GAME_HEIGHT * ratioy));
}
#viewport{
width:device-width
}
body {
padding :0px;
margin:0px
}
<script src="https://pixijs.download/v4.6.2/pixi.min.js"></script>
<canvas id="gwin"></canvas>
Related
I made horizontal scroll website with PIXI JS and it has a ripple effect.
it worked fine till now but the only issue is it's showing a very low quality when I open up the website and from what I figured out that PIXI JS renderer get width and height to 800 x 600 resolution.
any ideas how to change the quality ?
here's the PIXI JS code snippet:
// Set up the variables needed and loads the images to create the effect.
// Once the images are loaded the ‘setup’ function will be called.
const app = new PIXI.Application({
width: window.innerWidth,
height: window.innerHeight,
resolution: 1,
antialias : true
});
document.body.appendChild(app.view);
app.stage.interactive = true;
var posX, displacementSprite, displacementFilter, bg, vx;
var container = new PIXI.Container();
app.stage.addChild(container);
PIXI.loader.add("depth.png").add("polygonexample.jpg").load(setup);
// In the ‘setup’ function the displacement sprite is created
// that will create the effect and this is added to a displacement filter.
// It’s then set to move its anchor point to the centre of the image and positioned on the screen.
function setup() {
posX = app.renderer.width / 2;
displacementSprite = new PIXI.Sprite(PIXI.loader.resources["depth.png"].texture);
displacementFilter = new PIXI.filters.DisplacementFilter(displacementSprite);
displacementSprite.anchor.set(0.5);
displacementSprite.x = app.renderer.width / 2;
displacementSprite.y = app.renderer.height / 2;
vx = displacementSprite.x;
// To finish off the ‘setup’ function, the displacement filter scale is set and the background positioned.
// Notice the scale is ‘0’ for the displacement, that’s because it will be set to a height as soon as the mouse moves.
app.stage.addChild(displacementSprite);
container.filters = [displacementFilter];
displacementFilter.scale.x = 0;
displacementFilter.scale.y = 0;
bg = new PIXI.Sprite(PIXI.loader.resources["polygonexample.jpg"].texture);
bg.width = app.renderer.width;
bg.height = app.renderer.height;
container.addChild(bg);
app.stage.on('mousemove', onPointerMove).on('touchmove', onPointerMove);
loop();
}
// grab the position of the mouse on the x-axis whenever the mouse moves.
function onPointerMove(eventData) {
posX = eventData.data.global.x;
}
// create a function that continually updates the screen. A velocity for the x-axis is worked out using the position of the mouse and the ripple.
function loop() {
requestAnimationFrame(loop);
vx += (posX - displacementSprite.x) * 0.045;
displacementSprite.x = vx;
var disp = Math.floor(posX - displacementSprite.x);
if (disp < 0) disp = -disp;
var fs = map(disp, 0, 500, 0, 120);
disp = map(disp, 0, 500, 0.1, 0.6);
displacementSprite.scale.x = disp;
displacementFilter.scale.x = fs;
}
// Finally, the map function is declared that maps value ranges to new values.
map = function(n, start1, stop1, start2, stop2) {
var newval = (n - start1) / (stop1 - start1) * (stop2 - start2) + start2;
return newval;
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/pixi.js/5.3.7/pixi.min.js"></script>
Try creating renderer using this code
const app = new PIXI.Application({
width: window.innerWidth,
height: window.innerHeight,
resolution: 1,
});
But if you resize window after creating renderer, it won't be automatically resized to window size. To solve that you can listen to resize event
EDIT: Removing margins also might help.
body {
margin: 0;
padding: 0;
overflow: hidden;
}
canvas {
display: block;
}
just found the answer and it was very silly thing actually.
the issue was with the width and the height they were set to window.innerWidth and window.innerHeight. my image quality was quite high so basically multiplying the width and the height inside PIXI.Application by 3 or 4 increases the qualit.
const app = new PIXI.Application({
width: window.innerWidth*3,
height: window.innerHeight*3,
resolution: 1,
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/pixi.js/5.3.7/pixi.min.js"></script>
i was testing some code with javascript, about resizing the html5 canvas. i've asked similar question before, when i was testing the same thing with jquery. and i've got the desired solution that time, reference (eg_1). in this (eg_1), the result was, canvas element was resizing in every frame because of requestAnimationFrame($.fn.animate); is taking place in a recursive form.the visual result for that is here the width attribute updates when i resize the console window. and if i close the console the canvas resizes automatically, i don't need to reload the window, to update the attribute values. means canvas is full screen, all time. but i am having problem with the same thing, in javascript. if i close the console, the width of the console cuts (or resizes) the canvas with a white space. here is the visual result the white space is my problem. i've to reload the window, to make the canvas full screen again. in short i'm not having the same effect as (eg_1). here i tried so far, reference (eg_2).
(eg_1)
html : <canvas></canvas>
css :
* {
margin: 0;
padding: 0;
overflow: hidden;
}
canvas {
background-color: turquoise;
}
jquery :
$(document).ready(function() {
var view = $(window),
canvas = $("canvas"),
ctx = canvas[0].getContext("2d"),
width = view.width(),
height = view.height();
$.fn.windowResize = function() {
var width = view.width();
height = view.height();
canvas.attr("width", width);
canvas.attr("height", height);
};
view.on("resize", $.fn.windowResize);
canvas.attr("width", width);
canvas.attr("height", height);
$.fn.animate = function() {
requestAnimationFrame($.fn.animate);
ctx.clearRect(0, 0, width, height);
// start here
};
$.fn.animate();
});
(eg_2)
var canvas = document.querySelectorAll("canvas")[0];
var context = canvas.getContext("2d");
var windowWidth = window.innerWidth;
var windowHeight = window.innerHeight;
function resize() {
setInterval(resize, 5);
clearInterval(resize);
canvas.width = windowWidth;
canvas.height = windowHeight;
}
resize();
Answer:
Your initial issue:
You need to get the updated values of window.innerWidth and window.innerHeight.
To do this you can turn the variables into functions that request the current values.
Example:
var canvas = document.querySelectorAll("canvas")[0];
var context = canvas.getContext("2d");
var windowWidth = () => window.innerWidth;
var windowHeight = () => window.innerHeight;
function resize() {
setInterval(resize, 5);
clearInterval(resize);
canvas.width = windowWidth();
canvas.height = windowHeight();
}
resize();
* {
margin: 0;
padding: 0;
overflow: hidden;
}
canvas {
background-color: turquoise;
}
<canvas></canvas>
Other issues:
Your use of Timers is incorrect. clearInterval(resize) isn't going to clear anything, because resize is not a timer itself.
Secondly you shouldn't be using any timers when rendering to Canvas. It can often lead to things like the above( multiple timers ) or issues with constant, unnecessary, re-processing.
Instead of resizing perpetually you may want to just do so when the resize event is dispatched. Even if you were using requestAnimationFrame - which would effectively stop the render if anything else takes precedence or if you switch tabs, it's an unnecessary process in that you're constantly re-rendering the same thing without cause. Canvas Apps tend to get big real quick when you add in multiple rendering functions, so you'll want to mitigate unnecessary steps.
You can do this by attaching to appropriate events and creating requestAnimationFrame helpers like in the following example:
var canvas = document.querySelectorAll("canvas")[0];
var context = canvas.getContext("2d");
var windowWidth = () => window.innerWidth;
var windowHeight = () => window.innerHeight;
var request = fn => requestAnimationFrame(fn),
requestHandler = fn => () => request(fn);
function resize() {
canvas.width = windowWidth();
canvas.height = windowHeight();
}
request(resize);
window.addEventListener("resize", requestHandler(resize) );
* {
margin: 0;
padding: 0;
overflow: hidden;
}
canvas {
background-color: turquoise;
}
<canvas></canvas>
I'm trying to resize the camera display within the canvas DOM element. I've tried using an event listener and am able to resize the canvas without any problem. The camera's video feed however is not updating its size, t stays the same as it was upon initialization. In order to make it work I've had to basically destroy much of the composition and then re-initialize the whole thing every time a window resize occurs. It works but its ugly. Does anyone have a better solution in mind? Maybe there is a way to make this one more elegant? Thanks for any input.
window.addEventListener( 'resize', onWindowResize, false );
function onWindowResize() {
// seriously
reformat = null
source = null
target.destroy()
target = null
seriously = new Seriously();
canvas.width = window.innerWidth * devicePixelRatio;
canvas.height = window.innerHeight * devicePixelRatio;
var source = seriously.source('camera');
target = seriously.target('#canvas');
reformat = seriously.transform('reformat');
reformat.source = source;
reformat.width = canvas.width;
reformat.height = canvas.height;
target.source = reformat
seriously.go(function(now) {
var minutes;
minutes = now / 6000;
console.log("running")
// split.angle = (minutes - Math.floor(minutes)) * PI2;
// split.split = Math.cos(now / 1000) / 2 + 0.5;
});
After iterating through each of the Seriously examples I found a simple solution.
var devicePixelRatio = window.devicePixelRatio || 1;
function resize() {
target.width = window.innerWidth * devicePixelRatio;
target.height = window.innerHeight * devicePixelRatio;
reformat.width = target.width;
reformat.height = target.height;
}
window.onresize = resize;
I am writing a small game in Javascript using the Phaser.js engine as a backend. However, knowing it is possible, the screen scaling issue has proven to be one
of the hardest sides of this.
Slither.io expands to fill the entire screen, and keeps the ratio. I want to use that as my own scaling method as well, but examples seem to be rather sparse.
The ones I have come across have not been all that clear.
These two functions are what I have come up with thus far, but they seem to cause the sprites to match the window scale - not keep a ratio and scale.
function resizeWindow()
{
game.scale.scaleMode = Phaser.ScaleManager.SHOW_ALL;
game.width = window.innerWidth * window.devicePixelRatio;
game.height = window.innerHeight * window.devicePixelRatioz;
gameScale = game.width / game.height;
if (game.height > game.width){
gameScale = (game.height / 300);
} else {
gameScale = (game.width / 480);
}
//game.scale.pageAlignVertically = true;
game.scale.pageAlignHorizontally = true;
game.scale.refresh();
gameScaleManager();
}
function gameScaleManager()
{
for(var i = 0; i < spriteList.length; i++)
{
spriteList[i].scale.setTo(gameScale, gameScale);
}
}
I finally solved it by way of a number of things
First, set your game scale mode to:
game.scale.scaleMode = Phaser.ScaleManager.RESIZE;
and then apply
game.scale.pageAlignVertically = true;
This does matter, especially for full window size.
Instead of relying on jQuery for rescaling, I then set this:
game.scale.setResizeCallback(rescale);
The rescale method handles screen scaling.
Finally, this method takes care of the actual work along with the "RESIZE" scale mode, which WILL affect -how- it works. EXACT_FIT and others tend to force the resolution to be the same as the window, from the experimentation I've done.
function rescale()
{
var windowHeight = window.innerHeight;
var windowWidth = window.innerWidth;
baseWidth = windowWidth * (gameHeight / windowHeight);
baseHeight = gameHeight;
if (windowHeight > windowWidth)
{
systemScale = (windowHeight / baseHeight) / 1.8;
} else {
systemScale = (windowWidth / baseWidth) / 1.8;
}
skyBackgroundGroup.scale.setTo(systemScale * (window.innerWidth - DPR / window.innerWidth - DPR) / 100 * 1, systemScale * 2.1);
MasterControlGroup.scale.setTo(systemScale / 0.98, systemScale / 0.98);
}
The divide by scale of 1.8 and 0.98 are entirely personal preferences.
I almost forgot the biggest part of it - have your camera focus on the center object you are watching.
I'm using createJS to drawn inside the canvas. I have my canvas set to occupy the browser window maintaining aspect ratio using the resize() function.
This is the code:
mytext = new createjs.Text("Lorem ipsum dolor sit amet 2","19px Calibri","#073949");
mytext.x = 450
mytext.y = 300;
stage.addChild(mytext);
resize = function() {
var canvas = document.getElementById('canvas');
var canvasRatio = canvas.height / canvas.width;
var windowRatio = window.innerHeight / window.innerWidth;
var width;
var height;
if (windowRatio < canvasRatio) {
height = window.innerHeight - 35;
width = height / canvasRatio;
} else {
width = window.innerWidth;
height = width * canvasRatio;
}
canvas.style.width = width + 'px';
canvas.style.height = height + 'px';
}()
What happens is that the text gets blurry (decrease of quality) when the canvas resizes.
http://i.imgur.com/RQOSajs.png
vs
http://i.imgur.com/Xwhf5c5.png
How can I solve this issue?
Since you are using CreateJS, you can simply resize the canvas, and scale the entire stage to redraw everything at the new size:
// just showing width to simplify the example:
var newWidth = 800;
var scale = newWidth/myCanvas.width;
myCanvas.width = newWidth;
myStage.scaleX = myStage.scaleY = scale;
myStage.update(); // draw at the new size.
#Adam's answer is correct as far as scaling the canvas goes. You do NOT want to scale with CSS, as it will stretch your canvas instead of changing its pixel dimensions. Set the width and height of the canvas using JavaScript instead.
stage.canvas.width = window.innerWidth;
stage.canvas.height = window.innerHeight;
As you stated in your comment, this will only change the canvas size, and not reposition or scale your content. You will have to do this manually. This is fairly simple. Generally, I recommend putting your "resize" listener in the JavaScript in your HTML file, rather than on a frame script.
First, determine the scale, based on the size of the window and the size of your content. You can use the exportRoot.nominalBounds.width and exportRoot.nominalBounds.height which is the bounds of the first frame. If you want to scale something else, use its nominalBounds instead.
Note that nominalBounds is appended to all MovieClips exported from Flash/Animate. If you enable multi-frame bounds, and want to use those, you will have to modify your approach.
The main idea is to use the original, unscaled size of your contents.
var bounds = exportRoot.nominalBounds;
// Uses the larger of the width or height. This will "fill" the viewport.
// Change to Math.min to "fit" instead.
var scale = Math.max(window.innerWidth / bounds.width, window.innerHeight / bounds.height);
exportRoot.scaleX = exportRoot.scaleY = scale;
You can then center it if you want.
exportRoot.x = *window.innerWidth - bounds.width*scale)/2;
exportRoot.y = *window.innerHeight - bounds.height*scale)/2;
Here is a quick sample of a responsive canvas using a simple shape as the scaling contents:
http://jsfiddle.net/lannymcnie/4yy08pax/
Doing this with Flash/Animate CC export has come up a few times, so it is on my list of future EaselJS demos to include on createjs.com, and in the EaselJS GitHub.
I hope this helps.
Take a look at my jsfiddle : https://jsfiddle.net/CanvasCode/ecr7o551/1/
Basically you just store the original canvas size and then use that to work out new positions and sizes
html
<canvas id="canvas" width="400" height="400">
Canvas was unable to start up.
</canvas>
<button onclick="resize()">Click me</button>
javascript
var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');
var originalWidth = canvas.width;
var originalHeight = canvas.height;
render = function()
{
context.fillStyle = "#DDD";
context.fillRect(0,0, originalWidth * (canvas.width / originalWidth), originalHeight * (canvas.height / originalHeight));
context.fillStyle = "#000";
var fontSize = 48 * (canvas.width / originalWidth);
context.font = fontSize+"px serif";
context.fillText("Hello world", 100 * (canvas.width / originalWidth), 200 * (canvas.height / originalHeight));
}
resize = function()
{
canvas.width = 800;
canvas.height = 600;
render();
}
render();
The HTML5 canvas element works with two different sizes
Visual size on screen, controlled via CSS, like you're setting with canvas.style.width/height
Size of pixel buffer for the drawing, controlled via numeric width and height pixel attributes on the canvas element.
The browser will stretch the buffer to fit the size on screen, so if the two values are not 1:1 ratio text will look blurry.
Try adding the following lines to your code
canvas.width = width;
canvas.height = height;
I created a function to resize all the elements on the screen after resizing the canvas. It saves the initial coordinates and scales for the elements with the original width of 900 px and then it changes them according to the current width ratio relative to the original width ratio. The text isn't blurry/bad quality anymore.
resize = function() {
var canvas = document.getElementById('canvas');
var canvasRatio = canvas.height / canvas.width;
var windowRatio = window.innerHeight / window.innerWidth;
var width;
var height;
if (windowRatio < canvasRatio) {
height = window.innerHeight;
width = height / canvasRatio;
} else {
width = window.innerWidth;
height = width * canvasRatio;
}
canvas.width = width;
canvas.height = height;
reziseElements();
};
reziseElements = function()
{
var canvrat = canvas.width / 900;
//Simplified
stage.scaleX = stage.scaleY = canvrat;
//Old Version
/*for (i=0; i<stage.numChildren ;i++)
{
currentChild = stage.getChildAt(i);
if (typeof currentChild.oscaleX == 'undefined')
{
currentChild.oscaleX = currentChild.scaleX;
currentChild.ox = currentChild.x;
currentChild.oy = currentChild.y;
}
}
for (i=0; i<stage.numChildren ;i++)
{
currentChild = stage.getChildAt(i);
currentChild.scaleX = currentChild.scaleY = currentChild.oscaleX * canvrat
currentChild.x = currentChild.ox * canvrat
currentChild.y = currentChild.oy * canvrat
} */
}