更新时间:2023-01-13 22:27:25
Canvas有两种类型的调整行为:
Canvas has two types of resize behavior:
这里有一个页面演示了两种类型的调整大小: http://xavi.co/static/so-resizable-canvas.html
Here's a page that demonstrates the two types of "resizing": http://xavi.co/static/so-resizable-canvas.html
如果您需要第一种类型调整大小(拉伸内容),然后将画布放入一个容器 div
,并设置 width
和 height
设置为100%。代码如下所示:
If you want the first type of resizing (stretch the content) then place the canvas into a container div
and set the width
and height
of the canvas to 100% using CSS. Here's what that code might look like:
/* The CSS */
#stretch {
height: 100px;
width: 200px;
}
#stretch canvas {
width: 100%;
height: 100%;
}
<!-- The markup -->
<div id="stretch"><canvas></canvas></div>
// The JavaScript
$("#stretch").resizable();
第二种调整大小(静态内容)的过程分为两步。首先必须调整canvas元素的 width
和 height
属性。不幸的是,这样做会清除画布,因此您必须重新绘制其所有内容。这里有一些代码:
The second type of resizing (static content) is a two step process. First you must adjust the width
and height
attributes of the canvas element. Unfortunately, doing this clears the canvas, so you must then re-draw all its contents. Here's bit of code that does this:
/* The CSS */
#resize {
height: 100px;
width: 200px;
}
<!-- The markup -->
<div id="resize"><canvas></canvas></div>
// The JavaScript
$("#resize").resizable({ stop: function(event, ui) {
$("canvas", this).each(function() {
$(this).attr({ width: ui.size.width, height: ui.size.height });
// Adjusting the width or height attribute clears the canvas of
// its contents, so you are forced to redraw.
reDraw(this);
});
} });
目前上述代码在用户停止调整窗口小部件时重新绘制画布的内容。可以在调整大小上重新绘制画布,但调整大小的事件会相当正常经常和重复是昂贵的操作 - 谨慎的方法。
Currently the code above re-draws the canvas's content when the user stops resizing the widget. It's possible to re-draw the canvas on resize, however resize events occur fairly often and re-draws are expensive operations -- approach with caution.