【问题标题】:HTML5 Canvas drawImage issueHTML5 Canvas drawImage 问题
【发布时间】:2014-07-24 23:31:23
【问题描述】:

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

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

问题是裁剪后的图像没有完全拉伸到画布应有的 200 像素宽度。见下图

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>

有什么帮助吗?

【问题讨论】:

  • 看起来给定的坐标是错误的。console.log(coordinates) 输出什么?
  • 它给了我一个带有四个键的对象,如下所示 - 对象 {x: 214, y: 121, width: 250, height: 250}
  • 我认为这没有问题..因为即使手动放置坐标...静止图像也不会拉伸到全宽。
  • 我正在尝试制作小提琴,但有些东西不想工作......
  • 好的,小提琴已经解决了。宽度和高度为 0 存在问题;在这里:jsfiddle.net/RgGJh/1

标签: html canvas crop drawimage


【解决方案1】:

画布使用宽度和高度属性。

<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

'width属性默认为300,height属性默认为150。'所以它没有你想要的大小除非你指定if。

小提琴: http://jsfiddle.net/RgGJh/2/

【讨论】:

  • 干杯...完成了这项工作..谢谢男人!没有点击我说我错过了这个,因为我已经在样式属性中给出了高度和宽度。愚蠢的...浪费了好几个小时。
猜你喜欢
  • 1970-01-01
  • 2012-03-30
  • 2012-08-09
  • 1970-01-01
  • 2012-08-09
  • 2011-03-12
  • 1970-01-01
  • 2013-01-01
  • 2019-05-29
相关资源
最近更新 更多