问题
So I'm making a website and I have a amazing star wars video with a green background. And I want to remove the green background (chroma key) and paste the video over the html5 website background.
I've searched for hours (not jokking) and I can only find complex code that uses images...
So I would like to replace the green video background with nothing and then paste it over the background of the website.
Can someone help me? I know this is an old toppic, but I'm just starting to code and help would be appreciated.
回答1:
Starting information: The video element
can be an image source for html5 canvas. That means a frame of video can be drawn onto (and manipulated by) the canvas.
Overview: The context.getImageData
method will get the canvas' RGBA pixel data in an array. After modifying the array's pixel data, context.putImageData
will put the modified pixels back onto the canvas.
A Plan Use CSS to position an html5 canvas over the site background. Use that canvas to draw video frames over the site (with greenish video pixels made transparent so the site background shows through).
(some assembly & learning required on your part):
Position an html5 canvas element covering the website background.
Inside a time loop (requestAnimationFrame
):
- Clear the canvas:
context.clearRect
, - Draw a video frame onto the canvas:
context.drawImage(video,0,0)
, - Get the pixel data from the canvas:
context.getImageData
, - Check each pixel for "green-ish-ness":
if(green>220 && red<20 && blue<20)
, - If a pixel is greenish, make it transparent:
(alpha=0)
, - Put the modified pixels back onto the canvas:
context.putImageData
, - Repeat at #1 until the video finishes.
References to help with your learning
Stackoverflow prior post regarding #2: Put the video tag on the Canvas tag
Stackoverflow prior post regarding #3-6: Looping through pixels in an image
来源:https://stackoverflow.com/questions/34253535/how-to-remove-green-background-of-a-video-and-paste-that-video-on-the-background