HTML5 Canvas drawImage问题

时间:2014-06-04 10:43:51

标签: html html5 canvas crop drawimage

我使用 cropper.js library 从图像中获取裁剪坐标,然后我创建一个画布来下载裁剪后的图像。

我的固定裁剪尺寸最大为200x200像素

问题在于裁剪后的图像不能完全伸展到画布的200 px宽度。见下图

enter image description here

Check this fiddle(感谢@entio的小提琴)

以下是代码

<body>
        <img src="Desert.jpg" id="image" style="float:left;"/>
        <canvas id="myCanvas" style="height:200px; width:200px; position:absolute; right:50px; top:20px; border:1px dotted black;"></canvas>
        <div>
        <label><em>y</em>coordinate</label>                                
        <input type="text" name="y" id="y-1" class="form-control" value="0" />

        <label><em>x</em> coordinate</label>                                
        <input type="text" name="x" id="x-1" class="form-control" value="0" />

        <label>Selected <em>width</em></label>                                
        <input type="text" name="width" id="width-1" class="form-control" value="0" />

        <label>Selected <em>height</em></label>                                
        <input type="text" name="width" id="height-1" class="form-control" value="0" />                                
     </div>                   

    </body>
    <script type="text/javascript">
        document.getElementById('image').onload = function() {
            new Cropper(image, {
                // options              
                max_width: 200,
                max_height: 200,                    
                update: function(coordinates) {
                    console.log(coordinates);
                    console.log(image);                     
                    for (var i in coordinates) {
                        document.getElementById(i + '-1').value = coordinates[i];
                    }
                    var canvas = document.getElementById('myCanvas');
                    var context = canvas.getContext('2d');                  
                    context.drawImage(image, coordinates['x'],coordinates['y'], coordinates['width'],coordinates['height'], 0, 0, 200, 200);
                }
            });
        }
    </script>

任何帮助?

1 个答案:

答案 0 :(得分:3)

Canvas使用width和height属性。

<canvas id="myCanvas" width="200" height="200" style="height:200px; width:200px; posit...

http://www.whatwg.org/specs/web-apps/current-work/multipage/the-canvas-element.html

&#39; width属性默认为300,而height属性默认为150.&#39; 因此除非您指定if,否则它没有您想要的大小。

<强> FIDDLE: http://jsfiddle.net/RgGJh/2/