Skip to content

Instantly share code, notes, and snippets.

@Schindst
Created May 31, 2020 07:01
Show Gist options
  • Save Schindst/dab6804d42ad8f12560e5a768c9d141b to your computer and use it in GitHub Desktop.
Save Schindst/dab6804d42ad8f12560e5a768c9d141b to your computer and use it in GitHub Desktop.
Image Green Screen
<script src= "https://www.dukelearntoprogram.com/course1/common/js/image/SimpleImage.js"></script>
<h1>Upload an Image</h1>
<canvas id="canl" ></canvas>
<canvas id="canr" ></canvas>
<p>Foreground:
<input type="file" multiple="false" accept="image/*" id="fginput" onchange="loadForegroundImage()" ></p>
<p>Background:
<input type="file" multiple="false" accept="image/*" id="bginput" onchange="loadBackgroundImage()" ></p>
<p>
<input type="button" value="Create Composite" onclick="doGreenScreen()" >
<input type="button" value="Clear Canvases" onclick="clearCanvas()" >
</p>
var fgImage = null;
var bgImage = null;
var output = null;
var canvas;
function loadForegroundImage() {
var fginput = document.getElementById("fginput");
fgImage = new SimpleImage(fginput);
canvas = document.getElementById("canl");
fgImage.drawTo(canvas);
};
function loadBackgroundImage() {
var bginput = document.getElementById("bginput");
bgImage = new SimpleImage(bginput);
canvas = document.getElementById("canr");
bgImage.drawTo(canvas);
};
function doGreenScreen() {
if (fgImage == null) {
alert('please select foreground image');
} else if (!fgImage.complete() || !bgImage.complete()) {
alert('please wait until pictures are loaded');
} else if(bgImage == null) {
alert('Please select background image');
} else {
doClear("canr");
greenScreenLoop();
}
};
function clearCanvas() {
doClear("canl");
doClear("canr");
};
function doClear(canvas_id) {
canvas = document.getElementById(canvas_id);
var context = canvas.getContext("2d");
context.clearRect(0,
0,
canvas.width,
canvas.height);
};
function greenScreenLoop() {
var newImage = new SimpleImage(fgImage.getWidth(), fgImage.getHeight());
for(var fgPixel of fgImage.values()) {
var x = fgPixel.getX();
var y = fgPixel.getY();
if (fgPixel.getGreen() > fgPixel.getRed() + fgPixel.getBlue()) {
var bgPixel = bgImage.getPixel(x, y);
newImage.setPixel(x, y, bgPixel);
} else {
newImage.setPixel(x, y, fgPixel);
}
}
canvas = document.getElementById("canr");
newImage.drawTo(canvas);
}
body {
text-align: center;
background-color: lightgray;
margin: 30px;
}
canvas {
background-color: white;
margin: 5pt;
width: 250px;
}
@Schindst
Copy link
Author

simple interactive website for green screen

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment