HTML5 响应式画布:调整浏览器画布绘制的大小消失

Posted

技术标签:

【中文标题】HTML5 响应式画布:调整浏览器画布绘制的大小消失【英文标题】:HTML5 responsive canvas: resizing the browser canvas draw disappear 【发布时间】:2013-03-30 11:48:51 【问题描述】:

我想使用百分比大小制作一个响应式画布,一旦用户调整窗口大小,画布就会相对调整。 我可以使用下面的代码来缩放画布,但唯一的问题是当我缩放窗口大小时,鼠标绘图会消失。

<style>
bodymargin:0px;padding:0px;background:#a9a9a9;
#main
display:block;
width:80%;
padding:50px 10%;
height:300px;
 
canvasdisplay:block;background:#fff;
</style>
</head>
<body>
<div id="main" role="main">
<canvas id="paint"  >
< !-- Provide fallback -->
</canvas>
</div> 

<script>

var c = document.getElementById('paint');
var ctx = c.getContext('2d');
var x = null;
var y;

c.onmousedown = function(e)
x = e.pageX - c.offsetLeft;
y = e.pageY - c.offsetTop;
ctx.beginPath();
ctx.moveTo(x,y);



c.onmouseup = function(e)
x=null;




c.onmousemove = function(e)
if(x==null) return;
x = e.pageX - c.offsetLeft;
y = e.pageY - c.offsetTop; 
ctx.lineTo(x,y);
ctx.stroke();



$(document).ready( function()
//Get the canvas &
var c = $('#paint');

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();

); 


</script>

谢谢。

【问题讨论】:

听起来像是***.com/questions/5517783/…的副本 使用这个库,在每一帧上绘制屏幕:georgealways.github.io/gee 看看这个:***.com/a/23128583/1265753 【参考方案1】:

调整画布大小时处理内容

如果您调整画布的大小,绘制的内容总是会被擦除。这就是画布的行为方式。

您可以在调整大小后重新绘制内容,也可以将内容保存为图像数据并在调整大小后恢复(参见 canvas.toDataURL)。

这是代码和小提琴:http://jsfiddle.net/m1erickson/V6SVz/

<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" media="all" href="css/reset.css" /> <!-- reset css -->
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>

<style>
    body background-color: ivory; padding:10px; 
    canvasborder:1px solid red;
</style>

<script>
$(function()

    var canvas=document.getElementById("canvas");
    var ctx=canvas.getContext("2d");

    // draw some content
    ctx.lineWidth=3;
    ctx.fillStyle="blue";
    ctx.strokeStyle="red";
    ctx.rect(50,50,100,50);
    ctx.fill();
    ctx.stroke();
    ctx.font="14px Verdana";
    ctx.fillStyle="white";
    ctx.fillText("Scale Me",65,75);

    function saveResizeAndRedisplay(scaleFactor)

        // save the canvas content as imageURL
        var data=canvas.toDataURL();

        // resize the canvas
        canvas.width*=scaleFactor;
        canvas.height*=scaleFactor;

        // scale and redraw the canvas content
        var img=new Image();
        img.onload=function()
            ctx.drawImage(img,0,0,img.width,img.height,0,0,canvas.width,canvas.height);
        
        img.src=data;

    

    $("#resizer").click(function() saveResizeAndRedisplay(1.5); );

); // end $(function());
</script>

</head>

<body>
    <button id="resizer">Click to resize the canvas</button><br/>
    <canvas id="canvas" width=200 height=150></canvas>
</body>
</html>

【讨论】:

【参考方案2】:
c.attr('width', $(container).width() ); //max width
c.attr('height', $(container).height() ); //max height

上面的代码相当于clearRect,用于清除画布。所以如果要保留之前绘制的内容,则无法调整宽度和高度。 作为一种解决方案,您可以创建一个具有所需宽度的新画布并使用 drawImage(c) 绘制先前画布的内容。c 是画布对象。然后您必须删除画布

【讨论】:

谢谢那么有没有什么选项可以先保存画布绘图,然后设置 c.attr().. 或任何其他方式为画布设置动态响应宽度/高度。【参考方案3】:

我也遇到了你在 mu 应用程序中面临的同样问题,在阅读了它之后,我得出了这样的结论:canvas 元素的行为在重新调整大小后会自行清除,这是解决此问题的唯一方法就是为window re-size事件添加一个监听器,当事件触发时重绘画布。

$(window).resize(function(e) 
// function to redraw on the canvas
);



$(document).ready(function(e)
    var c = $('#example'); // getting the canvas element
    var ct = c.get(0).getContext('2d');
    var container = $(c).parent();
    $(window).resize( respondCanvas ); //handling the canvas resize
    function respondCanvas() 
        // makign the canvas fill its container
        c.attr('width', $(container).width() ); //max width
        c.attr('height', ($(container).height() -20 )); //max height
    
    respondCanvas();
    make_image('images/india.png',1,1);

希望对你有帮助。

Source

【讨论】:

从网站复制代码时请提供出处。【参考方案4】:

谢谢。这真的很有帮助。下面是我试图做的代码。

#main
display:block;
width:80%;
height:300px;
background:#e0e0e0;
 
canvasdisplay:block;background:#fff;border:1px solid red;

</style>

<script>

$(function()

var container=document.getElementById("main");
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");

// draw some content
//alert(canvas.width);

var w=$(container).width();
var h=$(container).height();



$(window).resize( saveResizeAndRedisplay );
function saveResizeAndRedisplay()

    // save the canvas content as imageURL
    var data=canvas.toDataURL();

    // resize the canvas
    canvas.width = $(container).width();
    canvas.height = $(container).height();
    //alert($(container).width());

    // scale and redraw the canvas content
    var img=new Image();
    img.onload=function()
        ctx.drawImage(img,0,0,img.width,img.height);
    
    img.src=data;



saveResizeAndRedisplay();

); 
</script>

</head>

<body>

<div id="main" role="main">
 <canvas id="canvas" width=200 height=150></canvas>
</div>

<script>
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
var x = null;
var y;

canvas.onmousedown = function(e)
x = e.pageX - canvas.offsetLeft;
y = e.pageY - canvas.offsetTop;
ctx.beginPath();
ctx.moveTo(x,y);


canvas.onmouseup = function(e)
x=null;



canvas.onmousemove = function(e)
if(x==null) return;
x = e.pageX - canvas.offsetLeft;
y = e.pageY - canvas.offsetTop; 
ctx.lineTo(x,y);
ctx.stroke();

</script>

【讨论】:

【参考方案5】:

我创建了一个处理 HTML5 画布大小调整的 jQuery 插件。它旨在弥合移动和桌面用户之间的差距。它仍然是一个 WIP,但它是可扩展的,并且内置了一些基本的绘图功能。

http://trsanders.github.io/responsive-sketchpad/

【讨论】:

【参考方案6】:

我用这个方法:

var context = document.getElementById('paint').getContext('2d');
var canvas = context.canvas;

function responsive(width)
    var p = width / canvas.width;
    canvas.width *= p;
    canvas.height *= p;

    var scaleFactor = context.scaleFactor || 1;
    context.scale(p * scaleFactor, p * scaleFactor);
    context.scaleFactor = p * scaleFactor;


var mq = window.matchMedia("(min-width: 735px)");
mq.addListener(applyChanges);
applyChanges();

function applyChanges()
    if(!mq)
        responsive(350);
    else
        responsive(735);

【讨论】:

【参考方案7】:

我遇到了同样的问题。我的解决方案是使用 CSS3 的属性缩放到画布的父容器:

<div id="parent_div">
    <div id="constructor_div">
         <canvas  >
    </div>
</div>

<script>
    constructor_zoom();

    $(window).resize(function() 
        constructor_zoom();
    );

    function constructor_zoom()
    
        var parent_width = $('#parent_div').width();
        var item_width = $('#constructor_div').width();
        var coef = 0.1;

        $('.constructor_image').css('zoom', parent_width/item_width - coef);
    
</script>

coef - 从父边框开始缩进画布的系数。您可以将其设为零。

我希望它对某人有所帮助:-)

【讨论】:

不确定缩放是 CSS 属性

以上是关于HTML5 响应式画布:调整浏览器画布绘制的大小消失的主要内容,如果未能解决你的问题,请参考以下文章

适用于不同设备的响应式画布

在窗口调整大小时动态调整画布大小

如何在不损失图像质量的情况下调整图像大小以适合小型 HTML5 画布? [复制]

html5中怎么根据内容高低来调整画布大小

如何在html5中居中画布

如何为Fabric.js启用响应式设计