Resizable Canvas (JQuery UI)

后端 未结 3 1502
感动是毒
感动是毒 2020-12-24 07:13

ANY DOM element can be made resizable according to this page: http://jqueryui.com/demos/resizable/

However, it seems that this doesn\'t work for the CANVAS element.

3条回答
  •  梦谈多话
    2020-12-24 08:10

    Canvas has two types of resize behavior:

    • Resizing where the contents are stretched to fit the canvas's new dimensions
    • Resizing where the contents remain static while the canvas grows or shrinks

    Here's a page that demonstrates the two types of "resizing": http://xavi.co/static/so-resizable-canvas.html

    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 JavaScript $("#stretch").resizable();

    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 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.

提交回复
热议问题