在HTML5 Canvas中调整图像大小以适合JS中的任何监视器

时间:2018-11-07 14:21:26

标签: javascript html css image

我有一张图像可以覆盖整个屏幕的画布的整个宽度和高度。问题是,当代码在具有不同分辨率(宽度和高度)的计算机上运行时,图像无法适应该屏幕的适当高度和宽度。它保持了我在JS中设置的原始大小。我是JavaScript的新手,所以我能获得这张图像以在不同分辨率下调整大小的任何帮助都将是惊人的。谢谢!

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

1 个答案:

答案 0 :(得分:1)

您可以调整一些c.drawImage()参数,以使用某些window属性后得到所需的内容。

编辑:正如下面的评论中指出的那样,我添加了一些其他代码来侦听窗口调整大小,这将根据需要调整画布图像的尺寸。调整大小时,此解决方案确实会在屏幕上闪烁一点,因此存在潜在的缺陷。

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>