是否可以在后台使用画布和其他元素?

时间:2014-05-30 19:19:57

标签: javascript html css

我想在后台安装画布,适合整页+其他html元素。有可能吗?

如果不可能,我可以在没有画布的情况下在背景上画画吗?

2 个答案:

答案 0 :(得分:1)

是的,确实如此。只需为<canvas>元素提供这些规则和属性:

    canvas {
    position:absolute; 
    width:100%;
    height:100%
    top:0; 
    left:0;

    }
   /* just-in-case styling: */

       html , body {
       height: 100%;
       width: 100%;

    }

    * {

     padding: 0;
     margin: 0;

    }

或者,根据您要在画布上放置的内容,您可能还想添加一些JavaScript:

(function() {
        var canvas = document.getElementById('canvas'),
                context = canvas.getContext('2d');

        // resize the canvas to fill browser window dynamically
        window.addEventListener('resize', resizeCanvas, false);

        function resizeCanvas() {
                canvas.width = window.innerWidth;
                canvas.height = window.innerHeight;

                /**
                 * Your drawings need to be inside this function otherwise they will be reset when 
                 * you resize the browser window and the canvas goes will be cleared.
                 */
                drawStuff(); 
        }
        resizeCanvas();

        function drawStuff() {
                // do your drawing stuff here
        }
})();

这是 JSFIddle

这使得画布对于浏览器来说更重一些,但随着屏幕动态调整大小。它还可以确保您的动画正常。

答案 1 :(得分:1)

是的,您可以使用此CSS代码执行此操作:

#canvas {
   position:absolute;
   top:0;
   left:0;
   width:100%;
   height:100%;
   z-index:1;
}

#other_content {
    position:relative;
    z-index:2;
    /* other styling */
}

<强> jsFiddle demo.