响应的画布元素

时间:2016-05-05 18:16:56

标签: javascript html twitter-bootstrap canvas

我已经创建了一个响应式画布,但我很难弄清楚如何在画布中制作一个矩形元素也能响应。我需要矩形始终是画布宽度的100%,并且高度需要也是静态50px。

Canvas Html

<div id="newCanvas" role="main">
    <canvas id="respondCanvas" width="100" height="100">
        Please use a different browser
    </canvas>
</div>

CSS

#newCanvas {
display:block;
width:100%;
padding:50px 10%;
height:400px;
border:2px solid black;
background: #b8b894; /* For browsers that do not support gradients */
background: -webkit-linear-gradient(#b8b894, #ebebe0); /* For Safari 5.1 to 6.0 */
background: -o-linear-gradient(#b8b894, #ebebe0); /* For Opera 11.1 to 12.0 */
background: -moz-linear-gradient(#b8b894, #ebebe0); /* For Firefox 3.6 to 15 */
background: linear-gradient(#b8b894, #ebebe0); /* Standard syntax (must be last) */
}

的Javascript

$(document).ready( function(){
    //Get the canvas & context
    var c = $('#respondCanvas');
    var ct = c.get(0).getContext('2d');
    var container = $(c).parent();

    //Run function when browser resizes
    $(window).resize( respondCanvas );

    function respondCanvas(){
        c.attr('width', $(container).width() ); //max width
        c.attr('height', $(container).height() ); //max height

        //Call a function to redraw other content (texts, images etc)
    }

    //Initial call
    respondCanvas();

    // Code I used to draw a road
    //function drawRoad() {
    //    ctx.beginPath();
    //    ctx.rect(x, y, w, h);
    //    ctx.closePath();
    //    ctx.fill();
    //};

    //drawRoad();

    //    var can = document.getElementById("newCanvas");
    //    var ctx = can.getContext("2d");
    //    ctx.moveTo(0, 75); //x-axis, y-axis
    //    ctx.lineTo(400, 75);
    //    ctx.strokeStyle = "grey";
    //    ctx.lineWidth = 20;
    //    ctx.stroke();

});

演示 https://jsfiddle.net/ccvk3y5q/

参考文献: http://www.garygarside.com/labs/responsive-canvas/

http://ameijer.nl/2011/08/resizable-html5-canvas/

Make Html5 Canvas and Its contained image responsive across browsers

1 个答案:

答案 0 :(得分:1)

要获得所需的结果,您必须每隔几毫秒重绘一次画布并重新绘制所有对象,因此您必须存储要绘制的对象。然后,您可以更改这些存储对象中的变量(使用事件处理程序,setTimeout()等),以查看画布中反映的更改。

主循环示例:

function update(){
    ctx.beginPath;
    for(var i=0; i<rects.length;i++){
        ctx.drawRect(rects[i][0],rects[i][1],rects[i][2],rects[i][3]);
    }
    ctx.stroke();
}

添加矩形(在update()之外执行此操作):

rects[easily rememberable number] = [x,y,width,height];

rects.push(x,y,width,height);

编辑矩形的高度:

rects[#][3] = 15;