我正在使用多个画布来对2D画布上的图像进行动画处理(缩放/更改不透明度)。只需使用webgl
进行阅读即可提高整体FPS。我是WEBGL
的新手,发现它与2d
画布完全不同。有人可以指导我如何在主webgl
画布上渲染现有的2d画布。
这是一个演示代码,其中描绘了webgl canvas
和virtual 2d canvas
并绘制了图像。如何在webgl画布上绘制带有图像的2d画布?
let webglCanvas = $('#webgl-canvas')[0];
let webglContext = backgroundCanvas.getContext('webgl');
/* setting up 2d canvas */
let virtualCanvas = document.createElement('canvas');
let virtualContext = virtualCanvas.getContext('2d');
/* setting height and width */
webglCanvas.height = 100;
webglCanvas.width = 150;
virtualCanvas.height = 100;
virtualCanvas.width = 150;
/* fetching image to draw on 2d context */
let image = new Image();
image.src = "http://ahiliahomes.saibbywebdemos.online/assets/images/brown-back.jpg";
image.onload = () => drawImageOn2D()
function drawImageon2D() {
virtualContext.save();
virtualContext.clearRect(0, 0, virtualCanvas.width, virtualCanvas.height, 0, 0);
virtualContext.drawImage(image, 0, 0, image.width, image.height, 0, 0, virtualCanvas.width, virtualCanvas.height);
virtualContext.restore();
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<canvas id="webgl-canvas"></canvas>
答案 0 :(得分:0)
如果您不反对使用第三方库(那么,我强烈建议您使用它!),这就是我如何使用three.js的方法(我使用其他图像是因为遇到了CORS问题)。
这个想法基本上是在WebGL画布上创建一个平面并将图像作为纹理应用在其上。剩下的是样板代码,可渲染场景(aniamte
和使其可见(light
):
const IMG_WIDTH = 390;
const IMG_HEIGHT = 260;
var scene = new THREE.Scene();
// these are the default PerspectiveCamera initialization settings
var camera = new THREE.PerspectiveCamera( 45, IMG_WIDTH / IMG_HEIGHT, 1, 1000 );
// you'll have to play with the camera z position to get closer
// or further to the image, so render it smaller or bigger
camera.position.z = 10;
var renderer = new THREE.WebGLRenderer();
renderer.setSize( IMG_WIDTH, IMG_HEIGHT );
// LIGHT
var light = new THREE.PointLight( 0xffffff, 1, 0 );
light.position.set(1, 1, 100 );
scene.add(light)
var loader = new THREE.TextureLoader();
// IMAGE
var planeMaterial = new THREE.MeshLambertMaterial({
map: loader.load("https://i.imgur.com/fHyEMsl.jpg")
});
var planeGeometry = new THREE.PlaneGeometry(10, 10 * (IMG_HEIGHT/IMG_WIDTH));
var mesh = new THREE.Mesh(planeGeometry, planeMaterial);
mesh.position.set(0, 0, 0);
scene.add(mesh);
document.body.appendChild( renderer.domElement );
// here is the (stereotyped) render loop
function animate() {
requestAnimationFrame( animate );
renderer.render( scene, camera );
}
animate();
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/99/three.min.js"></script>