Centering a canvas

后端 未结 11 1437
野的像风
野的像风 2021-01-30 10:00

How do I markup a page with an HTML5 canvas such that the canvas

  1. Takes up 80% of the width

  2. Has a corresponding pixel h

11条回答
  •  走了就别回头了
    2021-01-30 10:59

    Looking at the current answers I feel that one easy and clean fix is missing. Just in case someone passes by and looks for the right solution. I am quite successful with some simple CSS and javascript.

    Center canvas to middle of the screen or parent element. No wrapping.

    HTML:

    No canvas support
    

    CSS:

    #canvas {
        position: absolute;
        top:0;
        bottom: 0;
        left: 0;
        right: 0;
        margin:auto;
    }
    

    Javascript:

    window.onload = window.onresize = function() {
        var canvas = document.getElementById('canvas');
        canvas.width = window.innerWidth * 0.8;
        canvas.height = window.innerHeight * 0.8;
    }
    

    Works like a charm - tested: firefox, chrome

    fiddle: http://jsfiddle.net/djwave28/j6cffppa/3/

提交回复
热议问题