Getting canvas width trouble - javascript

Okay. So I have a canvas with an id of mainCanvas, with javascript and css on the same html page. I want to have it so that I can make things a certain width of the canvas, in javascript (Example, a red rectangle be the width and height of the canvas). So I have the canvas width set to 60% and the height set to 500px (the height isn't the problem) in css, and I have the code,
var canvas = document.getElementById("mainCanvas");
var context = document.getContext("2d");
var width = canvas.width;
var height = canvas.height;
which gets the canvas width and height. Then I have a setInterval() function with a game function that calls and update function, and a render function.
function game() {
update();
render();
}
function update() {
}
function render() {
context.fillStyle = "red";
context.fillRect(0, 0, width, height);
}
setInterval(function() {
game();
}, 1000/30);
So I have a rectangle that has the width variable as the width parameter, and the height variable as the height parameter.
Just so it is easier to see, here is a snippet.
<html>
<head>
<title></title>
<style type="text/css">
body {
background-color: #222222;
}
canvas {
background-color: #1f1f1f;
width: 60%;
height: 500px;
}
</style>
</head>
<body>
<canvas id="mainCanvas"></canvas>
<script type="text/javascript">
var canvas = document.getElementById("mainCanvas");
var context = document.getContext("2d");
var width = canvas.width;
var height = canvas.height;
function game() {
update();
render();
}
function update() {
}
function render() {
context.fillStyle = "red";
context.fillRect(0, 0, width, height);
}
setInterval(function() {
game();
}, 1000/30);
</script>
</body>
</html>
Why is the width and height not working? I have seen many questions on stackoverflow but those don't fix my problem.

Change the line:
var context = document.getContext("2d");
To:
var context = canvas.getContext("2d");

Change it to:
var canvas = document.getElementById("mainCanvas");
var context = canvas.getContext("2d"); // `canvas` instead of `document`
var width = canvas.width;
var height = canvas.height;

Related

Responsive full width canvas in sveltejs

I'm quite new to svelte and I'm trying to get a canvas to render on the full screen using svelte. Sounds quite easy to do, but I can't get it to work properly. I'm binding a width and height variable to the clientWidth/clientHeight of the parent and using these variables to set the dimensions of the canvas. The issue now is that when onMount is called, the width and height variables are set but they are not applied to the canvas element yet. This means when the canvas renders for the first time, it still has the initial dimensions and not the ones of the parent. Only when I render it a second time it has the proper dimensions. How can get the canvas to have the right dimensions on the first render or render the canvas again when it has the proper dimensions?
Here you can find a "working" version.
<script>
import { onMount } from "svelte";
let canvas;
let ctx;
let width = 1007;
let height = 1140;
const draw = () => {
ctx.clearRect(0, 0, width, height);
ctx.beginPath();
ctx.moveTo(width/2 - 50, height/2);
ctx.arc(width/2, height/2, 50, 0, 2 * Math.PI);
ctx.fill();
}
onMount(() => {
ctx = canvas.getContext("2d");
draw();
setTimeout(draw, 5000);
});
</script>
<style>
.container {
width: 100%;
height: 100%;
}
</style>
<div
class="container"
bind:clientWidth={width}
bind:clientHeight={height}>
<canvas bind:this={canvas} {width} {height} />
</div>
You can solve this by waiting for the next 'tick'
import { onMount, tick } from 'svelte';
onMount(async () => {
ctx = canvas.getContext("2d");
canvas.width = width;
canvas.height = height;
await tick()
draw();
});
What await tick() does is to effectively pause execution until all current changes have been applied to the dom
tick in the docs

Resize image within HTML5 Canvas to fit any monitor in JS

I have an image that covers the entire width and height of a canvas that covers the entire screen. The problem is, when the code is run on a computer with a different resolution (width and height), the image does not adjust to the proper height and width of that screen. It stays the original size that I set it in JS. I'm very new to JavaScript, so any help I could get to this image to resize on different resolutions would be amazing. Thanks!
//Global Canvas
var canvas = document.querySelector('.canvas1');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
var c = canvas.getContext('2d');
//Functions
function load_image1() {
"use strict";
var base_image;
base_image = new Image();
base_image.src = ['https://postimg.cc/tnGDb1vD'];
base_image.onload = function(){
c.drawImage(base_image, (window.innerWidth - 1700), -100, 1920, 1080);
};
}
#charset "utf-8";
/* CSS Document */
body {
margin: 0;
}
.canvas1 {
margin: 0;
display: block;
}
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Sylvanas</title>
<link href="styles.css" rel="stylesheet" type="text/css">
</head>
<body>
<canvas class="canvas1">
</canvas>
<!--<canvas class="canvas2">
</canvas>-->
<script src="script.js"></script>
</body>
</html>
You can adjust some c.drawImage() params to get what you're after using some window properties.
Edit: As pointed out in a comment below I added some additional code to listen for a window resize which will adjust the dimensions of the canvas image as needed. This solution does flash a bit on my screen when resizing so there is a potential drawback.
c.drawImage(base_image, 0, 0, canvas.width, canvas.height);
JSFiddle: http://jsfiddle.net/gucr5m1b/4/
var canvas = document.querySelector('.canvas1');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
var c = canvas.getContext('2d');
function load_image1() {
"use strict";
var base_image = new Image();
base_image.src = ['http://i.imgur.com/8rmMZI3.jpg'];
base_image.onload = function() {
c.drawImage(base_image, 0, 0, canvas.width, canvas.height);
};
}
function resizeCanvas() {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
load_image1();
}
function startCanvas() {
window.addEventListener('resize', resizeCanvas, false);
resizeCanvas();
}
startCanvas();
#charset "utf-8";
/* CSS Document */
body {
margin: 0;
}
.canvas1 {
margin: 0;
display: block;
}
<canvas class="canvas1"></canvas>

Image gets distorted when using css to set canvas height/width 100%

I am currently trying to draw an image to canvas, I have this so far:
"use strict";
var debugging = true;
var canvas = document.getElementById('astoniaCanvas');
var ctx = canvas.getContext('2d');
function loadUI() {
var topOverlay = new Image();
topOverlay.src = "/images/00000999.png";
topOverlay.onload = function() {
ctx.drawImage(topOverlay, 0, 0, canvas.width, 10);
}
var bottomOverlay = new Image();
bottomOverlay.src = "/images/00000998.png";
if (debugging) {
console.log('Drawing');
}
}
loadUI();
That works fine, but the image loads and looks like this:
When it should look like this:
The dimensions of the good looking picture are 800x40.
If I remove the
canvas {
width: 100%;
height: 100%;
}
the image goes back to looking normal, how can I scale my canvas?
Any information would be great thanks.
You arent accounting for height. Canvas can be confusing when it comes to height/width vs clientHeight/clientWidth
When you create a canvas the css width and height has no bearing on the number of pixels the internal canvas contains. Unless specifically set a canvas comes with a width height of 300x150.
A trick I have used in the past is to use the clientWidth and a scale to set everything
"use strict";
var debugging = true;
var canvas = document.getElementById('astoniaCanvas');
var ctx = canvas.getContext('2d');
function loadUI() {
var topOverlay = new Image();
topOverlay.onload = function() {
// use a scale between the image width and the canvas clientWidth
var scale = topOverlay.width / canvas.clientWidth;
var newWidth = canvas.clientWidth;
var newHeight = topOverlay.height * scale;
// resize canvas based on clientWidth
canvas.width = newWidth;
canvas.height = newHeight;
ctx.drawImage(topOverlay, 0, 0, newWidth, newHeight);
}
topOverlay.src = "http://i.stack.imgur.com/AJnjh.png";
// var bottomOverlay = new Image();
// bottomOverlay.src = "/images/00000998.png";
if (debugging) {
console.log('Drawing');
}
}
loadUI()
<canvas id="astoniaCanvas" style="width: 100%"></canvas>

How to calculate shape height and width including its border width in canvas?

I am working on a project using HTML5 and javascript.I have a canvas on which document will be loaded.
canvas = document.getElementById('pdf');
ctx = canvas.getContext('2d');
In above canvas, document will be loaded.
I have to draw different shapes on it as an individual canvas at runtime.So that on drawing i have to create a new canvas for each and every Shape (required).
MouseDown
function mouse_Pressed(e) {
getMouse(e);//getting current X and Y position
x1=mx; y1=my;
var cords=getMousePos(canvas,e);
annCanvas=document.createElement('canvas'); //Creating
annCanvasContext=annCanvas.getContext('2d');
isDraw=true;isDrawAnn=true;
}
MouseMove
function mouse_Dragged(e)
{
if(isDraw)
{
getMouse(e);
x2=mx; y2=my;
calculatePoints(x1,y1,x2,y2);
var width=endX-startX;
var height=endY-startY;
annCanvas.style.position = "absolute";
annCanvas.width=4; //Width of square
annCanvas.style.left=""+startX+"px";
annCanvas.style.top=""+startY+"px";
annCanvas.height=height;
annCanvas.style.zIndex="100000";
document.getElementById("canvas").appendChild(annCanvas);
annCanvasContext.fillStyle='rgb(255,255,0)';
annCanvasContext.lineWidth=borderWidth;
annCanvasContext.strokeRect(0,0,width,height);
annCanvasContext.stroke();
}
}
MouseReleased
function mouse_Released(e)
{
isDrag = false;
isDraw=false;
isDrawAnn=false;
}
Main problem is that if i am drawing rectangle with border width 50 then its Canvas-outside part is going to cut because of less area of canvas(i.e. rect shape). So i want to calculate canvas height, width with its borderWidth.
This should take into account the border width as well as width etc.
function init() {
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var s = size(canvas);
alert(s[0]);
}
function size(el) {
var clientHeight = (el.offsetHeight > el.clientHeight) ? el.offsetHeight : el.clientHeight;
var clientWidth = (el.offsetWidth > el.clientWidth) ? el.offsetWidth : el.clientWidth;
return [clientWidth, clientHeight];
};
HTML:
<body onload="init();">
<canvas id="canvas" width="200" height="300" style="width: 500px; height: 400px; border: 10px solid brown;"></canvas>
</body>

Dynamically resize canvas window with javascript/jquery?

How can I resize a canvas with javascript/jquery?
Resizing using the css function and applying it to the canvas element just stretches the content as if you were stretching an image.
How would I go about doing this without the stretching?
http://jsfiddle.net/re8KU/4/
Make a function that does the drawing, then re-draw whenever something changes that requires it (like a page resize, etc). Try it out
Make sure you set the context.canvas.width/height, not CSS width/height. Also note that setting the size clears the canvas.
How I would write it:
(function(){
var c = $("#canvas"),
ctx = c[0].getContext('2d');
var draw = function(){
ctx.fillStyle = "#000";
ctx.fillRect(10,10,50,50);
};
$(function(){
// set width and height
ctx.canvas.height = 600;
ctx.canvas.width = 600;
// draw
draw();
// wait 2 seconds, repeate same process
setTimeout(function(){
ctx.canvas.height = 400;
ctx.canvas.width = 400;
draw();
}, 2000)
});
})();
​
(function($) {
$.fn.extend({
//Let the user resize the canvas to the size he/she wants
resizeCanvas: function(w, h) {
var c = $(this)[0]
c.width = w;
c.height = h
}
})
})(jQuery)
Use this little function I created to take care of resizing on the go. Use it this way --
$("the canvas element id/class").resizeCanvas(desired width, desired height)
Whenever the browser is resized, the following solution resizes the dimensions of the canvas based on the dimensions of the window by creating an initial ratio.
Jsfiddle: http://jsfiddle.net/h6c3rxxf/9/
Note: The canvas needs to be re-drawn, when it is resized.
HTML:
<canvas id="myCanvas" width="300" height="300" >
CSS:
canvas {
border: 1px dotted black;
background: blue;
}
JavaScript:
(function() {
// get the precentage of height and width of the cavas based on the height and width of the window
getPercentageOfWindow = function() {
var viewportSize = getViewportSize();
var canvasSize = getCanvastSize();
return {
x: canvasSize.width / (viewportSize.width - 10),
y: canvasSize.height / (viewportSize.height - 10)
};
};
//get the context of the canvas
getCanvasContext = function() {
return $("#myCanvas")[0].getContext('2d');
};
// get viewport size
getViewportSize = function() {
return {
height: window.innerHeight,
width: window.innerWidth
};
};
// get canvas size
getCanvastSize = function() {
var ctx = getCanvasContext();
return {
height: ctx.canvas.height,
width: ctx.canvas.width
};
};
// update canvas size
updateSizes = function() {
var viewportSize = getViewportSize();
var ctx = getCanvasContext();
ctx.canvas.height = viewportSize.height * percentage.y;
ctx.canvas.width = viewportSize.width * percentage.x;
};
var percentage = getPercentageOfWindow();
$(window).on('resize', function() {
updateSizes();
});
}());

Categories

Resources