美文网首页
canvas 实现图片切割

canvas 实现图片切割

作者: evelynlab | 来源:发表于2018-03-14 18:20 被阅读99次

场景

有一张图片,想将图片的左半部分切出来,做成新的图片

实现

利用canvas的drawImage方法,可以去这里熟悉api和参数设定

html:

<canvas id="my-canvas" width="438"  height="800" style="border: 1px solid #bdbdbd;"></canvas>

js:

var canvas = document.getElementById('my-canvas');
var context = canvas.getContext('2d');
    var imageObj = new Image();
    imageObj.setAttribute('crossOrigin', 'anonymous'); // 解决报错问题 failed to execute 'toDataURL' on 'HTMLCanvasElement' tainted canvaes may not be exported
    imageObj.onload = function(options) {
        var width = imageObj.width;
        var height = imageObj.height;
        // draw cropped image
        var sourceX = 0;
        var sourceY = 0;
        var sourceWidth = width / 2;
        var sourceHeight = height;
        var destWidth = sourceWidth;
        var destHeight = sourceHeight;
        var destX = 0;
        var destY = 0;
        // 宽度只绘制图片宽度的一半
        context.drawImage(imageObj, sourceX, sourceY, sourceWidth, sourceHeight, destX, destY, destWidth, destHeight);
        var res = canvas.toDataURL("image/png");       // base64 码流... 
    };
imageObj.src = 'http://lc-faNbeFy1.cn-e1.lcfile.com/5c569f82d96afd50a997.jpg';

效果图:


image.png

相关文章

网友评论

      本文标题:canvas 实现图片切割

      本文链接:https://www.haomeiwen.com/subject/rbqqqftx.html