سؤال

كيف يمكنني تغيير حجم تلقائيا HTML5 <canvas> عنصر لتناسب الصفحة ؟

على سبيل المثال يمكنني الحصول على <div> على نطاق واسع من خلال وضع height و width خصائص 100% ، ولكن <canvas> لن الحجم ؟

هل كانت مفيدة؟

المحلول

أعتقد أنني قد وجدت حل أنيق لهذا:

جافا سكريبت

/* important! for alignment, you should make things
 * relative to the canvas' current width/height.
 */
function draw() {
  var ctx = (a canvas context);
  ctx.canvas.width  = window.innerWidth;
  ctx.canvas.height = window.innerHeight;
  //...drawing code...
}

CSS.

html, body {
  width:  100%;
  height: 100%;
  margin: 0;
}

لم يكن لديه أي تأثير كبير للأداء السلبي بالنسبة لي، حتى الآن.

نصائح أخرى

الحل التالي عملت لي الأفضل. نظرا لأنني جديد نسبيا للترميز، أود الحصول على تأكيد بصري أن هناك شيء يعمل بالطريقة التي أتوقعها. لقد وجدت ذلك في الموقع التالي:http://htmlcheats.com/html/resize-the-html5-canvas-dyamically/

إليك الرمز:

<!DOCTYPE html>

<head>
    <meta charset="utf-8">
    <title>Resize HTML5 canvas dynamically | www.htmlcheats.com</title>
    <style>
    html, body {
      width: 100%;
      height: 100%;
      margin: 0px;
      border: 0;
      overflow: hidden; /*  Disable scrollbars */
      display: block;  /* No floating content on sides */
    }
    </style>
</head>

<body>
    <canvas id='c' style='position:absolute; left:0px; top:0px;'>
    </canvas>

    <script>
    (function() {
        var
        // Obtain a reference to the canvas element using its id.
        htmlCanvas = document.getElementById('c'),
        // Obtain a graphics context on the canvas element for drawing.
        context = htmlCanvas.getContext('2d');

       // Start listening to resize events and draw canvas.
       initialize();

       function initialize() {
           // Register an event listener to call the resizeCanvas() function 
           // each time the window is resized.
           window.addEventListener('resize', resizeCanvas, false);
           // Draw canvas border for the first time.
           resizeCanvas();
        }

        // Display custom canvas. In this case it's a blue, 5 pixel 
        // border that resizes along with the browser window.
        function redraw() {
           context.strokeStyle = 'blue';
           context.lineWidth = '5';
           context.strokeRect(0, 0, window.innerWidth, window.innerHeight);
        }

        // Runs each time the DOM window resize event fires.
        // Resets the canvas dimensions to match window,
        // then draws the new borders accordingly.
        function resizeCanvas() {
            htmlCanvas.width = window.innerWidth;
            htmlCanvas.height = window.innerHeight;
            redraw();
        }
    })();

    </script>
</body> 
</html>

تظهر لك الحدود الزرقاء حافة قماش تغيير حجمها، وهي دائما على طول حافة النافذة، مرئية على جميع الجوانب الأربعة، والتي لم تكن الحال بالنسبة لبعض الإجابات الأخرى المذكورة أعلاه. آمل أن يساعد.

أساسا ما عليك فعله هو ربط حدث OneResize لجسمك، بمجرد قبض على الحدث، تحتاج فقط إلى تغيير حجم القماش باستخدام Window.innerwidth و Window.innerheight.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Canvas Resize</title>

    <script type="text/javascript">
        function resize_canvas(){
            canvas = document.getElementById("canvas");
            if (canvas.width  < window.innerWidth)
            {
                canvas.width  = window.innerWidth;
            }

            if (canvas.height < window.innerHeight)
            {
                canvas.height = window.innerHeight;
            }
        }
    </script>
</head>

<body onresize="resize_canvas()">
        <canvas id="canvas">Your browser doesn't support canvas</canvas>
</body>
</html>

وضع قماش تنسيق مساحة العرض والارتفاع يستند إلى مستعرض العميل الأبعاد يتطلب منك تغيير حجم وإعادة رسم كلما المتصفح هو تغيير حجمها.

أقل معقدة الحل هو الحفاظ على drawable أبعاد المتغيرات في جافا سكريبت ، ولكن مجموعة قماش الأبعاد بناء على الشاشة.عرض الشاشة.الأبعاد الارتفاع.استخدام CSS لتناسب:

#containingDiv { 
  overflow: hidden;
}
#myCanvas {
  position: absolute; 
  top: 0px;
  left: 0px;
} 

نافذة المتصفح عموما لن يكون من أي وقت مضى أكبر من الشاشة نفسها (باستثناء حيث دقة الشاشة misreported, كما أنها يمكن أن تكون غير مطابقة الشاشات المزدوجة) ، وبالتالي فإن الخلفية لا تظهر بكسل نسب لا تختلف.قماش بكسل سوف يكون طرديا مع دقة الشاشة إلا إذا كنت تستخدم CSS لزيادة قماش.

أ CSS النقي نهج إضافة إلى حل jerseyboy أعلاه.
يعمل في Firefox (تم اختباره في V29)، كروم (تم اختباره في V34) و Internet Explorer (تم اختباره في V11).

<!DOCTYPE html>
<html>
    <head>
    <style>
        html,
        body {
            width: 100%;
            height: 100%;
            margin: 0;
        }
        canvas {
            background-color: #ccc;
            display: block;
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            width: 100%;
            height: 100%;
        }
    </style>
</head>
<body>
    <canvas id="canvas" width="500" height="500"></canvas>
    <script>
        var canvas = document.getElementById('canvas');
        if (canvas.getContext) {
            var ctx = canvas.getContext('2d');
            ctx.fillRect(25,25,100,100);
            ctx.clearRect(45,45,60,60);
            ctx.strokeRect(50,50,50,50);
        }
    </script>
</body>
</html>

رابط إلى المثال: http://temporaer.net/open/so/140502_canvas-fit-to-window.html.

ولكن اعتن، كما jerseyboy الدول في تعليقه:

remining قماش مع CSS هو مزعج. على الأقل على Chrome و Safari، لن يتوافق مراكز الأحداث في الفأر / المس الكهربائية 1: 1 مع مواقع Poxel Pixel، وستحتاج إلى تحويل أنظمة الإحداثيات.

ما لم تكن تريد أن ترقى قماش لبيانات الصور الخاصة بك تلقائيا (هذا ما يجري إجابة جيمس سوداء، لكنه لن يبدو جميلا)، يجب عليك تغيير حجمه بنفسك وإعادة رسم الصورة. توسيط قماش

function resize() {

    var canvas = document.getElementById('game');
    var canvasRatio = canvas.height / canvas.width;
    var windowRatio = window.innerHeight / window.innerWidth;
    var width;
    var height;

    if (windowRatio < canvasRatio) {
        height = window.innerHeight;
        width = height / canvasRatio;
    } else {
        width = window.innerWidth;
        height = width * canvasRatio;
    }

    canvas.style.width = width + 'px';
    canvas.style.height = height + 'px';
};

window.addEventListener('resize', resize, false);

إذا كانت Div ملأ تماما صفحة الويب، فيمكنك ملء هذا DIV وكذلك يحتوي على قماش يملأ DIV.

قد تجد هذا مثيرا للاهتمام، حيث قد تحتاج إلى استخدام CSS لاستخدام النسبة المئوية، ولكن ذلك يعتمد على المتصفح الذي تستخدمه، ومقدار اتفاق مع المواصفات:http://www.whatwg.org/specs/web-apps/current-work/multipage/the-canvas-element.html#the-canvas-element.

الأبعاد الجوهرية لعنصر قماش تساوي حجم مساحة الإحداثيات، مع تفسير الأرقام في البكسل CSS. ومع ذلك، يمكن بحجم العنصر بشكل تعسفي بواسطة ورقة نمط. أثناء التقديم، يتم تحجيم الصورة لتناسب حجم التخطيط هذا.

قد تحتاج إلى الحصول على أوفست وارتفاع DIV، أو احصل على ارتفاع النافذة / عرضها وتعيين ذلك كقيمة بكسل.

CSS.

body { margin: 0; } 
canvas { display: block; } 

جافا سكريبت

window.addEventListener("load", function()
{
    var canvas = document.createElement('canvas'); document.body.appendChild(canvas);
    var context = canvas.getContext('2d');

    function draw()
    {
        context.clearRect(0, 0, canvas.width, canvas.height);
        context.beginPath();
        context.moveTo(0, 0); context.lineTo(canvas.width, canvas.height); 
        context.moveTo(canvas.width, 0); context.lineTo(0, canvas.height); 
        context.stroke();
    }
    function resize()
    {
        canvas.width = window.innerWidth;
        canvas.height = window.innerHeight;
        draw();
    }
    window.addEventListener("resize", resize);
    resize();
});

إذا كنت مهتما بالحفاظ على نسب الجانب والقيام بذلك في CSS نقي (بالنظر إلى نسبة العرض إلى الارتفاع)، يمكنك القيام بشيء ما أدناه. المفتاح هو padding-bottom على ال ::content العنصر الذي يحجم container جزء. هذا هو الحجم بالنسبة لعرض الوالدين، وهو 100% بشكل افتراضي. النسبة المحددة هنا يجب أن تتطابق مع نسبة الأحجام على canvas جزء.

// Javascript

var canvas = document.querySelector('canvas'),
    context = canvas.getContext('2d');

context.fillStyle = '#ff0000';
context.fillRect(500, 200, 200, 200);

context.fillStyle = '#000000';
context.font = '30px serif';
context.fillText('This is some text that should not be distorted, just scaled', 10, 40);
/*CSS*/

.container {
  position: relative; 
  background-color: green;
}

.container::after {
  content: ' ';
  display: block;
  padding: 0 0 50%;
}

.wrapper {
  position: absolute;
  top: 0;
  right: 0;
  left: 0;
  bottom: 0;
}

canvas {
  width: 100%;
  height: 100%;
}
<!-- HTML -->

<div class=container>
  <div class=wrapper>
    <canvas width=1200 height=600></canvas>  
  </div>
</div>

(function() {

    // get viewport size
    getViewportSize = function() {
        return {
            height: window.innerHeight,
            width:  window.innerWidth
        };
    };

    // update canvas size
    updateSizes = function() {
        var viewportSize = getViewportSize();
        $('#myCanvas').width(viewportSize.width).height(viewportSize.height);
        $('#myCanvas').attr('width', viewportSize.width).attr('height', viewportSize.height);
    };

    // run on load
    updateSizes();

    // handle window resizing
    $(window).on('resize', function() {
        updateSizes();
    });

}());

باستخدام JQuery، يمكنك تتبع تغيير حجم النافذة وتغيير عرض قماشك باستخدام JQUERY أيضا.

شئ مثل هذا

$( window ).resize(function() {
 		$("#myCanvas").width($( window ).width())
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<canvas id="myCanvas" width="200" height="100" style="border:1px solid #000000;">

أعتقد أن هذا هو ما يجب علينا القيام به بالضبط: http://www.html5rocks.com/en/tutorials/casestudies/gopherwoord-studios-resizing-html5-games/

function resizeGame() {
    var gameArea = document.getElementById('gameArea');
    var widthToHeight = 4 / 3;
    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('gameCanvas');
    gameCanvas.width = newWidth;
    gameCanvas.height = newHeight;
}

window.addEventListener('resize', resizeGame, false);
window.addEventListener('orientationchange', resizeGame, false);

أولا، لا يمكنك استخدام سمات العرض والارتفاع لتغيير الحجم (مع طريقي، على الأقل) لأن ذلك سوف يكسره. يمكنك القيام بذلك: HTML:

<canvas id = 'myCanvas'></canvas>

JS:

var canvas = document.getElementById('myCanvas');

var W = window.innerWidth;
var H = window.innerHeight;
canvas.width = W;
canvas.height = H;
canvas.style.position = 'absolute';
//Or set the position to absolute using CSS

(أرجو أن يغفر لي لأي مطبعي، أميل إلى القيام بذلك كثيرا)

أنا أستخدم Sketch.js لذلك بعد تشغيل الأمر INIT ل Canvas، أغير العرض والارتفاع مع JQUERY. انها قواعد الأبعاد على العنصر الأصل.

$ ('# Drawcanvas'). رسم (). Amart ('الارتفاع'، $ ('# Drawcanvas'). الارتفاع (). الارتفاع ()). ().العرض())؛

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top