首页 > 解决方案 > 如何在画布上突出显示图像的一部分?

问题描述

我的项目是通过指出手图像的手指来捕获指纹。 原始图像

何时捕捉食指我想突出显示/动画类似如下: 在此处输入图像描述

如何使用 javascript 或任何其他技术在画布中做到这一点?

更新:我需要一个示例代码来在手指上上下移动一个条,以创造一种手指正在被扫描的感觉。

标签: javascriptcanvas

解决方案


以下是您大致需要采取的步骤的示例:

//Get reference to canvas.
//Here i will create a canvas manually
var canvas = document.body.appendChild(document.createElement("canvas"));
canvas.width = canvas.height = 200;
var ctx = canvas.getContext("2d");
//Animation properties
var animationStart = Date.now();
var animationDuration = 1 * 1000;
//Overlay image
//In your case it would be an IMG element, but for this example i'll use a canvas
var overlayImage = document.createElement("canvas");
overlayImage.width = 40;
overlayImage.height = 100;
overlayImage.getContext("2d").fillStyle = "blue";
overlayImage.getContext("2d").fillRect(0, 0, overlayImage.width, overlayImage.height);
//Start the animation
requestAnimationFrame(Draw);
function Draw() {
    //Determine current animationStep
    var currentTime = Date.now();
    var animationProgress = Math.min(1, (currentTime - animationStart) / animationDuration);
    //Draw background image.
    //In this case it will just be a red background, but you would probably use 
    ctx.globalAlpha = 1;
    ctx.fillStyle = "red";
    ctx.fillRect(10, 0, 180, 200);
    //Draw overlaying image
    ctx.globalAlpha = 0.4;
    ctx.drawImage(overlayImage, 80, 30);
    //Draw highlightet part of overlaying image
    ctx.globalAlpha = 1;
    ctx.drawImage(overlayImage, 80, 30, overlayImage.width, overlayImage.height * animationProgress);
    //Draw highlight
    //You might want a blending mode here: https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/globalCompositeOperation
    if (animationProgress != 1) {
        ctx.fillStyle = "white";
        ctx.globalAlpha = 0.1;
        for (var i = 1; i <= 10; i++) {
            ctx.fillRect(70, 30 + overlayImage.height * animationProgress, overlayImage.width + 20, -i);
        }
    }
    //Restart animation if fully progressed
    if (animationProgress == 1) {
        setTimeout(function () {
            //Call again to loop
            animationStart = Date.now();
            requestAnimationFrame(Draw);
        }, 300);
    }
    else {
        //Call again to loop
        requestAnimationFrame(Draw);
    }
}


推荐阅读