javascript - 如何在画布上突出显示图像的一部分?
问题描述
如何使用 javascript 或任何其他技术在画布中做到这一点?
更新:我需要一个示例代码来在手指上上下移动一个条,以创造一种手指正在被扫描的感觉。
解决方案
以下是您大致需要采取的步骤的示例:
//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);
}
}
推荐阅读
- react-native - 如果缓存数据与新的 reducers 结构不一致,我们如何防止移动应用程序崩溃?
- java - 使用 Keycloak 保护 Swagger 3
- javascript - 如何将变量从php返回到javascript
- amazon-web-services - 从 Extendscript 调用 Amazon Lambda(或获取 Amazon Lambda 的 http 调用 url)
- macos - 在不需要时杀死所有 Adobe 后台进程 MAC
- c++ - 扩展包含 lambda 类型的参数包时出现奇怪的错误
- database - Android房间数据库插入/更新序列
- haskell - 如何为这个特定结构实现 foldr?
- css - 标头中的 Jekyll 代码块太小
- reactjs - React 限制渲染次数以防止无限循环...重新渲染次数过多