Skip to content

Instantly share code, notes, and snippets.

@MattArnold
Created July 20, 2016 19:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MattArnold/71a7c3b47dff2163084e8d302aa7aaad to your computer and use it in GitHub Desktop.
Save MattArnold/71a7c3b47dff2163084e8d302aa7aaad to your computer and use it in GitHub Desktop.
Update a skin image to be wrapped around a 3D animated character in the browser. Then take a still PNG image of a frame of animation.
/*
I am using the ThreeJS library to draw and animate a 3D character in a canvas element. The user may use a file upload element to
upload their own image file, to serve as the texture wrapped on the 3D character. This works.
I have a listener set up to detect when the file input changes. The handler updates the skin, and on the next line, it calls a
`snapshot()` function, which creates a still PNG image of a frame of animation.
The goal was to have a still PNG of the character with the new skin, but the resulting still image always shows the texture that was
previously wrapped on the character, not the one the user uploaded.
Is something in my code unexpectedly asynchronous? Or is the change handler firing before the change is complete?
Here is my code:
*/
// Upload a skin
document.getElementById('uploadedskin').addEventListener('change',
function(event){
img.src = URL.createObjectURL(event.target.files[0]);
document.getElementById('skin').value = canvas.toDataURL(event.target.files[0]);
snapshot();
});
function snapshot() {
var preview, cartimg, cartimgenc, scaleCanvas, scaleCtx, thumbnail;
scaleCanvas = document.createElement('canvas');
scaleCtx = scaleCanvas.getContext('2d');
preview = document.getElementById('model').firstElementChild;
cartimg = document.getElementById('cart_image');
cartimgenc = document.getElementById('cart_image_enc');
toBeScaled = preview.toDataURL('image/png');
// hasAnimate = false;
scaleCanvas.width = 128;
scaleCanvas.height = 128;
scaleCtx.fillStyle = '#777';
scaleCtx.fillRect(0, 0, 128, 128);
scaleCtx.fillStyle = '#ddd';
scaleCtx.fillRect(8, 3, 112, 6);
scaleCtx.fillRect(3, 8, 6, 112);
scaleCtx.fillStyle = '#333';
scaleCtx.fillRect(120, 8, 6, 112);
scaleCtx.fillRect(8, 118, 112, 6);
scaleCtx.drawImage(preview, 0, 0, preview.width, preview.height, 0, 0, scaleCanvas.width, scaleCanvas.height);
thumbnail = scaleCanvas.toDataURL('image/png');
cartimg.src = thumbnail;
cart_image_enc.value = thumbnail;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment