Raycaster didn't detect the whole geometry in threejs - javascript

function checkCollisiontofloor() {
var cube = scene.getObjectByName('floor');
var originPoint = cube.position.clone();
for (var vertexIndex = 0; vertexIndex < cube.geometry.vertices.length; vertexIndex++) {
var localVertex = cube.geometry.vertices[vertexIndex].clone();
var globalVertex = localVertex.applyMatrix4(cube.matrix);
var directionVector = globalVertex.sub(cube.position);
var ray = new THREE.Raycaster(originPoint, directionVector.clone().normalize());
var collisionResults = ray.intersectObjects(cubearr);
if (collisionResults.length > 0 && collisionResults[0].distance < directionVector.length()) {
limit++;
console.log(limit);
collisionResults[0].object.visible = false;
if (limit == num)
{
createCubes(num+=5);
level++;
var l = "level";
var final = (l + " " + level);
console.log (final);
document.getElementById("Level").innerHTML = final;
speed+= 0.1;
}
}
}
}
The Whole Code
<canvas id="scene"></canvas>
<script src="lib/three.min.js"></script>
<script src="lib/OrbitControls.js"></script>
<html>
<style>
#myText2
{
font-weight: bolder;
font-size: 30px;
}
.buttons
{
position: fixed;
top: 20px;
}
</style>
<body>
<div class="buttons">
<label style="color:red;"><span id="myText2"></span></label>
<h1>Score: <span id="myText"></span></h1>
<h1> <span id="Level"></span></h1>
</div>
<script>
var ww = 1500,
wh = 500;
var scene;
var k=0.02;
var Up=60;
var count=0;
var flag = true;
var speed=0.4;
var cubearr = [];
var num = 10;
var max=48 , min=-48;
var limit = 0;
var level = 1;
function init()
{
renderer = new THREE.WebGLRenderer({antialias:true});
renderer.setSize(ww, wh);
renderer.setClearColor(0xFFFFFF, 1);
document.body.appendChild(renderer.domElement);
scene = new THREE.Scene();
camera = new THREE.PerspectiveCamera(40, ww/wh,1,1000);
camera.position.z = 100;
camera.position.y = 5;
camera.name = 'cam';
camera.lookAt(new THREE.Vector3(0,0,0));
scene.add(camera);
light = new THREE.PointLight( 0xFFFFFF, 1, 10000 );
light.position.set( 0, 20, 50 );
light.name = 'light';
scene.add( light );
text();
createCubes(num);
window.addEventListener("keydown", moveSphere);
dir();
renderer.render(scene,camera);
};
function text()
{
//THREE.ImageUtils.crossOrigin = '';
elements = new THREE.Object3D();
loader = new THREE.CubeTextureLoader();
loader.setPath( 'C:/xampp/htdocs/graphics/' );
// Create sphere
sphereG = new THREE.SphereGeometry(4, 100, 100, 0, Math.PI * 2, 0, Math.PI * 2);
spherem = new THREE.MeshLambertMaterial({color: 0xff2255});
texture2 = new THREE.TextureLoader().load('spheretex.jpg');
material2 = new THREE.MeshBasicMaterial( { map: texture2 } );
sphere = new THREE.Mesh(sphereG, material2);
sphere.position.y = -13;
sphere.name = 'sp';
elements.add(sphere);
//Create floor
planeG = new THREE.BoxGeometry( 100, 5, 10 );
material = new THREE.MeshBasicMaterial( {color: 0x00ff00} );
texture1 = new THREE.TextureLoader().load('texturefloor.jpg');
texture1.wrapS = THREE.RepeatWrapping;
texture1.wrapT = THREE.RepeatWrapping;
texture1.repeat.set( 100, 10 );
material1 = new THREE.MeshBasicMaterial( { map: texture1 } );
//texture msh shaghl fa hatet material bas msh material1 3ashn ahtulu color
floor= new THREE.Mesh( planeG, material1 );
floor.position.y = -20;
floor.name = ("floor");
elements.add(floor);
scene.add(elements);
//renderer.render(scene,camera);
};
function createCubes(x)
{
document.getElementById("Level").innerHTML = "Level 1";
geometry2 = new THREE.BoxGeometry(5,5,5);
texture = new THREE.TextureLoader().load( '25649.jpg' );
materialtex = new THREE.MeshBasicMaterial( { map: texture } );
for (let i = 0; i < x; i++)
{
cubearr[i] = new THREE.Mesh(geometry2, materialtex);
cubearr[i].position.x =(Math.random() * (max - min)) + min;
cubearr[i].position.y = Up;
Up = Up+10;
scene.add(cubearr[i]);
//cubes.push(cubearr[i]);
}
renderer.render(scene,camera);
}
function dir()
{
var s = scene.getObjectByName("sp");
if (flag == false)
{
return;
}
requestAnimationFrame(dir);
sphere.position.y +=speed;
camera.position.y +=speed;
floor.position.y+=speed;
checkCollisiontosphere();
checkCollisiontofloor();
renderer.render(scene, camera);
}
function moveSphere(e)
{
moveDistance = 0.30;
sp = scene.getObjectByName('sp');
cam = scene.getObjectByName('cam');
light = scene.getObjectByName('light');
if (e.keyCode == '39')
{
if(sp.position.x < 48)
{
sp.rotation.z -= moveDistance;
sp.position.x += 3;
sp.rotation.x += 3;
light.position.x += 3;
count++;
document.getElementById("myText").innerHTML = count;
}
}
else if (e.keyCode == '37')
{
if(sp.position.x > -48)
{
sp.rotation.z += moveDistance;
sp.position.x-= 3;
sp.rotation.x -= 3;
light.position.x -= 3;
count++;
document.getElementById("myText").innerHTML = count;
}
}
else if(e.keyCode == '27')
{
if (flag)
{
flag = false;
}
else
{
flag = true;
dir();
}
}
};
window.addEventListener("keydown", moveSphere);
function checkCollisiontosphere() {
var cube = scene.getObjectByName('sp');
var originPoint = cube.position.clone();
for (var vertexIndex = 0; vertexIndex < cube.geometry.vertices.length; vertexIndex++) {
var localVertex = cube.geometry.vertices[vertexIndex].clone();
var globalVertex = localVertex.applyMatrix4(cube.matrix);
var directionVector = globalVertex.sub(cube.position);
var ray = new THREE.Raycaster(originPoint, directionVector.clone().normalize());
var collisionResults = ray.intersectObjects(cubearr);
if (collisionResults.length > 0 && collisionResults[0].distance < directionVector.length()) {
document.getElementById("myText2").innerHTML = "GAME OVER";
flag=false }
}
}
function checkCollisiontofloor() {
var cube = scene.getObjectByName('floor');
var originPoint = cube.position.clone();
for (var vertexIndex = 0; vertexIndex < cube.geometry.vertices.length; vertexIndex++) {
var localVertex = cube.geometry.vertices[vertexIndex].clone();
var globalVertex = localVertex.applyMatrix4(cube.matrix);
var directionVector = globalVertex.sub(cube.position);
var ray = new THREE.Raycaster(originPoint, directionVector.clone().normalize());
var collisionResults = ray.intersectObjects(cubearr);
if (collisionResults.length > 0 && collisionResults[0].distance < directionVector.length()) {
limit++;
console.log(limit);
collisionResults[0].object.visible = false;
if (limit == num)
{
createCubes(num+=5);
level++;
var l = "level";
var final = (l + " " + level);
console.log (final);
document.getElementById("Level").innerHTML = final;
speed+= 0.1;
}
}
}
}
function levels()
{
if(count == 30)
{
document.getElementById("Level").innerHTML = "Level 2";
speed=0.6;
}
if(count == 60)
{
document.getElementById("Level").innerHTML = "Level 3";
speed=0.8;
}
if(count == 90)
{
document.getElementById("Level").innerHTML = "Level 4";
speed=1;
}
}
init();
</script>
</body>
</html>

Related

Data does not update in firebase

so I have been working on a piano game where two people compete against each other and press notes as fast as they can. The game should end when one of the players reaches a certain score, but the database is not updating the game state.
sketch.js
var playercount = 0;
var player;
var database;
var playerIndex = null;
var gamestate = 0;
var game;
var wkey;
var bkey;
var cKey
var dKey
var eKey
var fKey
var gKey
var aKey
var bKey
var csKey
var dsKey
var gsKey
var fsKey
var asKey
var cstate = true;
var dstate = true;
var estate = true;
var fstate = true;
var gstate = true;
var astate = true;
var bstate = true;
var csstate = true;
var dsstate = true;
var fsstate = true;
var gsstate = true;
var asstate = true;
var form;
//var arr = ["C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A"]
function preload() {
//wkey = loadImage("wkey.png");
// bkey = loadImage("bkey.png");
cKey = loadImage("C.png")
dKey = loadImage("D.png")
eKey = loadImage("E.png")
fKey = loadImage("F.png")
gKey = loadImage("G.png")
aKey = loadImage("A.png")
bKey = loadImage("B.png")
csKey = loadImage("Csharp.png")
dsKey = loadImage("Dsharp.png")
gsKey = loadImage("Gsharp.png")
fsKey = loadImage("Fsharp.png")
asKey = loadImage("Asharp.png")
}
function setup() {
createCanvas(windowWidth,windowHeight);
database = firebase.database();
form = new Form();
form.display();
player = new Player();
player.getCount();
game = new Game();
game.getState();
}
function draw() {
background("white");
if(playercount == 2){
game.updateState(1);
}
if(gamestate == 1){
game.start();
}
if(player.score == 10) {
game.updateState(2);
}
if(gamestate == 2){
game.end();
}
drawSprites();
}
game.js
class Game {
constructor() {
}
start() {
form.title.hide();
var resetButton = createSprite(1000, 200, 50, 50);
if(mousePressedOver(resetButton)){
console.log("hi")
database.ref("/").set({
playerCount: 0,
gameState: 0,
players: {},
});
window.location.reload();
}
var C = createSprite(width/2-600, height/2, 100, 400);
C.shapeColor = "grey";
var D = createSprite(width/2-495, height/2, 100, 400);
D.shapeColor = "grey";
var E = createSprite(width/2-390, height/2, 100, 400);
E.shapeColor = "grey";
var F = createSprite(width/2-285, height/2, 100, 400);
F.shapeColor = "grey";
var G = createSprite(width/2-180, height/2, 100, 400);
G.shapeColor = "grey";
var A = createSprite(width/2-75, height/2, 100, 400);
A.shapeColor = "grey";
var B = createSprite(width/2+30, height/2, 100, 400);
B.shapeColor = "grey";
var Cs = createSprite(width/2-550, height/2-100, 50, 200);
Cs.shapeColor = "black";
var Ds = createSprite(width/2-445, height/2-100, 50, 200);
Ds.shapeColor = "black";
//var Es = createSprite(width/2-340, height/2-100, 50, 200);
// Es.shapeColor = "black";
var Fs = createSprite(width/2-235, height/2-100, 50, 200);
Fs.shapeColor = "black";
var Gs = createSprite(width/2-130, height/2-100, 50, 200);
Gs.shapeColor = "black";
var As = createSprite(width/2-25, height/2-100, 50, 200);
As.shapeColor = "black";
var c = new Notes(100, 40, 20, 20, cKey);
var d = new Notes(150, 40, 20, 20, dKey);
var e = new Notes(200, 40, 20, 20, eKey);
var f = new Notes(250, 40, 20, 20, fKey);
var g = new Notes(300, 40, 20, 20, gKey);
var a = new Notes(350, 40, 20, 20, aKey);
var b = new Notes(400, 40, 20, 20, bKey);
var cs = new Notes(450, 40, 20, 20, csKey);
var ds = new Notes(500, 40, 20, 20, dsKey);
var fs = new Notes(550, 40, 20, 20, fsKey);
var gs = new Notes(600, 40, 20, 20, gsKey);
var as = new Notes(200, 40, 20, 20, asKey);
var r1 = Math.round(random(90, 100))
var r2 = Math.round(random(70, 100))
var r3 = Math.round(random(80, 150))
var r4 = Math.round(random(90, 120))
var r5 = Math.round(random(83, 110))
var r6 = Math.round(random(100, 130))
var r7 = Math.round(random(95, 125))
var r8 = Math.round(random(77, 109))
var r9 = Math.round(random(101, 111))
var r10 = Math.round(random(95, 120))
var r11 = Math.round(random(80, 170))
var r12 = Math.round(random(100, 130))
if(frameCount%r1 ===0){
cstate = true
}
if(frameCount%r2 === 0){
dstate= true
}
if(frameCount%r3 === 0){
estate= true
}
if(frameCount%r4 === 0){
fstate= true
}
if(frameCount%r5 === 0){
gstate= true
}
if(frameCount%r6 === 0){
astate= true
}
if(frameCount%r7 === 0){
bstate= true
}
if(frameCount%r8 === 0){
csstate= true
}
if(frameCount%r9 === 0){
dsstate= true
}
if(frameCount%r10 === 0){
fsstate= true
}
if(frameCount%r11 === 0){
gsstate= true
}
if(frameCount%r12 === 0){
asstate= true
}
if(cstate === true){
c.display();
}
if(dstate === true){
d.display();
}
if(estate === true){
e.display();
}
if(fstate === true){
f.display();
}
if(gstate === true){
g.display();
}
if(astate === true){
a.display();
}
if(bstate === true){
b.display();
}
if(csstate === true){
cs.display();
}
if(dsstate === true){
ds.display();
}
if(fsstate === true){
fs.display();
}
if(gsstate === true){
gs.display();
}
if(asstate === true){
as.display();
}
if(mousePressedOver(C)&& cstate){
cstate = false;
C.shapeColor = "green";
player.score += 1;
}
if(mousePressedOver(D)&& dstate){
dstate = false;
D.shapeColor = "green";
player.score += 1;
}
if(mousePressedOver(E)&& estate){
estate = false;
E.shapeColor = "green";
player.score += 1;
}
if(mousePressedOver(F)&& fstate){
fstate = false;
F.shapeColor = "green";
player.score += 1;
}
if(mousePressedOver(G)&& gstate){
gstate = false;
G.shapeColor = "green";
player.score += 1;
}
if(mousePressedOver(A)&& astate){
astate = false;
A.shapeColor = "green";
player.score += 1;
}
if(mousePressedOver(B)&& bstate){
bstate = false;
B.shapeColor = "green";
player.score += 1;
}
if(mousePressedOver(Cs)&& cstate){
csstate = false;
Cs.shapeColor = "green";
player.score += 1;
}
if(mousePressedOver(Ds)&& dsstate){
dsstate = false;
Ds.shapeColor = "green";
player.score += 1;
}
if(mousePressedOver(Fs)&& fsstate){
fsstate = false;
Fs.shapeColor = "green";
player.score += 1;
}
if(mousePressedOver(Gs)&& gsstate){
gsstate = false;
Gs.shapeColor = "green";
player.score += 1;
}
if(mousePressedOver(As)&& asstate){
asstate = false;
As.shapeColor = "green";
player.score += 1;
}
player.updateScore(player.score);
text("score: "+player.score, 650, 40)
console.log(player.score)
}
getState() {
database.ref("gameState").on("value", (data)=>{
gamestate = data.val()
})
}
updateState(state) {
database.ref("/").update({
gameState : state
})
}
end() {
console.log("its the end of the game")
if(player.score >= 10 ){
text("you won", 900, height/2,)
} else {
text("you lost", 900, height/2)
}
}
}
player.js
class Player {
constructor() {
this.score = 0;
this.name = null;
this.index = null;
}
addPlayer() {
var playerIndex = "players/player" + this.index;
database.ref(playerIndex).set({
score : this.score,
name : this.name,
index : this.index,
})
}
getCount() {
database.ref("playerCount").on("value", (data) =>{
playercount = data.val()
})
}
updateCount(count) {
database.ref("/").update({playerCount : count})
}
updateScore(newScore) {
database.ref("players/player" + this.index).update({
score : newScore,
})
}
}
I tried seeing if there was a problem in my function to see why it was not updating in the database.

Drag object around a circle on mouse over - Adobe Animate/Create.js/Easel.js

Using Adobe Animate HTML5 Canvas which employs Create.js/Easel.js.
I have the following code which drags an object around a circle.
Works Ok, but the object should only be moveable when the cursor is over the object; object being streakRotatorKnob.
var knob_X = 454;
var knob_Y = 175;
var radius = 80;
root.streakRotatorKnob.addEventListener("pressmove",moveF.bind(this));
function moveF(e){
var rads = Math.atan2(stage.mouseY-knob_Y,stage.mouseX-knob_X);
e.currentTarget.x = knob_X + radius * Math.cos(rads);
e.currentTarget.y = knob_Y + radius * Math.sin(rads);
stage.update();
}
I have tried the following but it's not working at all with the if statement:
var knob_X = 454;
var knob_Y = 175;
var radius = 80;
root.streakRotatorKnob.addEventListener("pressmove",moveF.bind(this));
function moveF(e){
if(stage.mouseY == root.streakRotatorKnob.y && stage.mouseX == root.streakRotatorKnob.x){
var rads = Math.atan2(stage.mouseY-knob_Y,stage.mouseX-knob_X);
e.currentTarget.x = knob_X + radius * Math.cos(rads);
e.currentTarget.y = knob_Y + radius * Math.sin(rads);
stage.update();
}
}
UPDATE
Based on Muhammed Maruf's answer below (the Adobe Animate version), the following works better by removing the line:
root.c.addEventListener("rollout", rollout);
So we just have:
stage.enableMouseOver();
var knob_X = 454;
var knob_Y = 169;
var radius = 90;
var root = this;
root.c.addEventListener("rollover", rollover);
//root.c.addEventListener("rollout", rollout);
function rollover(e)
{
console.log("rollover")
root.c.addEventListener("pressmove", moveF);
}
function rollout(e)
{
console.log("rollout")
root.c.removeEventListener("pressmove", moveF);
}
function moveF(e)
{
var rads = Math.atan2(stage.mouseY - knob_Y, stage.mouseX - knob_X);
e.currentTarget.x = knob_X + radius * Math.cos(rads);
e.currentTarget.y = knob_Y + radius * Math.sin(rads);
stage.update();
}
This is how I edited the code. I think you meant that.
stage.enableMouseOver();
var knob_X = canvas.width/2;
var knob_Y = canvas.height/2;
var radius = 90;
var root = this;
root.streakRotatorKnob.addEventListener("rollover", rollover);
root.streakRotatorKnob.addEventListener("rollout", rollout);
function rollover(e)
{
console.log("rollover")
root.streakRotatorKnob.addEventListener("pressmove", moveF);
}
function rollout(e)
{
console.log("rollout")
root.streakRotatorKnob.removeEventListener("pressmove", moveF);
}
function moveF(e)
{
var rads = Math.atan2(stage.mouseY - knob_Y, stage.mouseX - knob_X);
e.currentTarget.x = knob_X + radius * Math.cos(rads);
e.currentTarget.y = knob_Y + radius * Math.sin(rads);
stage.update();
}
(function (cjs, an) {
var p; // shortcut to reference prototypes
var lib={};var ss={};var img={};
lib.ssMetadata = [];
(lib.AnMovieClip = function(){
this.actionFrames = [];
this.ignorePause = false;
this.gotoAndPlay = function(positionOrLabel){
cjs.MovieClip.prototype.gotoAndPlay.call(this,positionOrLabel);
}
this.play = function(){
cjs.MovieClip.prototype.play.call(this);
}
this.gotoAndStop = function(positionOrLabel){
cjs.MovieClip.prototype.gotoAndStop.call(this,positionOrLabel);
}
this.stop = function(){
cjs.MovieClip.prototype.stop.call(this);
}
}).prototype = p = new cjs.MovieClip();
// symbols:
// helper functions:
function mc_symbol_clone() {
var clone = this._cloneProps(new this.constructor(this.mode, this.startPosition, this.loop, this.reversed));
clone.gotoAndStop(this.currentFrame);
clone.paused = this.paused;
clone.framerate = this.framerate;
return clone;
}
function getMCSymbolPrototype(symbol, nominalBounds, frameBounds) {
var prototype = cjs.extend(symbol, cjs.MovieClip);
prototype.clone = mc_symbol_clone;
prototype.nominalBounds = nominalBounds;
prototype.frameBounds = frameBounds;
return prototype;
}
(lib.Sembol1 = function(mode,startPosition,loop,reversed) {
if (loop == null) { loop = true; }
if (reversed == null) { reversed = false; }
var props = new Object();
props.mode = mode;
props.startPosition = startPosition;
props.labels = {};
props.loop = loop;
props.reversed = reversed;
cjs.MovieClip.apply(this,[props]);
// Katman_1
this.shape = new cjs.Shape();
this.shape.graphics.f("#000000").s().p("AhuBuQgtguAAhAQAAg/AtguQAvguA/AAQBBAAAtAuQAuAuAAA/QAABAguAuQgtAuhBAAQg/AAgvgug");
this.timeline.addTween(cjs.Tween.get(this.shape).wait(1));
this._renderFirstFrame();
}).prototype = getMCSymbolPrototype(lib.Sembol1, new cjs.Rectangle(-15.6,-15.6,31.2,31.2), null);
// stage content:
(lib.index = function(mode,startPosition,loop,reversed) {
if (loop == null) { loop = true; }
if (reversed == null) { reversed = false; }
var props = new Object();
props.mode = mode;
props.startPosition = startPosition;
props.labels = {};
props.loop = loop;
props.reversed = reversed;
cjs.MovieClip.apply(this,[props]);
this.actionFrames = [0];
this.isSingleFrame = false;
// timeline functions:
this.frame_0 = function() {
if(this.isSingleFrame) {
return;
}
if(this.totalFrames == 1) {
this.isSingleFrame = true;
}
stage.enableMouseOver();
var knob_X = canvas.width/2;
var knob_Y = canvas.height/2;
var radius = 90;
var root = this;
root.streakRotatorKnob.addEventListener("rollover", rollover);
root.streakRotatorKnob.addEventListener("rollout", rollout);
function rollover(e)
{
console.log("rollover")
root.streakRotatorKnob.addEventListener("pressmove", moveF);
}
function rollout(e)
{
console.log("rollout")
root.streakRotatorKnob.removeEventListener("pressmove", moveF);
}
function moveF(e)
{
var rads = Math.atan2(stage.mouseY - knob_Y, stage.mouseX - knob_X);
e.currentTarget.x = knob_X + radius * Math.cos(rads);
e.currentTarget.y = knob_Y + radius * Math.sin(rads);
stage.update();
}
}
// actions tween:
this.timeline.addTween(cjs.Tween.get(this).call(this.frame_0).wait(1));
// Katman_1
this.streakRotatorKnob = new lib.Sembol1();
this.streakRotatorKnob.name = "streakRotatorKnob";
this.streakRotatorKnob.setTransform(207.8,131.8);
this.timeline.addTween(cjs.Tween.get(this.streakRotatorKnob).wait(1));
this._renderFirstFrame();
}).prototype = p = new lib.AnMovieClip();
p.nominalBounds = new cjs.Rectangle(467.2,316.2,-243.79999999999998,-168.79999999999998);
// library properties:
lib.properties = {
id: '214D9CE6C84FD84795816AF703BF00E4',
width: 550,
height: 400,
fps: 24,
color: "#CCCCCC",
opacity: 1.00,
manifest: [],
preloads: []
};
// bootstrap callback support:
(lib.Stage = function(canvas) {
createjs.Stage.call(this, canvas);
}).prototype = p = new createjs.Stage();
p.setAutoPlay = function(autoPlay) {
this.tickEnabled = autoPlay;
}
p.play = function() { this.tickEnabled = true; this.getChildAt(0).gotoAndPlay(this.getTimelinePosition()) }
p.stop = function(ms) { if(ms) this.seek(ms); this.tickEnabled = false; }
p.seek = function(ms) { this.tickEnabled = true; this.getChildAt(0).gotoAndStop(lib.properties.fps * ms / 1000); }
p.getDuration = function() { return this.getChildAt(0).totalFrames / lib.properties.fps * 1000; }
p.getTimelinePosition = function() { return this.getChildAt(0).currentFrame / lib.properties.fps * 1000; }
an.bootcompsLoaded = an.bootcompsLoaded || [];
if(!an.bootstrapListeners) {
an.bootstrapListeners=[];
}
an.bootstrapCallback=function(fnCallback) {
an.bootstrapListeners.push(fnCallback);
if(an.bootcompsLoaded.length > 0) {
for(var i=0; i<an.bootcompsLoaded.length; ++i) {
fnCallback(an.bootcompsLoaded[i]);
}
}
};
an.compositions = an.compositions || {};
an.compositions['214D9CE6C84FD84795816AF703BF00E4'] = {
getStage: function() { return exportRoot.stage; },
getLibrary: function() { return lib; },
getSpriteSheet: function() { return ss; },
getImages: function() { return img; }
};
an.compositionLoaded = function(id) {
an.bootcompsLoaded.push(id);
for(var j=0; j<an.bootstrapListeners.length; j++) {
an.bootstrapListeners[j](id);
}
}
an.getComposition = function(id) {
return an.compositions[id];
}
an.makeResponsive = function(isResp, respDim, isScale, scaleType, domContainers) {
var lastW, lastH, lastS=1;
window.addEventListener('resize', resizeCanvas);
resizeCanvas();
function resizeCanvas() {
var w = lib.properties.width, h = lib.properties.height;
var iw = window.innerWidth, ih=window.innerHeight;
var pRatio = window.devicePixelRatio || 1, xRatio=iw/w, yRatio=ih/h, sRatio=1;
if(isResp) {
if((respDim=='width'&&lastW==iw) || (respDim=='height'&&lastH==ih)) {
sRatio = lastS;
}
else if(!isScale) {
if(iw<w || ih<h)
sRatio = Math.min(xRatio, yRatio);
}
else if(scaleType==1) {
sRatio = Math.min(xRatio, yRatio);
}
else if(scaleType==2) {
sRatio = Math.max(xRatio, yRatio);
}
}
domContainers[0].width = w * pRatio * sRatio;
domContainers[0].height = h * pRatio * sRatio;
domContainers.forEach(function(container) {
container.style.width = w * sRatio + 'px';
container.style.height = h * sRatio + 'px';
});
stage.scaleX = pRatio*sRatio;
stage.scaleY = pRatio*sRatio;
lastW = iw; lastH = ih; lastS = sRatio;
stage.tickOnUpdate = false;
stage.update();
stage.tickOnUpdate = true;
}
}
an.handleSoundStreamOnTick = function(event) {
if(!event.paused){
var stageChild = stage.getChildAt(0);
if(!stageChild.paused || stageChild.ignorePause){
stageChild.syncStreamSounds();
}
}
}
an.handleFilterCache = function(event) {
if(!event.paused){
var target = event.target;
if(target){
if(target.filterCacheList){
for(var index = 0; index < target.filterCacheList.length ; index++){
var cacheInst = target.filterCacheList[index];
if((cacheInst.startFrame <= target.currentFrame) && (target.currentFrame <= cacheInst.endFrame)){
cacheInst.instance.cache(cacheInst.x, cacheInst.y, cacheInst.w, cacheInst.h);
}
}
}
}
}
}
})(createjs = createjs||{}, AdobeAn = AdobeAn||{});
var createjs, AdobeAn;
<!DOCTYPE html>
<!--
NOTES:
1. All tokens are represented by '$' sign in the template.
2. You can write your code only wherever mentioned.
3. All occurrences of existing tokens will be replaced by their appropriate values.
4. Blank lines will be removed automatically.
5. Remove unnecessary comments before creating your template.
-->
<html>
<head>
<meta charset="UTF-8">
<meta name="authoring-tool" content="Adobe_Animate_CC">
<title>index</title>
<!-- write your code here -->
<script src="https://code.createjs.com/1.0.0/createjs.min.js"></script>
<script src="index.js"></script>
<script>
var canvas, stage, exportRoot, anim_container, dom_overlay_container, fnStartAnimation;
function init() {
canvas = document.getElementById("canvas");
anim_container = document.getElementById("animation_container");
dom_overlay_container = document.getElementById("dom_overlay_container");
var comp=AdobeAn.getComposition("214D9CE6C84FD84795816AF703BF00E4");
var lib=comp.getLibrary();
handleComplete({},comp);
}
function handleComplete(evt,comp) {
//This function is always called, irrespective of the content. You can use the variable "stage" after it is created in token create_stage.
var lib=comp.getLibrary();
var ss=comp.getSpriteSheet();
exportRoot = new lib.index();
stage = new lib.Stage(canvas);
//Registers the "tick" event listener.
fnStartAnimation = function() {
stage.addChild(exportRoot);
createjs.Ticker.framerate = lib.properties.fps;
createjs.Ticker.addEventListener("tick", stage);
}
//Code to support hidpi screens and responsive scaling.
AdobeAn.makeResponsive(false,'both',false,1,[canvas,anim_container,dom_overlay_container]);
AdobeAn.compositionLoaded(lib.properties.id);
fnStartAnimation();
}
</script>
<!-- write your code here -->
</head>
<body onload="init();" style="margin:0px;">
<div id="animation_container" style="background-color:rgba(204, 204, 204, 1.00); width:550px; height:400px">
<canvas id="canvas" width="550" height="400" style="position: absolute; display: block; background-color:rgba(204, 204, 204, 1.00);"></canvas>
<div id="dom_overlay_container" style="pointer-events:none; overflow:hidden; width:550px; height:400px; position: absolute; left: 0px; top: 0px; display: block;">
</div>
</div>
</body>
</html>
I just saw what you wrote because of the time difference.
Let me answer your last comment as follows. In the example I posted, I averaged over the canvas. While you are giving the starting position, you need to enter the initial position information as if you were rotating it. I also solved a problem with Mac devices. The example should be:
stage.enableMouseOver();
var knob_X = canvas.width/2/stage.scaleX;
var knob_Y = canvas.height/2/stage.scaleY;
var radius = 90;
var root = this;
var rads = Math.atan2(1-knob_Y,1-knob_X);
root.streakRotatorKnob.x = knob_X + radius * Math.cos(rads);
root.streakRotatorKnob.y = knob_Y + radius * Math.sin(rads);
root.streakRotatorKnob.addEventListener("rollover", rollover);
root.streakRotatorKnob.addEventListener("rollout", rollout);
function rollover(e)
{
console.log("rollover")
root.streakRotatorKnob.addEventListener("pressmove", moveF);
}
function rollout(e)
{
console.log("rollout")
root.streakRotatorKnob.removeEventListener("pressmove", moveF);
}
function moveF(e)
{
var rads = Math.atan2(stage.mouseY/stage.scaleY - knob_Y, stage.mouseX/stage.scaleX - knob_X);
e.currentTarget.x = knob_X + radius * Math.cos(rads);
e.currentTarget.y = knob_Y + radius * Math.sin(rads);
stage.update();
}

three.js how to make texture "generated" texture coordinate, like blender cycles

I'm trying to display a texture onto a cylinder object in THREE.js, and I want to texture to show up on the cylinder in a well... not so distorted way, here's how it looks now:
and that is just based off this simple texture:
I don't want it to be distorted / stretched along the edges of the cylinder, I would like it to look something like the "generated" texture coordinate in blender cycles:
(notice the "box" setting in the image texture)
SOOO I have no idea how to set the texture coordinates in THREE.js ... ?
EDIT::: There's been a request for the actual source code, so here it is (even though it's complicated):
var COBY = new (function() {
this.p = Processing;
this.t=THREE;
this.mouseX = 0;
this.mouseY = 0;
this.Keyboard = new (function() {
this.keysDown = [];
for(var i = 0; i < 200; i++) {
this.keysDown[i] = false;
}
this.RIGHT = 39;
this.LEFT = 37;
this.UP = 38;
this.DOWN = 40;
this.setKeyDown = function(key) {
COBY.Keyboard.keysDown[key] = true;
};
this.setKeyUp = function(key) {
COBY.Keyboard.keysDown[key] = false;
};
this.isKeyDown = function(key) {
return COBY.Keyboard.keysDown[key];
};
});
document.body.onkeydown = function(e) {
COBY.Keyboard.setKeyDown(e.keyCode);
};
document.body.onkeyup = function(e) {
COBY.Keyboard.setKeyUp(e.keyCode);
};
document.body.onmousemove = function(e) {
COBY.mouseX = e.x;
COBY.mouseY = e.y;
};
this.shapes = {
cube:new THREE.BoxGeometry(1,1,1),
cylinder: new THREE.CylinderGeometry(0.5, 0.5, 1),
plane: new THREE.PlaneBufferGeometry(1,1),
};
this.textures = {
white:new THREE.MeshLambertMaterial({color:"white"}),
red:new THREE.MeshLambertMaterial({color:"red"}),
purple:new THREE.MeshLambertMaterial({color:"purple"}),
blue:new THREE.MeshLambertMaterial({color:"blue"}),
pink:new THREE.MeshLambertMaterial({color:"pink"}),
gray:new THREE.MeshLambertMaterial({color:"gray"}),
yellow:new THREE.MeshLambertMaterial({color:"yellow"}),
green:new THREE.MeshLambertMaterial({color:"green"})
};
this.loadTexture = function(name, path) {
COBY.textures[name] = new THREE.MeshBasicMaterial({
map: THREE.ImageUtils.loadTexture(path)
});
console.log(COBY.textures);
};
this.GUIContainer = function(obj) {
this.div = document.createElement("div");
this.div.style.position="absolute";
this.div.style.left=(obj.x || 0) + "px";
this.div.style.top=(obj.y || 0) + "px";
this.div.style.background=obj.color || "white";
this.div.style.width = (obj.width || 100) + "px";
this.div.style.height = (obj.height || 100) + "px";
this.div.style.display = obj.invisible ? "none" : "block";
var that = this;
this.add = function(g) {
that.div.appendChild(g.div);
};
if(document.body) {
document.body.appendChild(this.div);
}
};
this.GUIObject = function(obj) {
this.div = document.createElement("div");
this.div.style.position="absolute";
this.div.style.left=(obj.x || 0) + "px";
this.div.style.top=(obj.y || 0) + "px";
this.div.style.background=obj.color || "white";
this.div.style.width = (obj.width || 100) + "px";
this.div.style.height = (obj.height || 100) + "px";
if(obj.text) {
this.div.innerHTML = "<p class='gTxt'>" + obj.text + "</p>";
}
if(obj.type === "button") {
this.div.className = "btn";
}
};
this.Cobject = function(obj,world) {
this.width=obj.width||1;
this.height=obj.height||1;
this.depth=obj.depth||1;
this.position = new THREE.Vector3();
this.rotation = {x:0,y:0,z:0};
this.forReference = obj.forReference;
if(obj.position) {
this.position.x = obj.position.x || 0;
this.position.y = obj.position.y || 0;
this.position.z = obj.position.z || 0;
}
if(obj.rotation) {
this.rotation.x = obj.rotation.x || 0;
this.rotation.y = obj.rotation.y || 0;
this.rotation.z = obj.rotation.z || 0;
}
this.worldParent = world || false;
this.followMouse = obj.followMouse || false;
this.update=obj.update||function(c){};
this.start = obj.start || function(){};
this.texture = COBY.textures[obj.texture];
//this.texture.wrapS = this.texture.wrapT = THREE.MirroredRepeatWrapping;
this.mesh=new THREE.Mesh(COBY.shapes[obj.shape],this.texture);
var self = this;
this.updateTexture = function(path) {
self.mesh.material.map.image.src = path;
self.mesh.material.needsUpdate = true;
}
this.superUpdate = function(cob) {
self.mesh.scale.set(self.width,self.height,self.depth);
self.mesh.position.copy(self.position);
self.mesh.rotation.set(self.rotation.x,self.rotation.y,self.rotation.z);
self.update(cob);
};
};
function webglAvailable() {
try {
var canvas = document.createElement( 'canvas' );
return !!( window.WebGLRenderingContext && (
canvas.getContext( 'webgl' ) ||
canvas.getContext( 'experimental-webgl' ) )
);
} catch ( e ) {
return false;
}
}
this.World=function (obj) {
this.width = window.innerWidth;
this.height = window.innerHeight;
this.loadTextures = function(texts) {
for(var i = 0; i < texts.length; i++) {
COBY.loadTexture(texts[i].name, texts[i].path);
}
};
if(obj) {
this.width=obj.width || window.innerWidth;
this.height=obj.height || window.innerHeight;
if(obj.textures) {
this.loadTextures(obj.textures);
}
}
this.scene=new THREE.Scene();
this.camera = new THREE.PerspectiveCamera( 75, this.width / this.height, 0.1, 10000 );
this.camera.name = "camera";
//if ( webglAvailable() ) {
this.renderer = new THREE.WebGLRenderer({alpha:true});
// } else {
// this.renderer = new THREE.CanvasRenderer();
// }
this.renderer.setSize(this.width,this.height);
this.renderer.setClearColor(0x000000, 0);
this.renderer.domElement.style.position="absolute";
this.renderer.domElement.style.left="0";
this.renderer.domElement.style.top="0";
this.camera.position.z=5;
this.cobs = [];
this.meshes=[];
var that=this;
this.light = function(x,y,z,inten) {
var directionalLight1=new THREE.DirectionalLight(0xffffff);
directionalLight1.position.set(x,y,z,inten || 1);
directionalLight1.name == "light";
that.scene.add(directionalLight1);
};
this.lights = function() {
var ambientLight = new THREE.AmbientLight( 0x606060 );
that.scene.add( ambientLight );
var directionalLight = new THREE.DirectionalLight( 0xffffff );
directionalLight.position.set( 1, 0.75, -0.5 ).normalize();
that.scene.add( directionalLight );
};
this.lights();
this.add=function(obj){
if(!obj.forReference) {
if(obj.mesh) {
that.scene.add(obj.mesh);
that.meshes.push(obj.mesh);
that.cobs.push(obj);
} else {
that.scene.add(obj);
}
}
obj.start(obj);
};
this.cob = function(c) {
that.add(new COBY.Cobject(c,that));
};
this.addCobjects = function(cobs) {
for(var i = 0; i < cobs.length; i++) {
that.add(new COBY.Cobject(cobs[i],that));
}
};
this.empty = function() {
that.meshes = [];
that.cobs = [];
for(var i = that.scene.children.length - 1; i >= 0; i--) {
that.scene.remove(that.scene.children[i]);
}
that.scene.add(that.camera);
that.lights();
console.log("just actually emptied..feels good");
};
this.update=function (){
// noprotect
for(var i=0;i<that.cobs.length;i++) {
that.cobs[i].superUpdate(that.cobs[i]);
}
that.loop();
that.renderer.render(that.scene, that.camera);
};
this.loop=function(){
};
this.canvas=this.renderer.domElement;
this.start = function(div) {
if(!div)
document.body.appendChild(this.canvas);
else
div.appendChild(this.canvas);
function sketchProc(proc) {
// noprotect
proc.draw=function(){
that.update();
};
}
var procInst=new Processing(document.createElement("canvas"),sketchProc);
};
};
})();
Both THREE.CylinderGeometry() and THREE.CylinderBufferGeometry() work as expected:
var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera(60, window.innerWidth / window.innerHeight, 1, 1000);
camera.position.setScalar(10);
var renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setClearColor(0x404040);
document.body.appendChild(renderer.domElement);
var controls = new THREE.OrbitControls(camera, renderer.domElement);
//var cylGeom = new THREE.CylinderGeometry(5, 5, 1, 8);
var cylGeom = new THREE.CylinderBufferGeometry(5, 5, 1, 8);
var texLoader = new THREE.TextureLoader();
var texEnd = texLoader.load("https://threejs.org/examples/textures/UV_Grid_Sm.jpg");
texEnd.wrapS = THREE.RepeatWrapping;
texEnd.wrapT = THREE.RepeatWrapping;
texEnd.repeat.set(1, 1);
var texSide = texLoader.load("https://threejs.org/examples/textures/UV_Grid_Sm.jpg");
texSide.wrapS = THREE.RepeatWrapping;
texSide.wrapT = THREE.RepeatWrapping;
texSide.repeat.set(1, 1 / (cylGeom.parameters.radiusTop * cylGeom.parameters.radiusBottom));
var cylMatEnd = new THREE.MeshBasicMaterial({
map: texEnd
});
var cylMatSide = new THREE.MeshBasicMaterial({
map: texSide
});
var cyl = new THREE.Mesh(cylGeom, [cylMatSide, cylMatEnd, cylMatEnd]);
scene.add(cyl);
render();
function render() {
requestAnimationFrame(render);
renderer.render(scene, camera);
}
body {
overflow: hidden;
margin: 0;
}
<script src="https://threejs.org/build/three.min.js"></script>
<script src="https://threejs.org/examples/js/controls/OrbitControls.js"></script>

javascript function didn't work in chrome

i have this function witch shows the user a loadingpanel at postback.
It works fine in IE and Firefox.
But Chrome showed me this Error:
I don't understand why. Does anyone have an idea?
I mean why it works in IE and Firefox. Where is the difference that it doesn't work in Chrome?
(function(){
var emptyFn = function(){};
function lp(d) {
this.converter = d.converter;
this.data = d.path || d.data;
this.imageData = [];
this.multiplier = d.multiplier || 1;
this.padding = d.padding || 0;
this.fps = d.fps || 25;
this.stepsPerFrame = ~~d.stepsPerFrame || 1;
this.trailLength = d.trailLength || 1;
this.pointDistance = d.pointDistance || .05;
this.domClass = d.domClass || 'lp';
this.backgroundColor = d.backgroundColor || 'rgba(0,0,0,0)';
this.fillColor = d.fillColor;
this.strokeColor = d.strokeColor;
this.stepMethod = typeof d.step == 'string' ?
stepMethods[d.step] :
d.step || stepMethods.square;
this._setup = d.setup || emptyFn;
this._teardown = d.teardown || emptyFn;
this._preStep = d.preStep || emptyFn;
this.width = d.width;
this.height = d.height;
this.fullWidth = this.width + 2*this.padding;
this.fullHeight = this.height + 2*this.padding;
this.domClass = d.domClass || 'lp';
this.setup();
}
var argTypes = lp.argTypes = {
DIM: 1,
DEGREE: 2,
RADIUS: 3,
OTHER: 0
};
var argSignatures = lp.argSignatures = {
arc: [1, 1, 3, 2, 2, 0],
bezier: [1, 1, 1, 1, 1, 1, 1, 1],
line: [1,1,1,1]
};
var pathMethods = lp.pathMethods = {
bezier: function(t, p0x, p0y, p1x, p1y, c0x, c0y, c1x, c1y) {
t = 1-t;
var i = 1-t,
x = t*t,
y = i*i,
a = x*t,
b = 3 * x * i,
c = 3 * t * y,
d = y * i;
return [
a * p0x + b * c0x + c * c1x + d * p1x,
a * p0y + b * c0y + c * c1y + d * p1y
]
},
arc: function(t, cx, cy, radius, start, end) {
var point = (end - start) * t + start;
var ret = [
(Math.cos(point) * radius) + cx,
(Math.sin(point) * radius) + cy
];
ret.angle = point;
ret.t = t;
return ret;
},
line: function(t, sx, sy, ex, ey) {
return [
(ex - sx) * t + sx,
(ey - sy) * t + sy
]
}
};
var stepMethods = lp.stepMethods = {
square: function(point, i, f, color, alpha) {
this._.fillRect(point.x - 3, point.y - 3, 6, 6);
},
fader: function(point, i, f, color, alpha) {
this._.beginPath();
if (this._last) {
this._.moveTo(this._last.x, this._last.y);
}
this._.lineTo(point.x, point.y);
this._.closePath();
this._.stroke();
this._last = point;
}
}
lp.prototype = {
setup: function() {
var args,
type,
method,
value,
data = this.data;
this.canvas = document.createElement('canvas');
this._ = this.canvas.getContext('2d');
this.canvas.className = this.domClass;
this.canvas.height = this.fullHeight;
this.canvas.width = this.fullWidth;
this.canvas.innerHTML = "<img src='../img/ContentLoad.gif' width='60px' height='60px' alt='Wird geladen' style='margin-top: 30px;' />"
this.points = [];
for (var i = -1, l = data.length; ++i < l;) {
args = data[i].slice(1);
method = data[i][0];
if (method in argSignatures) for (var a = -1, al = args.length; ++a < al;) {
type = argSignatures[method][a];
value = args[a];
switch (type) {
case argTypes.RADIUS:
value *= this.multiplier;
break;
case argTypes.DIM:
value *= this.multiplier;
value += this.padding;
break;
case argTypes.DEGREE:
value *= Math.PI/180;
break;
};
args[a] = value;
}
args.unshift(0);
for (var r, pd = this.pointDistance, t = pd; t <= 1; t += pd) {
t = Math.round(t*1/pd) / (1/pd);
args[0] = t;
r = pathMethods[method].apply(null, args);
this.points.push({
x: r[0],
y: r[1],
progress: t
});
}
}
this.frame = 0;
if (this.converter && this.converter.setup) {
this.converter.setup(this);
}
},
prep: function(frame) {
if (frame in this.imageData) {
return;
}
this._.clearRect(0, 0, this.fullWidth, this.fullHeight);
this._.fillStyle = this.backgroundColor;
this._.fillRect(0, 0, this.fullWidth, this.fullHeight);
var points = this.points,
pointsLength = points.length,
pd = this.pointDistance,
point,
index,
frameD;
this._setup();
for (var i = -1, l = pointsLength*this.trailLength; ++i < l && !this.stopped;) {
index = frame + i;
point = points[index] || points[index - pointsLength];
if (!point) continue;
this.alpha = Math.round(1000*(i/(l-1)))/1000;
this._.globalAlpha = this.alpha;
if (this.fillColor) {
this._.fillStyle = this.fillColor;
}
if (this.strokeColor) {
this._.strokeStyle = this.strokeColor;
}
frameD = frame/(this.points.length-1);
indexD = i/(l-1);
this._preStep(point, indexD, frameD);
this.stepMethod(point, indexD, frameD);
}
this._teardown();
this.imageData[frame] = (
this._.getImageData(0, 0, this.fullWidth, this.fullWidth)
);
return true;
},
draw: function() {
if (!this.prep(this.frame)) {
this._.clearRect(0, 0, this.fullWidth, this.fullWidth);
this._.putImageData(
this.imageData[this.frame],
0, 0
);
}
if (this.converter && this.converter.step) {
this.converter.step(this);
}
if (!this.iterateFrame()) {
if (this.converter && this.converter.teardown) {
this.converter.teardown(this);
this.converter = null;
}
}
},
iterateFrame: function() {
this.frame += this.stepsPerFrame;
if (this.frame >= this.points.length) {
this.frame = 0;
return false;
}
return true;
},
play: function() {
this.stopped = false;
var hoc = this;
this.timer = setInterval(function(){
hoc.draw();
}, 1000 / this.fps);
},
stop: function() {
this.stopped = true;
this.timer && clearInterval(this.timer);
}
};
window.lp = lp;
}());
function ContentLoader(e) {
function isIE () {
var myNav = navigator.userAgent.toLowerCase();
return (myNav.indexOf('msie') != -1) ? parseInt(myNav.split('msie')[1]) : false;
}
if (isIE () == 8) {
var div = document.createElement('div');
var img = document.createElement('img');
img.src = '../img/ContentLoad.gif';
div.innerHTML = "<b style='color: #1d4377; z-index: 5000;'>Ihre Anfrage wird bearbeitet...</b><br /><i>...einen Moment bitte...</i><br />";
div.style.cssText = 'position: fixed; z-index: 6000; width: 100%; padding-top: 20%; left: 0; top: 0; height: 100%; text-align: center; background: #fff; filter: alpha(opacity=70);';
div.appendChild(img);
img.style.cssText = 'margin-top:20px;'
document.body.appendChild(div);
} else {
var div = document.createElement('div');
var circle = new lp({
width: 60,
height: 60,
padding: 50,
strokeColor: '#1d4377',
pointDistance: .01,
stepsPerFrame: 4,
trailLength: .8,
step: 'fader',
setup: function () {
this._.lineWidth = 5;
},
path: [
['arc', 25, 25, 25, 0, 360]
]
});
circle.play();
div.innerHTML = "<b style='color: #1d4377; z-index: 5000;'>Ihre Anfrage wird bearbeitet...</b><br /><i>...einen Moment bitte...</i><br />";
div.style.cssText = 'position: fixed; z-index: 6000; width: 100%; padding-top: 20%; left: 0; top: 0; height: 100%; text-align: center; background: #fff; opacity: 0.7;';
div.appendChild(circle.canvas);
document.body.appendChild(div);
}
}
Edit:
I call it like this:
<form id="frmTilgungsaussetzungErgebnis" runat="server" enctype="multipart/form-data" onsubmit="ContentLoader();">
Your function lp is not defined in the else scope.
Try
var circle = new this.lp({
instade
var circle = new lp({

Any particular reason I'm getting "Component not available" and "Index Size Error:Dom exception" errors on this code

I'm Javascript/HTML5 newbie and I'm building what is supposed to be a simple blackjack game. I'm learning from a book and I presume my code is fine (checked it a lot) and I know my image files are correctly named. I've included this all in one html file for simplicity.
Any particular reason why this wouldn't be loading into the canvas. Both Chrome and Firefox appear to be taking particular issue with the deal and newGame function. Any advice would be greatly appreciated. (also ignore ugly indenting still new to the stackoverflow tools.)
Thanks
var cwidth = 800;
var cheight = 600;
var cardw = 75;
var cardh = 107;
var playerxp = 100;
var playeryp = 300;
var housexp = 500;
var houseyp = 100;
var housetotal;
var playertotal;
var pi = 0;
var hi = 0;
var deck = [];
var playerhand = [];
var househand = [];
var back = new Image();
function init () {
ctx = document.getElementById('canvas').getContext('2d');
ctx.font = "italic 20pt Georgia";
ctx.fillstyle = 'blue';
builddeck();
back.src = 'cardback.png';
canvas1 = document.getElementById('canvas');
window.addEventListener('keydown', getkey, false);
shuffle();
dealstart();
}
function getkey(event) {
var keyCode;
if (event == null)
{
keyCode = window.event.keyCode;
window.event.preventDefault();
}
else {
keyCode = event.keyCode;
event.preventDefault();
}
switch(keyCode) {
case 68:
deal();
break;
case 72:
playerdone();
break;
case 78:
newgame();
break;
default:
alert("press d, h or n please.");
}
}
function dealstart() {
playerhand[pi] = dealfromdeck(1);
ctx.drawImage(playerhand[pi].picture, playerxp, playeryp, cardw, cardh);
playerxp = playerxp+30;
pi++;
househand[hi] = dealfromdeck(2);
ctx.drawImage(back, housexp, houseyp, cardw, cardh);
housexp = housexp+20;
hi++;
playerhand[pi] = dealfromdeck(1);
ctx.drawImage(playerhand[pi].picture, playerxp, playeryp, cardw, cardh);
playerxp = playerxp+30;
pi++;
househand[hi] = dealfromdeck(2);
ctx.drawImage(househand[hi].picture, housexp, houseyp, cardw, cardh);
housexp = housexp+20;
hi++;
}
function deal() {
playerhand[pi] = dealfromdeck(1);
ctx.drawImage(playerhand[pi].picture, playerxp, playeryp, cardw, cardh);
playerxp = playerxp+30;
pi++;
if (more_to_house()) {
househand[hi] = dealfromdeck(2);
ctx.drawImage(househand[hi].picture, housexp, houseyp, cardw, cardh);
housexp = housexp+20;
hi++;
}
}
function more_to_house() {
var ac = 0;
var i;
var sumup = 0;
for(i = 0; i < hi; i++) {
sumup += househand[i].value;
if (househand[i].value==1){ac++;}
}
if (ac>0) {
if ((sumup+10)<=21){
sumup+=10;
}
}
housetotal = sumup;
if (sumup<17){
return true;
}
else{
return false;
}
}
function dealfromdeck(who){
var card;
var ch = 0;
while ((deck[ch].dealt>0)&&(ch<51)){
ch++;
}
if (ch>=51) {
ctx.fillText("NO MORE CARDS IN DECK. Reload.", 200, 250);
ch = 51;
}
deck[ch].dealt = who;
card = deck[ch];
return card;
}
function builddeck() {
var n;
var si;
var suitname = ["clubs", "hearts", "spades", "diamonds"];
var i;
i=0;
var picname;
var nums = ["a", "2", "3", "4", "5", "6", "7", "8", "9", "10", "j", "q", "k"];
for (si=0; si<4; si++) {
for(n=0; n<13; n++) {
picname = suitname[si]+"-"+nums[n]+"-75.png";
deck[i] = new MCard(n+1, suitname[si], picname);
i++;
}
}
}
function MCard(n, s, picname){
this.num = n;
if (n>10) n = 10;
this.value = n;
this.suit = s;
this.picture = new Image();
this.picture.src = picname;
this.dealt = 0;
}
function add_up_player (){
var ac = 0;
var i;
var sumup = 0;
for(i=0; i<pi; i++){
sumup += playerhand[i].value;
if (playerhand[i].value==1)
{
ac++;
}
}
if (ac>0) {
if((sumup+10)<=21){
sumup+=10;
}
}
return sumup;
}
function playerdone() {
while (more_to_house()) {
househand[hi] = dealfromdeck(2);
ctx.drawImage(back, housexp, houseyp, cardw, cardh);
housexp = housexp+20;
hi++;
}
showhouse();
playertotal = add_up_player();
if (playertotal > 21) {
if (housetotal > 21) {
ctx.fillText("You and the house both went bust.", 30, 100);
}
else{
ctx.fillText("You went over and lost.", 30 , 100);
}
}
else
if (housetotal > 21) {
ctx.fillText("You Won. The house went bust.", 30, 100);
}
else
if (playertotal >= housetotal) {
if (playertotal > housetotal) {
ctx.fillText("You won.", 30, 100);
}
else {
ctx.fillText("You draw.", 30 , 100);
}
}
else
if(housetotal <= 21) {
ctx.fillText("You Lost.", 30, 100);
}
else {
ctx.fillText("You won because the house went over.");
}
}
function newgame() {
ctx.clearRect(0, 0, cwidth, cheight);
pi = 0;
hi = 0;
playerxp = 100;
housexp = 500;
dealstart();
}
function showhouse() {
var i;
housexp = 500;
for (i=0; i<hi; i++){
ctx.drawImage(househand[i].picture, housexp, houseyp, cardw, cardh);
housexp = housexp+20;
}
}
function shuffle() {
var i = deck.length - 1;
var s;
while (i>0) {
s = Math.floor(Math.random()*(i+1));
swapindeck(s,i);
i--;
}
}
function swapindeck(j, k) {
var hold = new MCard(deck[j].num, deck[j].suit, deck[j].picture.src);
deck[j] = deck[k];
deck[k] = hold;
}
body {
background-color: white;
color: black;
font-size: 18px;
font-family: Verdana, Geneva, sans-serif;
}
footer {
display: block;
font-family: Tahoma, Geneva, sans-serif;
text-align: center;
font-style: oblique;
}
header {
width: 100%;
}
<html>
<head>
<title>BlackJack</title>
</head>
<body onLoad = "init();">
<header>Press d for deal or 1 more card, h for hold, n for new game.</header>
<canvas id="canvas" width="800" height = "500">
Your Browser doesn't support the Html5 element canvas.
</canvas>
<footer>
</footer>
</body>
</html>
When I run your code I actually get this error, for the same line you specified:
Uncaught InvalidStateError: Failed to execute 'drawImage' on 'CanvasRenderingContext2D': The HTMLImageElement provided is in the 'broken' state.
Which means the image you are trying to draw cannot be found in a directory to be drawn.
So I replaced the static code images you had with external links and the code works fine:
var cwidth = 800;
var cheight = 600;
var cardw = 75;
var cardh = 107;
var playerxp = 100;
var playeryp = 300;
var housexp = 500;
var houseyp = 100;
var housetotal;
var playertotal;
var pi = 0;
var hi = 0;
var deck = [];
var playerhand = [];
var househand = [];
var back = new Image();
function init() {
ctx = document.getElementById('canvas').getContext('2d');
ctx.font = "italic 20pt Georgia";
ctx.fillstyle = 'blue';
builddeck();
back.src = 'http://www.jimknapp.com/Cards/Non-Bicycle_files/image001.jpg';
canvas1 = document.getElementById('canvas');
window.addEventListener('keydown', getkey, false);
shuffle();
dealstart();
}
function getkey(event) {
var keyCode;
if (event == null) {
keyCode = window.event.keyCode;
window.event.preventDefault();
} else {
keyCode = event.keyCode;
event.preventDefault();
}
switch (keyCode) {
case 68:
deal();
break;
case 72:
playerdone();
break;
case 78:
newgame();
break;
default:
alert("press d, h or n please.");
}
}
function dealstart() {
playerhand[pi] = dealfromdeck(1);
ctx.drawImage(playerhand[pi].picture, playerxp, playeryp, cardw, cardh);
playerxp = playerxp + 30;
pi++;
househand[hi] = dealfromdeck(2);
ctx.drawImage(back, housexp, houseyp, cardw, cardh);
housexp = housexp + 20;
hi++;
playerhand[pi] = dealfromdeck(1);
ctx.drawImage(playerhand[pi].picture, playerxp, playeryp, cardw, cardh);
playerxp = playerxp + 30;
pi++;
househand[hi] = dealfromdeck(2);
ctx.drawImage(househand[hi].picture, housexp, houseyp, cardw, cardh);
housexp = housexp + 20;
hi++;
}
function deal() {
playerhand[pi] = dealfromdeck(1);
ctx.drawImage(playerhand[pi].picture, playerxp, playeryp, cardw, cardh);
playerxp = playerxp + 30;
pi++;
if (more_to_house()) {
househand[hi] = dealfromdeck(2);
ctx.drawImage(househand[hi].picture, housexp, houseyp, cardw, cardh);
housexp = housexp + 20;
hi++;
}
}
function more_to_house() {
var ac = 0;
var i;
var sumup = 0;
for (i = 0; i < hi; i++) {
sumup += househand[i].value;
if (househand[i].value == 1) { ac++; }
}
if (ac > 0) {
if ((sumup + 10) <= 21) {
sumup += 10;
}
}
housetotal = sumup;
if (sumup < 17) {
return true;
} else {
return false;
}
}
function dealfromdeck(who) {
var card;
var ch = 0;
while ((deck[ch].dealt > 0) && (ch < 51)) {
ch++;
}
if (ch >= 51) {
ctx.fillText("NO MORE CARDS IN DECK. Reload.", 200, 250);
ch = 51;
}
deck[ch].dealt = who;
card = deck[ch];
return card;
}
function builddeck() {
var n;
var si;
var suitname = ["C", "H", "S", "D"];
var i;
i = 0;
var picname;
var nums = ["A", "2", "3", "4", "5", "6", "7", "8", "9", "0", "J", "Q", "K"];
for (si = 0; si < 4; si++) {
for (n = 0; n < 13; n++) {
picname = "https://deckofcardsapi.com/static/img/" + nums[n] + suitname[si] + ".png";
deck[i] = new MCard(n + 1, suitname[si], picname);
i++;
}
}
}
function MCard(n, s, picname) {
this.num = n;
if (n > 10) n = 10;
this.value = n;
this.suit = s;
this.picture = new Image();
this.picture.src = picname;
this.dealt = 0;
}
function add_up_player() {
var ac = 0;
var i;
var sumup = 0;
for (i = 0; i < pi; i++) {
sumup += playerhand[i].value;
if (playerhand[i].value == 1) {
ac++;
}
}
if (ac > 0) {
if ((sumup + 10) <= 21) {
sumup += 10;
}
}
return sumup;
}
function playerdone() {
while (more_to_house()) {
househand[hi] = dealfromdeck(2);
ctx.drawImage(back, housexp, houseyp, cardw, cardh);
housexp = housexp + 20;
hi++;
}
showhouse();
playertotal = add_up_player();
if (playertotal > 21) {
if (housetotal > 21) {
ctx.fillText("You and the house both went bust.", 30, 100);
} else {
ctx.fillText("You went over and lost.", 30, 100);
}
} else
if (housetotal > 21) {
ctx.fillText("You Won. The house went bust.", 30, 100);
} else
if (playertotal >= housetotal) {
if (playertotal > housetotal) {
ctx.fillText("You won.", 30, 100);
} else {
ctx.fillText("You draw.", 30, 100);
}
} else
if (housetotal <= 21) {
ctx.fillText("You Lost.", 30, 100);
} else {
ctx.fillText("You won because the house went over.");
}
}
function newgame() {
ctx.clearRect(0, 0, cwidth, cheight);
pi = 0;
hi = 0;
playerxp = 100;
housexp = 500;
dealstart();
}
function showhouse() {
var i;
housexp = 500;
for (i = 0; i < hi; i++) {
ctx.drawImage(househand[i].picture, housexp, houseyp, cardw, cardh);
housexp = housexp + 20;
}
}
function shuffle() {
var i = deck.length - 1;
var s;
while (i > 0) {
s = Math.floor(Math.random() * (i + 1));
swapindeck(s, i);
i--;
}
}
function swapindeck(j, k) {
var hold = new MCard(deck[j].num, deck[j].suit, deck[j].picture.src);
deck[j] = deck[k];
deck[k] = hold;
}
body {
background-color: white;
color: black;
font-size: 18px;
font-family: Verdana, Geneva, sans-serif;
}
footer {
display: block;
font-family: Tahoma, Geneva, sans-serif;
text-align: center;
font-style: oblique;
}
header {
width: 100%;
display: block;
}
<!DOCTYPE html>
<html>
<head>
<title>BlackJack</title>
</head>
<body onLoad="init();">
<header>Press d for deal or 1 more card, h for hold, n for new game.</header>
<canvas id="canvas" width="800" height="500">
Your Browser doesn't support the Html5 element canvas.
</canvas>
<footer>
</footer>
</body>
</html>
If you do get this error, I've specified, while using external links, then it's probably because you have an ad blocker blocking the image from being loaded in externally

Categories

Resources