课程地址: 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