[英]Need help re-positioning a circle when the canvas size changes
所以我正在使用本教程中的功能
看起來像這樣-
function resizeGame() {
var gameArea = document.getElementById('canvas-container');
var widthToHeight = 11 / 6;
var newWidth = window.innerWidth;
var newHeight = window.innerHeight;
var newWidthToHeight = newWidth / newHeight;
if (newWidthToHeight > widthToHeight) {
newWidth = newHeight * widthToHeight;
gameArea.style.height = newHeight + 'px';
gameArea.style.width = newWidth + 'px';
} else {
newHeight = newWidth / widthToHeight;
gameArea.style.width = newWidth + 'px';
gameArea.style.height = newHeight + 'px';
}
gameArea.style.marginTop = (-newHeight / 2) + 'px';
gameArea.style.marginLeft = (-newWidth / 2) + 'px';
var gameCanvas = document.getElementById('ctx');
gameCanvas.width = newWidth;
gameCanvas.height = newHeight;
HEIGHT = newHeight;
WIDTH = newWidth
}
因此,我使用WIDTH和HEIGHT定位在畫布上的所有東西都可以正常工作。 但是我的游戲中還有其他一些東西,它們僅使用x和y,並且不會隨畫布而變化。
if(drawBall){
ctx.save();
ctx.beginPath();
ctx.arc(ball.x, ball.y, (ball.diameter/2) - 5,0, 2*Math.PI);
ctx.fillStyle = ball.color;
ctx.fill();
ctx.restore();
}
我如何對我的ball.x和ball.y進行處理,使其隨畫布正確更改?
一切都取決於比率。 知道您可以隨時調整屏幕大小時的位置。
var ratio = { x:1, y: 1 };
function start(){
ratio.x = canvas.width / canvas.clientWidth;
ratio.y = canvas.height / canvas.clientHeight;
drawSomething();
}
function drawSomething(){
context.rect(rectX * ratio.x, rectY * ratio.y, rectWidth * ratio.x, rectHeight * ratio.y);
/// stroke and all that good stuff
}
now listen for window change
window.onresize = function(){
// get new ratio's and draw again
start();
}
這樣,用戶在畫布上以相同的相對位置和大小進行繪制的大小調整都無關緊要。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.