Game Development Reference
In-Depth Information
There are two issues to watch out for when loading images. First, if you
are running your application locally (by double-clicking on the file, you
will see a
file:///
URL), Chrome will prevent loading images by
default for security reasons (to keep malicious JavaScript from accessing
local files on your computer). You can solve this by either changing your
browser's security settings or running the file using a local HTTP server
as explained at
https://github.com/mrdoob/three.js/wiki/
How-to-run-things-locally
. The second issue is that you cannot
render images loaded from another domain in WebGL, also for security
reasons. You can solve this by serving the image with the
Access-
Control-Allow-Origin
header set to
null
as explained at
https://
hacks.mozilla.org/2011/11/using-cors-to-load-webgl-
textures-from-cross-domain-images/
.
The
ImageUtils.loadTexture()
function loads images. Let's use a slightly more
advanced version to render the
earth
image:
THREE.ImageUtils.loadTexture('earth.jpg', undefined, function(texture)
{
geometry = new THREE.SphereGeometry(280, 20, 20);
material = new THREE.MeshBasicMaterial({map: texture, overdraw:
true});
mesh = new THREE.Mesh(geometry, material);
mesh.rotation.x = 30 * Math.PI / 180;
scene.add(mesh);
});
The second parameter for
loadTexture
is currently unused, and the third parameter
is a callback that is invoked when the image is successfully loaded. (A fourth
parameter is also accepted for an error callback function.) We've seen all the rest of
this code before except the
overdraw
option, which eliminates small gaps between
the mesh's faces that arise due to limitations of the canvas API. (The
WebGLRenderer
does not need this property; it can align faces more perfectly.) You can see the result
in the following screenshot:
Earth as a sphere with a mapped texture