Canvas 应用 互动版

实现图像裁剪


这个主要是实现一个居中的覆盖矩形(overlay),接着通过计算背景图片和该覆盖矩形的偏移来获取图片裁剪区域的坐标,

然后再通过CanvasdrawImagetoDataURL完成裁剪图的绘制。

crop = function(){  
    var crop_canvas,  
        left = $('.overlay').offset().left - $container.offset().left,  
        top =  $('.overlay').offset().top - $container.offset().top,  
        width = $('.overlay').width(),  
        height = $('.overlay').height();  

    crop_canvas = document.createElement('canvas');  
    crop_canvas.width = width;  
    crop_canvas.height = height;  

    crop_canvas.getContext('2d').drawImage(image_target, left, top, width, height, 0, 0, width, height);  
    window.open(crop_canvas.toDataURL("image/png"));  
}