Reputation: 305
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>
Upvotes: 0
Views: 68
Reputation: 2335
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>
Upvotes: 1