I was trying a tutorial which would draw a triangle and a square using WebGL.
http://learningwebgl.com/blog/?p=28 that one.
So when I got to the first testing zone.
I got the error:
Uncaught ReferenceError: initGL is not defined.
This is my code:
var triangleVertexPositionBuffer;
var squareVertexPositionBuffer;
function webGLStart() {
var canvas = document.getElementById("lesson01-canvas");
initGL(document.getElementById("lesson01-canvas"));
initShaders();
initBuffers();
gl.clearColor(0.0, 0.0, 0.0, 1.0);
gl.enable(gl.DEPTH_TEST);
drawScene();
}
function initBuffers() {
// driehoek
triangleVertexPositionBuffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, triangleVertexPositionBuffer);
var vertices = [
0.0, 1.0, 0.0,
-1.0, -1.0, 0.0,
1.0, -1.0, 0.0
];
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertices), gl.STATIC_DRAW);
triangleVertexPositionBuffer.itemSize = 3;
triangleVertexPositionBuffer.numItems = 3;
// vierkant
squareVertexPositionBuffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, squareVertexPositionBuffer);
vertices = [
1.0, 1.0, 0.0,
-1.0, 1.0, 0.0,
1.0, -1.0, 0.0,
-1.0, -1.0, 0.0
];
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertices), gl.STATIC_DRAW);
squareVertexPositionBuffer.itemSize = 3;
squareVertexPositionBuffer.numItems = 4;
}
function drawScene() {
gl.viewport(0, 0, gl.viewportWidth, gl.viewportHeight);
gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
mat4.perspective(pMatrix, 45, gl.viewportWidth / gl.viewportHeight, 0.1, 100.0);
mat4.identity(mvMatrix);
mat4.translate(mvMatrix, mvMatrix, [-1.5, 0.0, -7.0]);
gl.bindBuffer(gl.ARRAY_BUFFER, triangleVertexPositionBuffer);
gl.vertexAttribPointer(shaderProgram.vertexPositionAttribute,
triangleVertexPositionBuffer.itemSize, gl.FLOAT, false, 0, 0);
setMatrixUniforms();
gl.drawArrays(gl.TRIANGLES, 0, triangleVertexPositionBuffer.numItems);
mat4.translate(mvMatrix, mvMatrix, [3.0, 0.0, 0.0]);
gl.bindBuffer(gl.ARRAY_BUFFER, squareVertexPositionBuffer);
gl.vertexAttribPointer(shaderProgram.vertexPositionAttribute,
squareVertexPositionBuffer.itemSize, gl.FLOAT, false, 0, 0);
setMatrixUniforms();
gl.drawArrays(gl.TRIANGLE_STRIP, 0, squareVertexPositionBuffer.numItems);
}
Those functions (e.g. initGL) are not part of WebGL
Presumably they are other functions in (or which should have been mentioned by) the tutorial - maybe there is a JavaScript library that should be included? It appears that initGL should also have set the global gl variable.
For instance, see "initGL" of the same site (which I found by searching for "WebGL initGL"). You'll have to hunt down the other definitions (where is initShaders?) to patch the given code ..
Like user2864740 mentioned you are missing some helper functions that the tutorial writer has created. I would suggest clicking the "Click here and you’ll see the live WebGL version" link near the top of every chapter and viewing the source code.
It seems you are missing the following code:
var gl;
function initGL(canvas) {
try {
gl = canvas.getContext("experimental-webgl");
gl.viewportWidth = canvas.width;
gl.viewportHeight = canvas.height;
} catch (e) {
}
if (!gl) {
alert("Could not initialise WebGL, sorry :-(");
}
}
function getShader(gl, id) {
var shaderScript = document.getElementById(id);
if (!shaderScript) {
return null;
}
var str = "";
var k = shaderScript.firstChild;
while (k) {
if (k.nodeType == 3) {
str += k.textContent;
}
k = k.nextSibling;
}
var shader;
if (shaderScript.type == "x-shader/x-fragment") {
shader = gl.createShader(gl.FRAGMENT_SHADER);
} else if (shaderScript.type == "x-shader/x-vertex") {
shader = gl.createShader(gl.VERTEX_SHADER);
} else {
return null;
}
gl.shaderSource(shader, str);
gl.compileShader(shader);
if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
alert(gl.getShaderInfoLog(shader));
return null;
}
return shader;
}
var shaderProgram;
function initShaders() {
var fragmentShader = getShader(gl, "shader-fs");
var vertexShader = getShader(gl, "shader-vs");
shaderProgram = gl.createProgram();
gl.attachShader(shaderProgram, vertexShader);
gl.attachShader(shaderProgram, fragmentShader);
gl.linkProgram(shaderProgram);
if (!gl.getProgramParameter(shaderProgram, gl.LINK_STATUS)) {
alert("Could not initialise shaders");
}
gl.useProgram(shaderProgram);
shaderProgram.vertexPositionAttribute = gl.getAttribLocation(shaderProgram, "aVertexPosition");
gl.enableVertexAttribArray(shaderProgram.vertexPositionAttribute);
shaderProgram.pMatrixUniform = gl.getUniformLocation(shaderProgram, "uPMatrix");
shaderProgram.mvMatrixUniform = gl.getUniformLocation(shaderProgram, "uMVMatrix");
}
var mvMatrix = mat4.create();
var pMatrix = mat4.create();
function setMatrixUniforms() {
gl.uniformMatrix4fv(shaderProgram.pMatrixUniform, false, pMatrix);
gl.uniformMatrix4fv(shaderProgram.mvMatrixUniform, false, mvMatrix);
}
Depending on the rest of the html on your page, you may also be missing the following script tags:
<script id="shader-fs" type="x-shader/x-fragment">
precision mediump float;
void main(void) {
gl_FragColor = vec4(1.0, 1.0, 1.0, 1.0);
}
</script>
<script id="shader-vs" type="x-shader/x-vertex">
attribute vec3 aVertexPosition;
uniform mat4 uMVMatrix;
uniform mat4 uPMatrix;
void main(void) {
gl_Position = uPMatrix * uMVMatrix * vec4(aVertexPosition, 1.0);
}
</script>
Related
I am trying to set this HTML code to a Chromebook background. Is this possible? I also don't want to have to use any extensions.
<style>*{
-webkit-box-sizing: border-box;
box-sizing: border-box;
}
html, body{
height: 100%;
margin: 0;
padding: 0;
background-color: #333;
overflow: hidden;
}
canvas{
background-color: #000;
}</style>
<div class="container">
<div class="row">
<canvas id="nokey" width="800" height="800">
</canvas>
</div>
</div>
<script>
var canvas = document.getElementById('nokey'),
can_w = parseInt(canvas.getAttribute('width')),
can_h = parseInt(canvas.getAttribute('height')),
ctx = canvas.getContext('2d');
// console.log(typeof can_w);
var ball = {
x: 0,
y: 0,
vx: 0,
vy: 0,
r: 0,
alpha: 1,
phase: 0
},
ball_color = {
r: 207,
g: 255,
b: 4
},
R = 2,
balls = [],
alpha_f = 0.03,
alpha_phase = 0,
// Line
link_line_width = 0.8,
dis_limit = 260,
add_mouse_point = true,
mouse_in = false,
mouse_ball = {
x: 0,
y: 0,
vx: 0,
vy: 0,
r: 0,
type: 'mouse'
};
// Random speed
function getRandomSpeed(pos){
var min = -1,
max = 1;
switch(pos){
case 'top':
return [randomNumFrom(min, max), randomNumFrom(0.1, max)];
break;
case 'right':
return [randomNumFrom(min, -0.1), randomNumFrom(min, max)];
break;
case 'bottom':
return [randomNumFrom(min, max), randomNumFrom(min, -0.1)];
break;
case 'left':
return [randomNumFrom(0.1, max), randomNumFrom(min, max)];
break;
default:
return;
break;
}
}
function randomArrayItem(arr){
return arr[Math.floor(Math.random() * arr.length)];
}
function randomNumFrom(min, max){
return Math.random()*(max - min) + min;
}
console.log(randomNumFrom(0, 10));
// Random Ball
function getRandomBall(){
var pos = randomArrayItem(['top', 'right', 'bottom', 'left']);
switch(pos){
case 'top':
return {
x: randomSidePos(can_w),
y: -R,
vx: getRandomSpeed('top')[0],
vy: getRandomSpeed('top')[1],
r: R,
alpha: 1,
phase: randomNumFrom(0, 10)
}
break;
case 'right':
return {
x: can_w + R,
y: randomSidePos(can_h),
vx: getRandomSpeed('right')[0],
vy: getRandomSpeed('right')[1],
r: R,
alpha: 1,
phase: randomNumFrom(0, 10)
}
break;
case 'bottom':
return {
x: randomSidePos(can_w),
y: can_h + R,
vx: getRandomSpeed('bottom')[0],
vy: getRandomSpeed('bottom')[1],
r: R,
alpha: 1,
phase: randomNumFrom(0, 10)
}
break;
case 'left':
return {
x: -R,
y: randomSidePos(can_h),
vx: getRandomSpeed('left')[0],
vy: getRandomSpeed('left')[1],
r: R,
alpha: 1,
phase: randomNumFrom(0, 10)
}
break;
}
}
function randomSidePos(length){
return Math.ceil(Math.random() * length);
}
// Draw Ball
function renderBalls(){
Array.prototype.forEach.call(balls, function(b){
if(!b.hasOwnProperty('type')){
ctx.fillStyle = 'rgba('+ball_color.r+','+ball_color.g+','+ball_color.b+','+b.alpha+')';
ctx.beginPath();
ctx.arc(b.x, b.y, R, 0, Math.PI*2, true);
ctx.closePath();
ctx.fill();
}
});
}
// Update balls
function updateBalls(){
var new_balls = [];
Array.prototype.forEach.call(balls, function(b){
b.x += b.vx;
b.y += b.vy;
if(b.x > -(50) && b.x < (can_w+50) && b.y > -(50) && b.y < (can_h+50)){
new_balls.push(b);
}
// alpha change
b.phase += alpha_f;
b.alpha = Math.abs(Math.cos(b.phase));
// console.log(b.alpha);
});
balls = new_balls.slice(0);
}
// loop alpha
function loopAlphaInf(){
}
// Draw lines
function renderLines(){
var fraction, alpha;
for (var i = 0; i < balls.length; i++) {
for (var j = i + 1; j < balls.length; j++) {
fraction = getDisOf(balls[i], balls[j]) / dis_limit;
if(fraction < 1){
alpha = (1 - fraction).toString();
ctx.strokeStyle = 'rgba(150,150,150,'+alpha+')';
ctx.lineWidth = link_line_width;
ctx.beginPath();
ctx.moveTo(balls[i].x, balls[i].y);
ctx.lineTo(balls[j].x, balls[j].y);
ctx.stroke();
ctx.closePath();
}
}
}
}
// calculate distance between two points
function getDisOf(b1, b2){
var delta_x = Math.abs(b1.x - b2.x),
delta_y = Math.abs(b1.y - b2.y);
return Math.sqrt(delta_x*delta_x + delta_y*delta_y);
}
// add balls if there a little balls
function addBallIfy(){
if(balls.length < 20){
balls.push(getRandomBall());
}
}
// Render
function render(){
ctx.clearRect(0, 0, can_w, can_h);
renderBalls();
renderLines();
updateBalls();
addBallIfy();
window.requestAnimationFrame(render);
}
// Init Balls
function initBalls(num){
for(var i = 1; i <= num; i++){
balls.push({
x: randomSidePos(can_w),
y: randomSidePos(can_h),
vx: getRandomSpeed('top')[0],
vy: getRandomSpeed('top')[1],
r: R,
alpha: 1,
phase: randomNumFrom(0, 10)
});
}
}
// Init Canvas
function initCanvas(){
canvas.setAttribute('width', window.innerWidth);
canvas.setAttribute('height', window.innerHeight);
can_w = parseInt(canvas.getAttribute('width'));
can_h = parseInt(canvas.getAttribute('height'));
}
window.addEventListener('resize', function(e){
console.log('Window Resize...');
initCanvas();
});
function goMovie(){
initCanvas();
initBalls(20);
window.requestAnimationFrame(render);
}
goMovie();
// Mouse effect
canvas.addEventListener('mouseenter', function(){
console.log('mouseenter');
mouse_in = true;
balls.push(mouse_ball);
});
canvas.addEventListener('mouseleave', function(){
console.log('mouseleave');
mouse_in = false;
var new_balls = [];
Array.prototype.forEach.call(balls, function(b){
if(!b.hasOwnProperty('type')){
new_balls.push(b);
}
});
balls = new_balls.slice(0);
});
canvas.addEventListener('mousemove', function(e){
var e = e || window.event;
mouse_ball.x = e.pageX;
mouse_ball.y = e.pageY;
// console.log(mouse_ball);
});
</script>
Since you said, "Chromebook." There's no native support for it as you're asking; without extension.
According to Google's Chromebook Help, they state only .png & .jpg backgrounds.
If you haven't yet, download an image (.png or .jpg) from the web that
you’d like as your wallpaper.
Also, referencing the crosexperts website, it states:
there’s no native support for moving wallpapers, we had to create an
engine — and editor — to make this possible. But, amazingly, it is
possible.
Chrome OS doesn’t support Live Wallpapers in any way.
I'm trying to create a program in WebGL that allows you to draw or create shapes of n-size via keyboard input. The user enters in the number of sides to generate a shape with that many sides. So, if you press '3', you will get a triangle, if you press '4', you will get a square, if you press '5', you will get a pentagon, etc.
So far, I've been able to create seperate pieces of code that create triangles, squares, pentagons, etc. without keyboard input but I'm not sure how to go about generating shapes within the same program with n-sides via user/keyboard input. How would I go about doing this?
Examples of my code so far:
Drawing a triangle:
var VSHADER_SOURCE =
'attribute vec4 a_Position;\n' +
'void main() {\n' +
' gl_Position = a_Position;\n' +
'}\n';
var FSHADER_SOURCE =
'void main() {\n' +
' gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0);\n' +
'}\n';
function main() {
var canvas = document.getElementById('webgl');
var gl = getWebGLContext(canvas);
if (!gl) {
console.log('Failed to get the rendering context for WebGL');
return;
}
if (!initShaders(gl, VSHADER_SOURCE, FSHADER_SOURCE)) {
console.log('Failed to initialize shaders.');
return;
}
var n = initVertexBuffers(gl);
if (n < 0) {
console.log('Failed to set the positions of the vertices');
return;
}
gl.clearColor(0, 0, 0, 0);
gl.clear(gl.COLOR_BUFFER_BIT);
gl.drawArrays(gl.TRIANGLES, 0, n);
}
function initVertexBuffers(gl) {
var vertices = new Float32Array([
0, 0.5, -0.5, -0.5, 0.5, -0.5
]);
var n = 3; // The number of vertices
var vertexBuffer = gl.createBuffer();
if (!vertexBuffer) {
console.log('Failed to create the buffer object');
return -1;
}
gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer);
gl.bufferData(gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW);
var a_Position = gl.getAttribLocation(gl.program, 'a_Position');
if (a_Position < 0) {
console.log('Failed to get the storage location of a_Position');
return -1;
}
gl.vertexAttribPointer(a_Position, 2, gl.FLOAT, false, 0, 0);
gl.enableVertexAttribArray(a_Position);
return n;
}
Drawing a square:
var VSHADER_SOURCE =
'attribute vec4 a_Position;\n' +
'void main() {\n' +
' gl_Position = a_Position;\n' +
'}\n';
var FSHADER_SOURCE =
'void main() {\n' +
' gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0);\n' +
'}\n';
function main() {
var canvas = document.getElementById('webgl');
var gl = getWebGLContext(canvas);
if (!gl) {
console.log('Failed to get the rendering context for WebGL');
return;
}
if (!initShaders(gl, VSHADER_SOURCE, FSHADER_SOURCE)) {
console.log('Failed to initialize shaders.');
return;
}
var n = initVertexBuffers(gl);
if (n < 0) {
console.log('Failed to set the positions of the vertices');
return;
}
gl.clearColor(0, 0, 0, 0);
gl.clear(gl.COLOR_BUFFER_BIT);
gl.drawArrays(gl.TRIANGLE_STRIP, 0, n);
}
function initVertexBuffers(gl) {
var vertices = new Float32Array([
-1, -1, -1, 1, 1, 1, 1, -1, -1, -1,
]);
var n = 5; // The number of vertices
var vertexBuffer = gl.createBuffer();
if (!vertexBuffer) {
console.log('Failed to create the buffer object');
return -1;
}
gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer);
gl.bufferData(gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW);
var a_Position = gl.getAttribLocation(gl.program, 'a_Position');
if (a_Position < 0) {
console.log('Failed to get the storage location of a_Position');
return -1;
}
gl.vertexAttribPointer(a_Position, 2, gl.FLOAT, false, 0, 0);
gl.enableVertexAttribArray(a_Position);
return n;
}
You can start by writing a function computing vertices positions for a polygon with the number of sides as param.
For example, this one computes the polar coordinates of the polygon within a circle of given radius. You can write your own one.
computePolygonPositions(sides, radius)
{
let positions = []
for (let i=0; i<sides; i++)
{
let i0 = i
let i1 = (i+1) % sides
let theta0 = 2.0 * Math.PI * i0 / sides
let theta1 = 2.0 * Math.PI * i1 / sides
let x0 = radius * Math.cos(theta0)
let y0 = radius * Math.cos(theta0)
let x1 = radius * Math.cos(theta1)
let y1 = radius * Math.cos(theta1)
positions.push(0, 0)
positions.push(x0, y0)
positions.push(x1, y1)
}
return positions
}
Of course, you can upgrade this function to add indices, tex coordinates, colors or anything you need.
Once you're done with it, just call it to create a new vertex buffer that you'll bind on ARRAY_BUFFER, set the layout and enable the position attribute.
With stage 3d I set up a basic triangle, and I can use append rotation and append scale and everything works, but using append translation on the z axis, the triangle will dissapear with the translation being 1 or higher. With other shapes it would dissapear with only 3 or higher. And it doesn't look like the triangle is getting any smaller/farther away between 0 and 0.9 translation. The translation on the x and y axis do work though.
Here are my shader codes:
private static const VERTEX_SHADER_SOURCE:String = "m44 op, va0, vc1";
private static const FRAGMENT_SHADER_SOURCE:String = "mov oc, fc0";
my render loop:
addEventListener(Event.ENTER_FRAME, enter);
var t:Number=0;
function enter():void {
context3D.clear();
context3D.setProgram(program);
var m:Matrix3D = new Matrix3D;
m.appendTranslation(0, 0, t);
t+=0.01;
context3D.setProgramConstantsFromMatrix(Context3DProgramType.VERTEX, 1, m, true);
context3D.setVertexBufferAt(0, buffer, 0, Context3DVertexBufferFormat.FLOAT_3);
context3D.setProgramConstantsFromVector(Context3DProgramType.FRAGMENT, 0, color);
context3D.drawTriangles(indexBuffer);
context3D.present();
}
my full code:
var assembler:AGALMiniAssembler = new AGALMiniAssembler();
assembler.assemble(Context3DProgramType.VERTEX, VERTEX_SHADER_SOURCE);
if (assembler.error) {
trace("vertex shader error " +assembler.error);
return;
}
var vertexShaderByteCode:ByteArray = assembler.agalcode;
assembler.assemble(Context3DProgramType.FRAGMENT, FRAGMENT_SHADER_SOURCE);
if (assembler.error) {
trace("fragment shader error " + assembler.error);
return;
}
var fragmentShaderByteCode:ByteArray = assembler.agalcode;
var program:Program3D = context3D.createProgram();
try {
program.upload(vertexShaderByteCode, fragmentShaderByteCode);
}
catch (err:Error) {
trace("couldnt upload shader program" + err);
return;
}
color = new <Number>[0.9296875, 0.9140625, 0.84765625, 1];
var verts:Vector.<Number> = Vector.<Number>([
0.5, 0, 0,
-0.5, 0, 0,
0, 0.5, 0
]);
var buffer:VertexBuffer3D = context3D.createVertexBuffer(3, 3);
buffer.uploadFromVector(verts, 0, 3);
var indices:Vector.<uint> = Vector.<uint>([0, 1, 2])
var indexBuffer:IndexBuffer3D = context3D.createIndexBuffer(3);
indexBuffer.uploadFromVector(indices, 0, 3);
addEventListener(Event.ENTER_FRAME, enter);
var t:Number=0;
function enter():void {
context3D.clear();
context3D.setProgram(program);
var m:Matrix3D = new Matrix3D;
m.appendTranslation(0, 0, t);
t+=0.01;
context3D.setProgramConstantsFromMatrix(Context3DProgramType.VERTEX, 1, m, true);
context3D.setVertexBufferAt(0, buffer, 0, Context3DVertexBufferFormat.FLOAT_3);
context3D.setProgramConstantsFromVector(Context3DProgramType.FRAGMENT, 0, color);
context3D.drawTriangles(indexBuffer);
context3D.present();
}
I am trying to display an animation, in which an avatar moves her both arms. I created the animation on Blender (v2.75) and exported to JSON (r71). The result: the avatar appears on browser, but there is no animation (no movements of arms). Here is the code: jsfiddle and below is the complete code. Can someone help me please?
<html>
<head>
<title>My first Three.js app</title>
<style>
body { margin: 0; }
canvas { width: 100%; height: 100% }
</style>
</head>
<body>
<script src="models/three.js"></script>
<script>
var camera, light, renderer, objeto, animation, helpset, clock, animacao;
var loader;
function init() {
scene = new THREE.Scene();
camera = new THREE.PerspectiveCamera( 75, window.innerWidth/window.innerHeight, 0.1, 1000 );
scene.add( new THREE.AmbientLight( 0x666666 ) );
light = new THREE.DirectionalLight( 0xdfebff, 1.75 );
light.position.set( 50, 200, 100 );
light.position.multiplyScalar( 1.3 );
light.castShadow = true;
//light.shadowCameraVisible = true;
light.shadowMapWidth = 1024;
light.shadowMapHeight = 1024;
var d = 300;
light.shadowCameraLeft = -d;
light.shadowCameraRight = d;
light.shadowCameraTop = d;
light.shadowCameraBottom = -d;
light.shadowCameraFar = 1000;
light.shadowDarkness = 0.5;
scene.add( light );
renderer = new THREE.WebGLRenderer();
renderer.setSize( window.innerWidth, window.innerHeight );
document.body.appendChild( renderer.domElement );
camera.position.z = 5;
clock = new THREE.Clock();
loader = new THREE.JSONLoader();
loader.load( 'models/SL-MD-avatar_erica95.json', addModel );
function addModel( geometry, materials ){
materials[0].skinning = true;
// materials[0].color = "0xb091cc";
var m = new THREE.MeshLambertMaterial(materials);
// console.log(materials[0]);
objeto= new THREE.SkinnedMesh( geometry, m);
objeto.castShadow = true;
objeto.receiveShadow = true;
helpset = new THREE.SkeletonHelper(objeto);
//scene.add(helpset);
// console.log(geometry.animations[0]);
animacao = objeto.geometry.animations[0];
var nome = objeto.geometry.animations[0]["name"];
console.log (nome);
var animation = new THREE.Animation (objeto, animacao);
console.log(animation);
animation.play();
console.log(animation.isPlaying);
scene.add(objeto);
// console.log(animation.data);
}
}
function render() {
delta = 0.75 * clock.getDelta();
scene.traverse(function(child) {
if (child instanceof THREE.SkinnedMesh){
child.rotation.y += .01;
}
});
THREE.AnimationHandler.update( delta );
}
function animate(){
requestAnimationFrame(animate);
render();
renderer.render(scene, camera);
}
init();
animate();
</script>
</body>
</html>
It looks like you have trouble using Blender. You just miss movements for the bones.
Look in the json :
"animations": [
{ // first object in the array (=animations[0])
"length": 2.36, // animation duration
"hierarchy": [{ // hierarchy : defines the keyframes for each bone
"keys": [{ // hierarchy[0] (first bone) : keys = keyframes
"pos": [0, 1.067, 0], // keys[0] at time 0 : defines pos, rot, scl
"rot": [0, 0, 0, 1],
"scl": [1, 1, 1],
"time": 0
}, { // keys[1] at 2.36 (=last keyframe)
"pos": [0, 1.067, 0],
"rot": [0, 0, 0, 1],
"scl": [1, 1, 1], // ! you can see values are identical to
"time": 2.36 // keys[0] ! so this bone won't move
}],
"parent": -1
}, {
.... // same for all hierarchy...
That means the animation is playing but nothing moves. Try to change any value (pos : [0,1.067,0] to pos:[3,5,20] for example) and you will see that the animation is really playing.
In blender you have to assign the movements to each keyframe.
It is almost complete ;)
I am using Chartjs to make line chart.How can I change the y axis labels to colours? (i.e. red for 1, green for 2, black for 3, ..)
UPDATE i've now added this feature into my fork of chartjs at https://github.com/leighquince/Chart.js, meanign you would not have to override or extend a new chart type. Just pass the option in like normal, here is an example http://fiddle.jshell.net/leighking2/jLzvhf4f/
So this could be achieved by overriding the scales draw method to run a custom function we provide when declaring the chart rather than just adding.
Below is the snippet but just as an explanation here is what has happened
created a new chart and overridden the buildScale method to pass a new option called customYLabel. this will be the option you pass to your chart when you declare it and it has 4 parameters; the value of the label, x position, y position, the canvas, this index of the label
the build scale also makes use of a custom scale
create a custom scale which overrides the normal scales draw method to check for this customYLabel option and uses it if present
the reset is normal, what you customYLabel does is up to you but it should at the very least call `ctx.fillText(value,x,y) so that the label is drawn on the canvas. In the below example i colour the label based on it's index but the options there many.
(here is a fiddle as well if thats easier to view http://fiddle.jshell.net/leighking2/2cac5t34/)
//extract helpers so we can use them in our custom scale class
var helpers = Chart.helpers,
each = helpers.each,
aliasPixel = helpers.aliasPixel,
toRadians = helpers.radians;
//new line chart which has an overridden buildscale that will pass the new option customYLabel
Chart.types.Line.extend({
// Passing in a name registers this chart in the Chart namespace in the same way
name: "LineAlt",
initialize: function (data) {
Chart.types.Line.prototype.initialize.apply(this, arguments);
},
buildScale: function (labels) {
var self = this;
var dataTotal = function () {
var values = [];
self.eachPoints(function (point) {
values.push(point.value);
});
return values;
};
var scaleOptions = {
templateString: this.options.scaleLabel,
height: this.chart.height,
width: this.chart.width,
ctx: this.chart.ctx,
textColor: this.options.scaleFontColor,
fontSize: this.options.scaleFontSize,
fontStyle: this.options.scaleFontStyle,
fontFamily: this.options.scaleFontFamily,
valuesCount: labels.length,
beginAtZero: this.options.scaleBeginAtZero,
integersOnly: this.options.scaleIntegersOnly,
//new options for custom y label
customYLabel: this.options.customYLabel,
calculateYRange: function (currentHeight) {
var updatedRanges = helpers.calculateScaleRange(
dataTotal(),
currentHeight,
this.fontSize,
this.beginAtZero,
this.integersOnly);
helpers.extend(this, updatedRanges);
},
xLabels: labels,
font: helpers.fontString(this.options.scaleFontSize, this.options.scaleFontStyle, this.options.scaleFontFamily),
lineWidth: this.options.scaleLineWidth,
lineColor: this.options.scaleLineColor,
showHorizontalLines: this.options.scaleShowHorizontalLines,
showVerticalLines: this.options.scaleShowVerticalLines,
gridLineWidth: (this.options.scaleShowGridLines) ? this.options.scaleGridLineWidth : 0,
gridLineColor: (this.options.scaleShowGridLines) ? this.options.scaleGridLineColor : "rgba(0,0,0,0)",
padding: (this.options.showScale) ? 0 : this.options.pointDotRadius + this.options.pointDotStrokeWidth,
showLabels: this.options.scaleShowLabels,
display: this.options.showScale
};
if (this.options.scaleOverride) {
helpers.extend(scaleOptions, {
calculateYRange: helpers.noop,
steps: this.options.scaleSteps,
stepValue: this.options.scaleStepWidth,
min: this.options.scaleStartValue,
max: this.options.scaleStartValue + (this.options.scaleSteps * this.options.scaleStepWidth)
});
}
this.scale = new Chart.CustomScale(scaleOptions);
},
});
//custom scale to use new customYLabel option
Chart.CustomScale = Chart.Scale.extend({
draw: function () {
var ctx = this.ctx,
yLabelGap = (this.endPoint - this.startPoint) / this.steps,
xStart = Math.round(this.xScalePaddingLeft);
if (this.display) {
ctx.fillStyle = this.textColor;
ctx.font = this.font;
each(this.yLabels, function (labelString, index) {
var yLabelCenter = this.endPoint - (yLabelGap * index),
linePositionY = Math.round(yLabelCenter),
drawHorizontalLine = this.showHorizontalLines;
ctx.textAlign = "right";
ctx.textBaseline = "middle";
if (this.showLabels) {
//if we have a customYLabel use it passing the value, x, y , canvas and index
if (this.customYLabel) {
this.customYLabel(labelString, xStart - 10, yLabelCenter, ctx, index);
} else {
ctx.fillText(labelString, xStart - 10, yLabelCenter);
}
}
// This is X axis, so draw it
if (index === 0 && !drawHorizontalLine) {
drawHorizontalLine = true;
}
if (drawHorizontalLine) {
ctx.beginPath();
}
if (index > 0) {
// This is a grid line in the centre, so drop that
ctx.lineWidth = this.gridLineWidth;
ctx.strokeStyle = this.gridLineColor;
} else {
// This is the first line on the scale
ctx.lineWidth = this.lineWidth;
ctx.strokeStyle = this.lineColor;
}
linePositionY += helpers.aliasPixel(ctx.lineWidth);
if (drawHorizontalLine) {
ctx.moveTo(xStart, linePositionY);
ctx.lineTo(this.width, linePositionY);
ctx.stroke();
ctx.closePath();
}
ctx.lineWidth = this.lineWidth;
ctx.strokeStyle = this.lineColor;
ctx.beginPath();
ctx.moveTo(xStart - 5, linePositionY);
ctx.lineTo(xStart, linePositionY);
ctx.stroke();
ctx.closePath();
}, this);
each(this.xLabels, function (label, index) {
var xPos = this.calculateX(index) + aliasPixel(this.lineWidth),
// Check to see if line/bar here and decide where to place the line
linePos = this.calculateX(index - (this.offsetGridLines ? 0.5 : 0)) + aliasPixel(this.lineWidth),
isRotated = (this.xLabelRotation > 0),
drawVerticalLine = this.showVerticalLines;
// This is Y axis, so draw it
if (index === 0 && !drawVerticalLine) {
drawVerticalLine = true;
}
if (drawVerticalLine) {
ctx.beginPath();
}
if (index > 0) {
// This is a grid line in the centre, so drop that
ctx.lineWidth = this.gridLineWidth;
ctx.strokeStyle = this.gridLineColor;
} else {
// This is the first line on the scale
ctx.lineWidth = this.lineWidth;
ctx.strokeStyle = this.lineColor;
}
if (drawVerticalLine) {
ctx.moveTo(linePos, this.endPoint);
ctx.lineTo(linePos, this.startPoint - 3);
ctx.stroke();
ctx.closePath();
}
ctx.lineWidth = this.lineWidth;
ctx.strokeStyle = this.lineColor;
// Small lines at the bottom of the base grid line
ctx.beginPath();
ctx.moveTo(linePos, this.endPoint);
ctx.lineTo(linePos, this.endPoint + 5);
ctx.stroke();
ctx.closePath();
ctx.save();
ctx.translate(xPos, (isRotated) ? this.endPoint + 12 : this.endPoint + 8);
ctx.rotate(toRadians(this.xLabelRotation) * -1);
ctx.font = this.font;
ctx.textAlign = (isRotated) ? "right" : "center";
ctx.textBaseline = (isRotated) ? "middle" : "top";
ctx.fillText(label, 0, 0);
ctx.restore();
}, this);
}
}
});
var randomScalingFactor = function () {
return Math.round(Math.random() * 100)
};
//example colour generator from
//https://www.designedbyaturtle.co.uk/2014/convert-string-to-hexidecimal-colour-with-javascript-vanilla/
// Convert an int to hexadecimal with a max length
// of six characters.
var intToARGB = function (i) {
var h = ((i >> 24) & 0xFF).toString(16) + ((i >> 16) & 0xFF).toString(16) + ((i >> 8) & 0xFF).toString(16) + (i & 0xFF).toString(16);
return h.substring(0, 6);
}
var lineChartData = {
labels: ["January", "February", "March", "April", "May", "June", "July"],
datasets: [{
label: "My First dataset",
fillColor: "rgba(220,220,220,0.2)",
strokeColor: "rgba(220,220,220,1)",
pointColor: "rgba(220,220,220,1)",
pointStrokeColor: "#fff",
pointHighlightFill: "#fff",
pointHighlightStroke: "rgba(220,220,220,1)",
data: [randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor()]
}, {
label: "My Second dataset",
fillColor: "rgba(151,187,205,0.2)",
strokeColor: "rgba(151,187,205,1)",
pointColor: "rgba(151,187,205,1)",
pointStrokeColor: "#fff",
pointHighlightFill: "#fff",
pointHighlightStroke: "rgba(151,187,205,1)",
data: [null, 10, null, null, 60, null, null]
}]
}
var ctx = document.getElementById("canvas").getContext("2d");
window.myLine = new Chart(ctx).LineAlt(lineChartData, {
//example of how this can be used, could use the value instead of the index
customYLabel: function (value, x, y, ctx, index) {
var defaultStyle = ctx.fillStyle;
ctx.fillStyle = '#' + intToARGB(index * 123456);
ctx.fillText(value, x, y);
ctx.fillStyle = defaultStyle;
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/1.0.1/Chart.js"></script>
<div style="width:100%">
<div>
<canvas id="canvas" height="200" width="600"></canvas>
</div>
</div>