【问题标题】:Crop image to canvas将图像裁剪到画布
【发布时间】:2012-06-10 14:59:03
【问题描述】:

我有 2 个 div

<div id="image-orig">
    <img src="image_example.jpg"/>
</div>

<div id="image-crop">
    <canvas id="preview" style="width:548px;height:387px"></canvas>
</div>

image_example.jpg 可以是任意大小的图片。

    function updatePreview(c) {
        if(parseInt(c.w) > 0) {
            var orig = $("#image-orig img")[0];
            var canvas = $("#image-crop canvas")[0];
            var context = canvas.getContext("2d");

            context.drawImage(orig,
                c.x*coeff,c.y*coeff,c.w*coeff,c.h*coeff,
                0,0,canvas.width,canvas.height
            );
        }
     }

    $(function(){
            $('#image-orig img').Jcrop({
                onSelect: updatePreview,
                onChange: updatePreview,
                aspectRatio : parseFloat($('#image-orig img').width()/$('#image-orig img').height())
            });
    });

coeff - 如果尺寸图像更大的 div 预览,它是系数。

这是个问题: http://dbwap.ru/3725988.png

在第二个 div(画布)中。图像质量非常低。

找到解决方案

            canvas.width = c.w*coeff;
            canvas.height = c.h*coeff;

            context.drawImage(orig,
                c.x*coeff,c.y*coeff,c.w*coeff,c.h*coeff,
                0,0,c.w*coeff,c.h*coeff
            );
            $(that.el).find("#ImageCode").attr('src', canvas.toDataURL());
            $(that.el).find("#ImageCode").show();

我只是创建图像标签并从画布复制到图像。

【问题讨论】:

    标签: html canvas crop jcrop


    【解决方案1】:

    如果您有权访问 .net,则可以使用 JCrop 修改新图像的保存方式: http://mironabramson.com/blog/post/2009/04/Cropping-image-using-jQuery,-Jcrop-and-ASPNET.aspx

    无需使用服务器端 (.net / php) 即可为您提供的解决方案:

    首先,确保在使用 JCrop 时启用了 html5 画布图像平滑:

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

    如果已经设置或没有效果,那么我认为您可以通过每个浏览器来调查图像选项的唯一其他选项:

    在 Mozilla 中启用平滑处理 - 以本文为例(查找“mozImageSmoothingEnabled”):https://developer.mozilla.org/en/Canvas_tutorial/Using_images#Controlling_image_scaling_behavior

    在 IE 中应用过滤器http://code.flickr.com/blog/2008/11/12/on-ui-quality-the-little-things-client-side-image-resizing/

    注意:可能有某种 Flash 解决方案可以工作,但将任何 Flash 解决方案与 JCrop 和 html5 画布结合起来可能太困难了。

    【讨论】:

    • 只是我需要在没有服务器端平台的情况下执行此操作。
    • 更新解决方案(首先,确保在html5画布中设置了图像平滑)
    • 也许可行,但此解决方案仅适用于 IE、Mozilla。我解决了我的问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-03
    • 1970-01-01
    • 1970-01-01
    • 2013-04-05
    • 1970-01-01
    相关资源
    最近更新 更多