[英]How to resize <canvas> based on window width/height and maintain aspect ratio?
[英]Updating canvas animation width on window resize
無法弄清楚如何做到這一點。 我具有正確的函數觸發功能,但是在邏輯為何無法正常運行腳本時卻迷失了方向。 我有一個console.log來顯示變量正在更新,但是動畫寬度不會隨之更新。
使用Javascript
$( document ).ready(function() {
var imgTag = new Image();
var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');
var x = canvas.width;
var y = 0;
imgTag.onload = animate;
imgTag.src = "http://foodhall.hellogriptest.com/hh/assets/medallion-bounce.png";
var h = window.innerHeight;
var w = window.innerWidth;
canvas.height = h;
canvas.width = w;
//moving image
var mover = {
x: 0,
y: 0,
width: 100,
height: 100,
color: '#000',
down: true,
right: true
}
function animate() {
clear();
render();
rID = requestAnimationFrame(animate);
}
function clear() {
context.clearRect(0, 0, canvas.width, canvas.height);
}
function render() {
//set direction
if (mover.down && mover.y >= h - mover.height)
mover.down = false;
if (!mover.down && mover.y <= 0)
mover.down = true;
if (mover.right && mover.x >= w - mover.width)
mover.right = false;
if (!mover.right && mover.x <= 0)
mover.right = true;
//make move
if (mover.right)
mover.x += 6;
else
mover.x -= 6;
if (mover.down)
mover.y += 6;
else
mover.y -= 6;
//drawRectangle(mover);
drawImage(mover);
}
function drawImage(mover) {
context.drawImage(imgTag, mover.x, mover.y); // draw image at current position
}
window.onresize = function() {
W = window.innerWidth;
H = window.innerHeight;
canvas.width = W;
canvas.height = H;
x = W;
console.log(x);
clear();
render();
drawImage(mover);
}
});//ready
Codepen — https://codepen.io/alcoven/pen/KROPrK
這是一個簡單的修復。 在腳本的開頭,將小寫字母w和小寫字母h設置為窗口的寬度和高度,但是在調整大小函數中,設置W = window.innerWidth。 然后創建大寫字母W變量並為其指定innerWidth。 小寫的w變量仍然以原始寬度存在,這就是渲染所使用的寬度。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.