温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

使用canvas怎么自定义一个头像功能

发布时间:2021-04-15 17:25:35 来源:亿速云 阅读:234 作者:Leah 栏目:web开发

使用canvas怎么自定义一个头像功能?很多新手对此不是很清楚,为了帮助大家解决这个难题,下面小编将为大家详细讲解,有这方面需求的人可以来学习下,希望你能有所收获。

实现细节:

因为你要对图片所在的区域进行截图,所以你得制作一张canvas,盖在图片所在的区域。这里,我们给出了一个函数,根据传入的DOM里面元素的类名创建相同位置的canvas,盖在原来的DOM元素上面:

function createCanvasByClassName(tag) {
    var canvasInitialWidth = $('.' + tag).width();
    var canvasInitialHeight = $('.' + tag).height();
    var left = $('.' + tag).offset().left - $('.' + tag).parent('.portraitContainer').offset().left + 1;
    var top = $('.' + tag).offset().top - $('.' + tag).parent('.portraitContainer').offset().top + 1;
    //var left = $('.' + tag).offset().left + 1;
    //var top = $('.' + tag).offset().top + 1;
    clearCanvasObj.left = $('.' + tag).offset().left + 1;
    clearCanvasObj.top = $('.' + tag).offset().top + 1;
    // clearCanvasObj.left = left;
    // clearCanvasObj.top = top;
    var canvasElement = $('<canvas></canvas>');
    var randomNum = Math.floor(getRandom(0, 10000));
    clearCanvasObj.canvasId = randomNum;
    canvasElement.attr({
        id: 'canvas',
        width: canvasInitialWidth,
        height: canvasInitialHeight
    });
    canvasElement.css({
        position: 'absolute',
        top: top, 
        left: left
    });
    //$('body').append(canvasElement);
    var appendEle = $('.portraitContainer').append(canvasElement);
    var canvas = document.getElementById('canvas');
    var ctx = canvas.getContext('2d');
    //ctx.fillStyle = "rgba(211,211,216,0.5)";
    ctx.clearRect(0, 0, canvasInitialWidth, canvasInitialHeight);
    ctx.fillStyle = "rgba(0,0,0, 0.4)";
    ctx.fillRect(0, 0, canvasInitialWidth, canvasInitialHeight);
    return canvas;
}

有了这张canvas你就可以在你图片所在区域肆意的操作了。首先,降整个区域画上一个浅黑色的阴影,然后再擦除初始小方框区域里面的颜色。然后给整个页面添加mousedown,mousemove,mouseup事件,他们所做的功能就跟你在页面中实现一个拖拽的功能类似,这里重点说下mousemove里面做的操作,代码如下:

function mousemoveFunc(event) {
    /* Act on the event */
    var nowMouseX = event.clientX - clearCanvasObj.left;
    var nowMouseY = event.clientY - clearCanvasObj.top;
    if (nowMouseX >= clearCanvasObj.xStart && nowMouseX <= clearCanvasObj.xStart + clearCanvasObj.width && nowMouseY >= clearCanvasObj.yStart && nowMouseY <= clearCanvasObj.yStart + clearCanvasObj.height) {
        clearCanvasObj.isCanvasArea = true;
        //clearCanvasObj.isRightCorner = false;
        imgContainerCanvas.style.cursor = 'move';
    } else if ((nowMouseX >= clearCanvasObj.xStart + clearCanvasObj.width - 10) && (nowMouseX <= clearCanvasObj.xStart+ clearCanvasObj.width + 10) 
        && (nowMouseY >= clearCanvasObj.yStart + clearCanvasObj.height - 10) && (nowMouseY <= clearCanvasObj.yStart + clearCanvasObj.height + 10)) {
        clearCanvasObj.isCanvasArea = true;
        //clearCanvasObj.beginDraw = false;

        imgContainerCanvas.style.cursor = 'se-resize';
    } 
    else {
        clearCanvasObj.isCanvasArea = false;
        //clearCanvasObj.isRightCorner = false;
        imgContainerCanvas.style.cursor = 'default';
    }
    var outerDomWidth = $(".imgContainer").width();
    var outerDomHeight = $(".imgContainer").height();
    var xDistance = event.clientX - clearCanvasObj.mouseX;
    var yDistance = event.clientY - clearCanvasObj.mouseY;
    //var outerCTX = canvas.getContext('2d');
    //移动小方框
    if (clearCanvasObj.beginDraw && clearCanvasObj.isCanvasArea && !clearCanvasObj.isRightCorner) {
        ry_CTX.fillStyle = clearCanvasObj.color;
        // console.log('1', clearCanvasObj.xStart, clearCanvasObj.yStart)
        ry_CTX.fillRect(clearCanvasObj.xStart, clearCanvasObj.yStart, clearCanvasObj.width, clearCanvasObj.height);
        //outerCTX.fillRect(0, 0, canvas.width, canvas.height);
        clearCanvasObj.xStart += xDistance;
        clearCanvasObj.yStart += yDistance;

        //判断方框是否达到边界
        if (clearCanvasObj.xStart <= 0) {
            clearCanvasObj.xStart = 0;
        }
        if (clearCanvasObj.yStart <= 0) {
            clearCanvasObj.yStart = 0;
        }
        if ((clearCanvasObj.xStart + clearCanvasObj.width) >= outerDomWidth) {
            clearCanvasObj.xStart = outerDomWidth - clearCanvasObj.width;
        }
        if ((clearCanvasObj.yStart + clearCanvasObj.height) >= outerDomHeight) {
            clearCanvasObj.yStart = outerDomHeight - clearCanvasObj.height;
        }
        // console.log('2', clearCanvasObj.xStart, clearCanvasObj.yStart)
        ry_CTX.clearRect(clearCanvasObj.xStart, clearCanvasObj.yStart, clearCanvasObj.width, clearCanvasObj.height);
        produceSmallPic(clearCanvasObj.xStart+clearCanvasObj.left, clearCanvasObj.yStart+clearCanvasObj.top, clearCanvasObj.width, clearCanvasObj.height, imageURL)
        clearCanvasObj.mouseX = event.clientX;
        clearCanvasObj.mouseY = event.clientY;
    }
    //拖拽小方框
    if (clearCanvasObj.isRightCorner) {
        ry_CTX.fillStyle = clearCanvasObj.color;
        ry_CTX.fillRect(clearCanvasObj.xStart, clearCanvasObj.yStart, clearCanvasObj.width, clearCanvasObj.height);
        var realDistance = Math.min(xDistance, yDistance)
        clearCanvasObj.width +=  realDistance;
        clearCanvasObj.height += realDistance;
        //拖动时边界条件的判断
        if (clearCanvasObj.xStart + clearCanvasObj.width >= outerDomWidth) {
            clearCanvasObj.width = outerDomWidth - clearCanvasObj.xStart;
            clearCanvasObj.height = outerDomWidth - clearCanvasObj.xStart;
        }
        if (clearCanvasObj.yStart + clearCanvasObj.height >= outerDomHeight) {
            clearCanvasObj.width = outerDomHeight - clearCanvasObj.yStart;
            clearCanvasObj.height = outerDomHeight - clearCanvasObj.yStart;
        }
        if (clearCanvasObj.width <= 10) {
            clearCanvasObj.width = 10;
        }
        if (clearCanvasObj.height <= 10) {
            clearCanvasObj.height = 10;
        }
        ry_CTX.clearRect(clearCanvasObj.xStart, clearCanvasObj.yStart, clearCanvasObj.width, clearCanvasObj.height);
        produceSmallPic(clearCanvasObj.xStart+clearCanvasObj.left, clearCanvasObj.yStart+clearCanvasObj.top, clearCanvasObj.width, clearCanvasObj.height, imageURL);
        clearCanvasObj.mouseX = event.clientX;
        clearCanvasObj.mouseY = event.clientY;
    }                            
}

函数里面,你需要注意拖拽的边界条件,一个是方框不能拖到图片所在DOM外的边界;另外一个就是当你鼠标放在小方框所在的区域改变鼠标的样式。方框在拖动的过程中,我们不断重绘方框移动的区域(也就是不断的画上阴影),然后在新的位置调用clearRect函数,重新擦出一个小方框出来。在拖拽或是拉伸的过程中,我们会不断调用produceSmallPic函数,在右边的容器(每个容器都是一个canvas)里面不断根据容器大小重绘出所需的头像。代码如下:

function produceSmallPic(imageURL,left, top, width, height) {
    var img = new Image();
    img.src = imageURL;
    var targetCtx = new Array();
    var targetCanvas = null;
    img.onload = function() {
        portraitGroupsArr.forEach(function(item, index) {
            targetCanvas = document.getElementById(item.class);
            targetCtx.push(targetCanvas.getContext('2d'));
            targetCtx[index].clearRect(0,0, item.width, item.height);
            targetCtx[index].drawImage(img, left - clearCanvasObj.left, top - clearCanvasObj.top, width, height, 0, 0 , item.width, item.height);
        })
    }
}

我们说下这个函数的作用,这里我们要注意一个参数imageURL,这个URL是由图片所在的DOM转化来的。因为你要把DOM所在的区域变成一张图片,这样你才能在利用drawImage函数截取你所需要的区域。所以我们先利用html2canvas库函数讲图片所在的DOM转化为canvas,这张canvas的内容是包含你所要截取的图片的,然后把这张canvas转化为图片取得图片地址imageURL,代码如下:

html2canvas(document.getElementById('imgContainer'), {
        onrendered: function(canvas) {
            var imageURL = canvasTransToImage(canavs);
            ...
        }

})
function canvasTransToImage(canvas) {
    var imageURL = canvas.toDataURL('image/png');
    return imageURL;
}

接着,你就可以便利右侧的canvas容器,讲图片重回到里面了,整个过程就这样结束,回头看来是不是很简单。

相关依赖:

代码如下:


<script src="<a href="https://cdn.bootcss.com/html2canvas/0.5.0-beta4/html2canvas.min.js"></script">https://cdn.bootcss.com/html2canvas/0.5.0-beta4/html2canvas.min.js"></script</a>>

看完上述内容是否对您有帮助呢?如果还想对相关知识有进一步的了解或阅读更多相关文章,请关注亿速云行业资讯频道,感谢您对亿速云的支持。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI