Reputation: 360
I am trying to load a Image from an url and draw it onto a canvas which is used as input for a Texture. I have implemented this on https://jsfiddle.net/9Louwn87/25/ . I have used this following snippet to load the image and create the texture
var img = new Image();
img.onload = function() {
canvas.width = size;
canvas.height = size;
ctx.drawImage(this, 0, 0, size, size);
if(texture)
{
texture.needsUpdate = true;
}
};
img.src = "https://threejsfundamentals.org/threejs/resources/images/wall.jpg";
texture = new THREE.Texture(canvas);
Please can anyone point me to the mistake.
Upvotes: 1
Views: 53
Reputation:
The issue is probably that since you're loading the image yourself and you're loading it from another domain you need to request permission to use the image.
var img = new Image();
img.onload = function() {
canvas.width = size;
canvas.height = size;
ctx.drawImage(this, 0, 0, size, size);
if(texture)
{
texture.needsUpdate = true;
}
};
img.crossOrigin = 'anonymous'; // ----------- Add this line
img.src = "https://threejsfundamentals.org/threejs/resources/images/wall.jpg";
texture = new THREE.Texture(canvas);
note that adding that line does not automatically let you use an image from another website. Rather it asks that website for permission to use the image. Some sites (imgur, flickr, github, threejsfundamentals.org), give that permission. Most sites do not give permission. If the image is on the same domain then you generally do not want to set crossOrigin
otherwise unless your server is configured to give permission you won't be able to use local images where as normally if you don't ask then local images just work.
Also, if you had opened the JavaScript console you'd have seen this error
three.min.js:572 Uncaught DOMException: Failed to execute 'texImage2D'
on 'WebGLRenderingContext': Tainted canvases may not be loaded.
One more thing, you can use three.js's ImageLoader
which handles this permission issue automatically setting crossDomain
if the image is on another domain and not setting it if it's local.
const loader = new THREE.ImageLoader();
loader.load("https://threejsfundamentals.org/threejs/resources/images/wall.jpg", function() {
canvas.width = size;
canvas.height = size;
ctx.drawImage(this, 0, 0, size, size);
if(texture)
{
texture.needsUpdate = true;
}
});
Upvotes: 2