Windows 8 Javascript set Canvas to fill screen - javascript

I'm trying to create a HTML5 canvas using Windows 8 / WinJS. Here's what I have:
var body = document.getElementById("body");
var canvas = document.createElement("canvas");
canvas.id = "myCanvas";
body.appendChild(canvas);
var canvasContext = canvas.getContext("2d");
canvas.width = document.width;
canvas.height = document.height;
canvasContext.fillStyle = "#f00";
canvasContext.fillRect(canvas.width - 100, canvas.height - 50, 100, 50);
console.log("canvas width " + canvas.width + ", height " + canvas.height);
Most of this is directly from a tutorial, but for all the tutorials I've seen, the width and height are set to hard coded numbers, for example:
canvas.width = 800;
canvas.height = 600;
Admittedly that does work, but I want the canvas to be as big as the screen, whatever the resolution. How do I achieve this?

You can just use the viewport with and viewport height CSS values to do this (see some information on these here)
In this specific case you could just do:
canvas.style.width = "100vw";
canvas.style.height = "100vh";
The advantage of this solution is that you don't have to load 3rd party libraries, e.g. JQuery to size to the full width / height.

By "screen", do you mean the browser window size?
If so, you can use window.outerWidth and window.outerHeight instead of document.width and document.height. Or if you use jQuery: $(window).width() and $(window).height().
Also, you want to listen to the resize event on the window so that you can reinitialize the canvas when the browser is resized.

Related

Canvas - resize image and save to a variable

So, I have a browser game which is run by a canvas with dynamic dimensions(it scales to the user's window's dimensions) which takes images at various sizes, scales them according to the user's window dimensions and draws them:
(example of my resizing algo:)
https://jsfiddle.net/8o3sn9mh/55/
var
canvas = document.getElementById('c'),
ctx = canvas.getContext('2d');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
var flower = new Image();
//the src is actually local, but i put a url for example's sake
flower.src = "http://plainicon.com/dboard/userprod/2803_dd580/prod_thumb/plainicon.com-46129-128px-af2.png"
flower.onload = function(){
ctx.drawImage(flower,0,0,128,128, 0, 0, window.innerWidth / 2, window.innerHeight / 2);
}
as you can see, I am drawing a 128x128px image and I resize it to half's the user's window. So, I was thinking - my game may do this operation every single render execution, and it may take unnecessary resizing time to perform it every time. So:
1) Does performing this resizing take more time since I use it every requestAnimationFrame?
2) Is there a way to resize my image one time, save it into a var and use it in order to save that time?
Regardless I'd like a way to save the resized image into a var in order to fit it inside canvas' createPattern method:
pattern = ctx.createPattern(resizedFlower, 'repeat'); //resizedFlower should be the original flower resized into half's the user's window's width + height
ctx.fillStyle = pattern;
ctx.fillRect(0, 0, 50, 50);
You can save your image to a canvas and then use drawImage with that canvas. For instance:
var canvas = document.getElementById('c'),
ctx = canvas.getContext('2d');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
var flowerCanvas = document.createElement('canvas');
flowerCanvas.width = window.innerWidth;
flowerCanvas.height = window.innerHeight;
flowerCtx = flowerCanvas.getContext('2d');
var flower = new Image();
//the src is actually local, but i put a url for example's sake
flower.src = "http://plainicon.com/dboard/userprod/2803_dd580/prod_thumb/plainicon.com-46129-128px-af2.png"
flower.onload = function(){
flowerCtx.drawImage(flower,0,0,128,128, 0, 0, window.innerWidth / 2, window.innerHeight / 2);
ctx.drawImage(flowerCanvas,0,0);
}
Now you can reuse flowerCanvas and it will be whatever size you initially drew it at. You probably won't see much of a performance gain between resizing vs not resizing, although you should benchmark it to be sure.
Also you shouldn't resize everything everyframe, you can listen for a window resize event, and resize when that event fires.

How to get original image from webcam in js?

How can I get the webcam video on the left to be in the same format as the right where the image is drawn?
Had this problem for a while and can't figure it out!
here's the code:
document.getElementById('capture').addEventListener('click', function() {
var w = video.videoWidth;
var h = video.videoHeight;
canvas.width = w;
canvas.height = h;
context.drawImage(video,0,0,w,h);
canvas.style.display='block';
});
You are using the size of your video html element instead of the size of the stream. That's why the photo is stretched. You should use the size of the video track.
If you specified it while calling MediaDevices.getUserMedia use those values.
Otherwise retrieve them from the video track (MediaStreamTrack.getSettings())
video.videoWidth is not the real width of video so you get different ratio on new canvas. Try this:
var videoRatio = video.videoWidth / video.videoHeight;
var width = video.offsetWidth, height = video.offsetHeight;
var elementRatio = width/height;
if(elementRatio > videoRatio) width = height * videoRatio;
else height = width / videoRatio;
canvas.width = width;
canvas.height = height;
context.drawImage(video,0,0,width,height);
canvas.style.display='block';

HTML5 canvas, fit to (rest of) screen

I've made a little web game, I'm using this code below to scale the game to the page size.
var canvas = document.getElementById("game");
var ctx = canvas.getContext("2d");
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
document.body.appendChild(canvas);
// Attempt at auto-resize
function resize_canvas(){
if (canvas.width != window.innerWidth)
{
canvas.width = window.innerWidth;
}
if (canvas.height != window.innerHeight)
{
canvas.height = window.innerHeight;
}
}
window.addEventListener("resize", resize_canvas);
window.addEventListener("orientationchange", resize_canvas);
However, I'm now adding a menu in the top of the game using some CSS and I'm running into problems.
The game takes the size of the inner window, so anything displayed along with the game will cause the content not to fit into the browser.
How can I make the game "fill" the rest of the window?
(I've found questions on how to scale the game to the window, but I'd like the game to fill the window instead)
An image to demonstrate the problem below:
(Notice the scrollbars, which I'd like to eliminate)
Edit:
I'm quite new to web development, but I have the feeling CSS doesn't really work well on canvas.
And if you remove the nav height ?
var canvas = document.getElementById("game");
var ctx = canvas.getContext("2d");
var menu = document.getElementById('nav')
resize_canvas();
document.body.appendChild(canvas);
// Attempt at auto-resize
function resize_canvas(){
canvas.width = window.innerWidth;
canvas.height = window.innerHeight - menu.offsetHeight;
}
window.addEventListener("resize", resize_canvas);
window.addEventListener("orientationchange", resize_canvas);
and
canvas {
position:relative;
}

If I resize my canvas, my createJS text becames blurry

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
} */
}

event.point not resizing with paper.js

This will drag my rectangle path. It works perfectly if the window hasn't resized.
function onMouseDrag(event) {
MyRectanglePath.position = event.point;
}
This will resize my game to be a square at either 100% width or 100% length of the browser window.
function OnResizeCalled() {
var gameWidth = window.innerWidth;
var gameHeight = window.innerHeight;
var scaleToFitX = gameWidth / 640;
var scaleToFitY = gameHeight / 640;
var currentScreenRatio = gameWidth / gameHeight;
var optimalRatio = Math.min(scaleToFitX, scaleToFitY);
canvas.style.width = 640 * optimalRatio + "px";
canvas.style.height = 640 * optimalRatio + "px";
}
// Resize
window.addEventListener("resize", OnResizeCalled, false);
OnResizeCalled();
The smaller my browser window gets, the farther the rectangle is from my mouse when I drag it. How do I make event.point scale with the rest of the canvas?
Paper.js is not designed to support manual resizing of the canvas, since that will blow up the pixels and cause all kind of internal issues. It will also interfere with HiDPI handling on Retina screens.
but you can resize the canvas using:
paper.view.viewSize = [width, height];
I hope this helps!
Umm as Mr. Jürg Lehni stated before, Paper.js is not designed to support manual resizing of the canvas. when paper.view.setViewSize() extends/ shrink the canvas to that size.
If you want to scale the things inside the canvas (e.g. path), you had to apply transformation to every item (with right Matrix) using .transform();

Categories

Resources