javascript - 在 Canvas 上製作假 CRT 效果
我想讓我的畫布看起來像是在一個曲面和圓角的CRT螢幕上,類似這兩張圖片:
我該如何對 HTML5 畫布做到這一點?我很樂意直接在畫布繪圖中做到,或是將 CSS 樣式應用到畫布上。
謝謝!
答案#1
快速搜尋給了我這個網站:WebGL 假 CRT 效果用於 HTML5 遊戲,它使用了 glfx.js 庫。
這是一個用於對圖像應用即時 WebGL 效果的庫,但
canvas標籤實際上可以作為圖像來源來使用...
這個示範使用這張圖片覆蓋到 canvas 上。
實際上創建效果的程式碼如下:
// Make sure you've included the glfx.js script in your code!
// Here I load a PNG with scanlines that I overwrite onto the 2D game's canvas.
// This file happens to be customized for the demo game, so to make this a
// general solution we'll need a generic scanline image or we'll generate them
// procedurally.
// Start loading the image right away, not after the onload event.
var lines = new Image();
lines.src = 'https://i.sstatic.net/QPN59.png';
window.addEventListener('load', fakeCRT, false);
function fakeCRT() {
var glcanvas, source, srcctx, texture, w, h, hw, hh, w75;
// Try to create a WebGL canvas (will fail if WebGL isn't supported)
try {
glcanvas = fx.canvas();
} catch (e) {return;}
// Assumes the first canvas tag in the document is the 2D game, but
// obviously we could supply a specific canvas element here.
source = document.getElementsByTagName('canvas')[0];
srcctx = source.getContext('2d');
// This tells glfx what to use as a source image
texture = glcanvas.texture(source);
// Just setting up some details to tweak the bulgePinch effect
w = source.width;
h = source.height;
hw = w / 2;
hh = h / 2;
w75 = w * 0.75;
// Hide the source 2D canvas and put the WebGL Canvas in its place
source.parentNode.insertBefore(glcanvas, source);
source.style.display = 'none';
glcanvas.className = source.className;
glcanvas.id = source.id;
source.id = 'old_' + source.id;
// It is pretty silly to setup a separate animation timer loop here, but
// this lets us avoid monkeying with the source game's code.
// It would make way more sense to do the following directly in the source
// game's draw function in terms of performance.
setInterval(function () {
// Give the source scanlines
srcctx.drawImage(lines, 0, 0, w, h);
// Load the latest source frame
texture.loadContentsOf(source);
// Apply WebGL magic
glcanvas.draw(texture)
.bulgePinch(hw, hh, w75, 0.12)
.vignette(0.25, 0.74)
.update();
}, Math.floor(1000 / 40));
}
通常是可行的,雖然我應該警告你,Safari 6 曾經至少有幾次讓我的整個系統凍結了一分鐘……但不是每次都會。我想你在 Chrome 上可能會更開心。

