dukelearntoprogram Green Screen Web Page 绿幕图片算法+HTML实现

本文介绍了一个用于网页的绿幕图片背景替换算法。该算法允许用户上传自定义的前景和背景图片,通过设置绿色阈值来实现前景人物与背景的合成。使用HTML、CSS和JavaScript实现,适用于CodePen平台。
摘要由CSDN通过智能技术生成

课程地址: https://www.coursera.org/learn/duke-programming-web/lecture/ZECaT/moving-to-codepen

介绍

一个可以更改绿幕图片的背景的算法,并且可以在网页上传自定义图片进行背景合成。

Html

<script src = "http://www.dukelearntoprogram.com/course1/common/js/image/SimpleImage.js"></script>
<h1>Green Screen Web Page</h1><p>
<canvas id = "fgcan"></canvas>
<canvas id = "bgcan"></canvas>
<p>
Foreground: <input type = "file" multiple = "false" accept = "image/*" id = "fgfile" 
                   onchange = "loadForegroundImage()">
<p>
Background: <input type = "file" multiple = "false" accept = "image/*" id = "bgfile" 
                   onchange = "loadBackgroundImage()">
<p>
Start: <input type = "button" value = "Start" onclick = "greenScreen()">
Clear: <input type = "button" value = "Clear" onclick = "clearfgCanvas(), clearbgCanvas()">

Css

canvas{
  width: 400px;
  height: 200px;
  border: 1px solid;
}

Js

var fgImage = null;
var bgImage = null;
var greenThreshold = 240;

 function loadForegroundImage(){
   var imgfile = document.getElementById("fgfile");
   fgImage = new SimpleImage(imgfile);
   
   var canvas = document.getElementById("fgcan");
   fgImage.drawTo(canvas);
 }

 function loadBackgroundImage(){
   var imgfile = document.getElementById("bgfile");
   bgImage = new SimpleImage(imgfile);
   
   var canvas = document.getElementById("bgcan");
   bgImage.drawTo(canvas);
   
   clertRect
 }

function clearfgCanvas(){
  
  var cvs = document.getElementById("fgcan");
  var ctx = cvs.getContext("2d");
  ctx.clearRect(0, 0, cvs.width, cvs.height);
  
}

function clearbgCanvas(){
  
  var cvs = document.getElementById("bgcan");
  var ctx = cvs.getContext("2d");
  ctx.clearRect(0, 0, cvs.width, cvs.height);
  
}

function greenScreen(){
  if(fgImage == null || ! fgImage.complete()){
    alert("foreground not loaded");
    return;
  }
  if(bgImage == null || ! bgImage.complete()){
    alert("background not loaded");
    return;
  }
  clearbgCanvas();
  
  var output = new SimpleImage(fgImage.getWidth(),fgImage.getHeight());
  for(var pixel of fgImage.values()){
    var x = pixel.getX();
    var y = pixel.getY();
    if(pixel.getGreen() > greenThreshold){
      var bgPixel = bgImage.getPixel(x, y);
      output.setPixel(x, y, bgPixel);
    }
    else{
        output.setPixel(x, y, pixel);
    }
  }
  
  
  var mycanvas = document.getElementById("fgcan");
  output.drawTo(mycanvas);
  
}

效果:

编译环境codepen.io
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值