Below is an easy way to put some text on a pixi.js (using WebGL) canvas.
How can we scroll / zoom the displayed part of the canvas ?
(i.e. mouse down + drag should move ...)
Example of what I would like to achieve : http://s419743653.onlinehome.fr/things/test2.htm
<!DOCTYPE HTML>
<html>
<head>
<title>pixi.js example 1</title>
<script src="pixi.js"></script>
</head>
<body>
<script>
var stage = new PIXI.Stage(0xFFFFFF);
var renderer = PIXI.autoDetectRenderer(800, 600);
document.body.appendChild(renderer.view);
var text = new PIXI.Text("Hello World", {font:"50px Arial", fill:"black"});
stage.addChild(text);
renderer.render(stage);
</script>
</body>
</html>
set the scale property on the DisplayObjectContainer. In your case you don't have any so you can scale the stage.
stage.scale.x = 2;
stage.scale.y = 2;
or you can put your objects in a group and scale the group.
var group = new Pixi.DisplayObjectContainer();
group.scale.x = 2;
group.scale.y = 2;
group.add(text);
Related
So Im very new to JavaScript and I'm still learning, in my code I would really like to understand why the tail of my snake is moving before the head, shouldn't the head's x increase before the tail's
Since the increment code for head is before
The tail. What I'm trying to achieve is to have the x increment then the head moves and as it moves the snakex array value gets replaced by velocity which now makes the tail's x increase but maintain a distance from the head's starting position so as not to overlap with the head
var canvas= document.querySelector("canvas");
var right=document.querySelector("#right");
var left=document.querySelector("#left");
var up=document.querySelector("#up");
var down=document.querySelector("#down");
canvas.width=window.innerWidth;
canvas.height=window.innerHeight-500;
var ctx= canvas.getContext("2d");
width= 20;
height=20;
var x=40;
var tx=x-20;
var y=0;
var sx;
var sy;
var inc=0;
var change=true;
var speed = 0;
var velocity;
var snakex=[x]
var snakey=[y]
var motionx;
setInterval(function move(){
ctx.fillStyle="white";
ctx.clearRect(0,0,canvas.width,canvas.height);
ctx.fillStyle="orange";
x+=20;
ctx.fillRect(snakex[0],snakey[0],20,20);
velocity=x-20;
snakex.splice(0,1, velocity);
ctx.strokeStyle="green";
ctx.strokeRect(velocity,snakey[0],20,20);
},200)
function sright(){
}
right.addEventListener("click", sright);
<!doctype html>
<html>
<head>
<title>snake</title>
<meta charset="utf-8">
</head>
<body>
<canvas></canvas>
<button id="right">right</button>
<button id="down">down</button>
<button id="left">left</button>
<button id="up">up</button>
</body>
</html>
Here is a fixed version of the code.
However, if you want your snake to grow and have more than 1 block in size, you will need to change the approach.
On each iteration, you will need to copy snake blocks from tail to head like so:
for (let index=snakeLength-2; index>=0; index --) {
snakex[index + 1] = snakex[index];
snakey[index + 1] = snakey[index];
}
This will guarantee that the snake's body moves. After this move, you can update snakex[0] and snakey[0] based on the user's input. This will allow a user to control the snake's head.
Please let me know if this helps.
var canvas= document.querySelector("canvas");
var right=document.querySelector("#right");
var left=document.querySelector("#left");
var up=document.querySelector("#up");
var down=document.querySelector("#down");
canvas.width=window.innerWidth;
canvas.height=window.innerHeight-500;
var ctx= canvas.getContext("2d");
width= 20;
height=20;
var x=40;
var tx=x-20;
var y=0;
var sx;
var sy;
var inc=0;
var change=true;
var speed = 0;
var velocity;
var snakex=[x]
var snakey=[y]
var motionx;
setInterval(function move(){
ctx.fillStyle="white";
ctx.clearRect(0,0,canvas.width,canvas.height);
ctx.fillStyle="orange";
// x+=20;
// here you need to update snakex[0] instead of x
// to make sure that the next execution of the method move
// will reuse it
snakex[0] = snakex[0] + 20;
ctx.fillRect(snakex[0],snakey[0],20,20);
// the tail should always be calculated based on the head
velocity=snakex[0]-20;
// the next line removes snakex[0] that was updated, you don't need this
// snakex.splice(0,1, velocity);
ctx.strokeStyle="green";
ctx.strokeRect(velocity,snakey[0],20,20);
},200)
function sright(){
}
right.addEventListener("click", sright);
<!doctype html>
<html>
<head>
<title>snake</title>
<meta charset="utf-8">
</head>
<body>
<canvas></canvas>
<button id="right">right</button>
<button id="down">down</button>
<button id="left">left</button>
<button id="up">up</button>
</body>
</html>
I have not been able to scroll through canvas move whole paper horizontally and
vertically.
It is possible?
<script type="text/javascript" src="~/Scripts/PaperJS/paper-full.js"></script>
<script type="text/javascript" src="~/Scripts/PaperJS/paper-core.js"></script>
<script>
$(document).ready(function () {
var canvas = document.getElementById('odbCanvas');
paper.setup(canvas);
var path = new paper.Path();
path.strokeColor = 'white';
var start = new paper.Point(100, 100);
path.moveTo(start);
path.lineTo(start.add(0,40));
path.lineTo(start.add(40,40));
path.lineTo(start.add(40,0));
path.lineTo(start.add(0,0));
paper.view.draw();
path.on('mousedrag', function (event) {
this.position = event.point;
});
});
</script>
You can use paper.view.scrollBy(new Point(x, y)) to scroll the whole View
Here's some example code:
// Draw a Rectangle for reference
var rect = new Path.Rectangle(new Point(200, 100), new Point(50, 50))
rect.strokeColor = 'black'
rect.strokeWidth = 1
// Create a Tool so we can listen for events
var toolPan = new paper.Tool()
toolPan.activate()
// On drag, scroll the View by the difference between mousedown
// and mouseup
toolPan.onMouseDrag = function (event) {
var delta = event.downPoint.subtract(event.point)
paper.view.scrollBy(delta)
}
And here's a Sketch for this (drag your mouse on the canvas)
Side note: You don't need to include both paper-core.js and paper-full.js. Use one or the other, depending whether you need PaperScript support as well (paper-full.js includes PS as well).
I found a cool animation on codepen that takes a map (img) and reconstruct it with blocks. The js files needed is three.min.js and TweenMax.min.js I took the links from codepen and pasted it into my head within <script src=""></script>. After copying every css and html (not much) it apears that three.min.js got an error(?).
I opened google chrome console and saw three.min.js:536 Uncaught TypeError: Cannot read property 'width' of null.
heres the codepen animation im reffering to:
http://codepen.io/Mamboleoo/pres/JYJPJr
My code:
<!DOCTYPE html>
<html>
<head>
<?php include $_SERVER["DOCUMENT_ROOT"] . "/assets/head.php"; ?>
<title><?php echo $address; ?> - Credits</title>
</head>
<body>
<?php include $_SERVER["DOCUMENT_ROOT"] . "/navigationbar.php"; ?>
<script>
var renderer, scene, camera, ww, wh, particles;
ww = window.innerWidth,
wh = window.innerHeight;
var centerVector = new THREE.Vector3(0, 0, 0);
var previousTime = 0;
var getImageData = function(image) {
var canvas = document.createElement("canvas");
canvas.width = image.width;
canvas.height = image.height;
var ctx = canvas.getContext("2d");
ctx.drawImage(image, 0, 0);
return ctx.getImageData(0, 0, image.width, image.height);
}
var drawTheMap = function() {
var geometry = new THREE.Geometry();
var material = new THREE.PointsMaterial({
size: 3,
color: 0x313742,
sizeAttenuation: false
});
for (var y = 0, y2 = imagedata.height; y < y2; y += 2) {
for (var x = 0, x2 = imagedata.width; x < x2; x += 2) {
if (imagedata.data[(x * 4 + y * 4 * imagedata.width) + 3] > 128) {
var vertex = new THREE.Vector3();
vertex.x = Math.random() * 1000 - 500;
vertex.y = Math.random() * 1000 - 500;
vertex.z = -Math.random() * 500;
vertex.destination = {
x: x - imagedata.width / 2,
y: -y + imagedata.height / 2,
z: 0
};
vertex.speed = Math.random() / 200 + 0.015;
geometry.vertices.push(vertex);
}
}
}
particles = new THREE.Points(geometry, material);
scene.add(particles);
requestAnimationFrame(render);
};
var init = function() {
THREE.ImageUtils.crossOrigin = '';
renderer = new THREE.WebGLRenderer({
canvas: document.getElementById("map"),
antialias: true
});
renderer.setSize(ww, wh);
renderer.setClearColor(0x1d1f23);
scene = new THREE.Scene();
camera = new THREE.PerspectiveCamera(50, ww / wh, 0.1, 10000);
camera.position.set(-100, 0, 220);
camera.lookAt(centerVector);
scene.add(camera);
texture = THREE.ImageUtils.loadTexture("http://mamboleoo.be/lab/transparentMap.png", undefined, function() {
imagedata = getImageData(texture.image);
drawTheMap();
});
window.addEventListener('resize', onResize, false);
};
var onResize = function(){
ww = window.innerWidth;
wh = window.innerHeight;
renderer.setSize(ww, wh);
camera.aspect = ww / wh;
camera.updateProjectionMatrix();
};
var render = function(a) {
requestAnimationFrame(render);
for (var i = 0, j = particles.geometry.vertices.length; i < j; i++) {
var particle = particles.geometry.vertices[i];
particle.x += (particle.destination.x - particle.x) * particle.speed;
particle.y += (particle.destination.y - particle.y) * particle.speed;
particle.z += (particle.destination.z - particle.z) * particle.speed;
}
if(a-previousTime>100){
var index = Math.floor(Math.random()*particles.geometry.vertices.length);
var particle1 = particles.geometry.vertices[index];
var particle2 = particles.geometry.vertices[particles.geometry.vertices.length-index];
TweenMax.to(particle, Math.random()*2+1,{x:particle2.x, y:particle2.y, ease:Power2.easeInOut});
TweenMax.to(particle2, Math.random()*2+1,{x:particle1.x, y:particle1.y, ease:Power2.easeInOut});
previousTime = a;
}
particles.geometry.verticesNeedUpdate = true;
camera.position.x = Math.sin(a / 5000) * 100;
camera.lookAt(centerVector);
renderer.render(scene, camera);
};
init();
</script>
<style>
canvas{width:100%;height:100%;padding:0;margin:0;overflow: hidden;}
</style>
<div class="wrapper">
<canvas id="map"></canvas>
</div>
<div style="position:relative; clear:both;"></div>
<!--</body>-->
<?php include $_SERVER["DOCUMENT_ROOT"] . "/footer.php"; ?>
</body>
</html>
The problem was worked out in the comments, but for the sake of not leaving a question technically unanswered I will explain the process for anyone stumbling across this page after searching for the error posted in the question.
In the example which was posted in the question (which is utilizing PHP to load the Javascript, but that matters little for the actual problem at hand) the Javascript relating to ThreeJS is being executed before the DOM has loaded the canvas element. Obviously ThreeJS requires the Canvas element, as it attaches its various listeners and objects to it, so when attempting to access members related to the canvas element it was simply getting undefined.
The fix for this was to load ThreeJS and all code related to it after the DOM had loaded the elements, there are multiple methods of doing that (which you should search for, as I'm afraid I don't have the time to explain them all), but I will highlight one which I deem the easiest. The method is to put all of your DOM specific code (Javascript that interacts with the DOM) at the bottom of your body tag (not below it, inside it at the very bottom. As Vikas Kapadiya pointed out, it would not be valid HTML if it was below it)
The below snippet shows how Javascript is loaded in relation to the DOM:
<!DOCTYPE html>
<html lang="en">
<head>
<title></title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script>
var p = document.getElementById('example');
console.log("In head " + p);
</script>
</head>
<body>
<p id="example">Hello</p>
<script>
var p = document.getElementById('example');
console.log("In body " + p.innerHTML);
</script>
</body>
</html>
Output:
In head null
In body Hello
As dictated by the above, the code within the head tag could not access the innerHTML (refering to the text content of the p tag) due to being executed before the DOM was loaded. The code found at the bottom of the body tag could, as the DOM was loaded and then the browser stumbled upon the Javascript.
Here are some related links which could shed more light than I have:
Where should I put <script> tags in HTML markup?
Where to place JavaScript functions: <head>? <body>? or, after </html>?
Just move wrapper div to just after body tag . then include all js .
Like this
<body>
<div class="wrapper">
<canvas id="map"></canvas>
</div>
Can anyone explain the purpose of the regX and regY in EaselJS? It gets me confused.
Technically, this code snippet:
var shape = new createjs.Shape();
shape.graphics.beginFill("blue").drawRect(centerX - SIZE / 2, centerY - SIZE / 2, SIZE, SIZE);
and this code snippet:
var shape = new createjs.Shape();
shape.graphics.beginFill("blue").drawRect(centerX - SIZE / 2, centerY - SIZE / 2, SIZE, SIZE);
shape.regX = SIZE / 2;
shape.regY = SIZE / 2;
provide the exact same result.
So, regX / regY actually subtract their value from the shape x / y?
To clarify, centerX, centerY are the represent the center of canvas and size is a property that represents the size of the shape.
The example you use is a Shape, which has a separate coordinate system that you draw points on. The regX / regY properties are on DisplayObject, so they apply to all objects on the stage. The same could be said for a Container, where you can draw your elements at [50,50], or draw them at [0,0], and offset the registration point.
Technically the two approaches accomplish the same result (offsetting the content visually), but the two have different purposes. The registration point can be changed after-the-fact, and simply offset where the element draws from.
This is more obvious for something like a Bitmap that is drawn at 0,0.
Simple answer: they are substitute x,y coordinates. The only use I know of is in rotating bitmaps. See the sample here.
Here's the code in the sample:
<!DOCTYPE html>
<html>
<head>
<script asrc="http://code.createjs.com/easeljs-0.7.0.min.js"></script>
<script>
//this sample uses the timer to rotate a bitmap around its center
var stage, rect, img; //declare global variables
function init() {
//this function is registered in the html body tag
stage = new createjs.Stage("demoCanvas"); //create a Stage object to work with the canvas element
img = new Image(); //create an Image object, then set its source property
img.src = 'green.jpg';
img.onload = handleImageLoad; //register a handler for the onload event
}
function handleImageLoad(event) {
//this function rus when the onload event completes
rect = new createjs.Bitmap(img); //create a Bitmap object, then set properties
rect.scaleX = .5;
rect.scaleY = .5;
rect.x = 250;
rect.y = 250;
rect.regX = img.width/2; //move registration point to center of bitmap
rect.regY = img.height/2;
stage.addChild(rect); //add the Bitmap object to the stage
createjs.Ticker.setFPS(30); //set the Ticker frame rate
createjs.Ticker.on("tick", tick); //add a Ticker event listener; 1st parameter specifies the event type,
//2nd parameter registers the function that is called when the event fires
}
function tick(event) {
//this function is called when the tick event fires
rect.rotation += 8; //increments rotation by 8 degrees
stage.update(event); //update the stage
}
//samples list: http://www.clarksoncs.com/JavaScriptSamples/EaselJS/easelJsSamplesIndex.html
</script>
</head>
<body onLoad="init();">
<!--add a canvas tag-->
<canvas id="demoCanvas" width="2000" height="2000"></canvas>
</body>
</html>
I am trying to grab the RGB value from a click on a colour wheel image.
Now i am trying to grab the RGB from this Colour wheel image below without using canvas getImageData.
How can i do this without canvas?
With canvas you can run.
$('#picker').click(function(e) { // mouse move handler
// get coordinates of current position
var canvasOffset = $(canvas).offset();
var canvasX = Math.floor(e.pageX - canvasOffset.left);
var canvasY = Math.floor(e.pageY - canvasOffset.top);
alert("canvasX " + canvasX + " canvasY " + canvasY);
// get current pixel
var imageData = ctx.getImageData(canvasX, canvasY, 1, 1);
var pixel = imageData.data;
alert(JSON.stringify(pixel));
});
I cannot use canvas for this only javascript can anyone tell me the best way to getImageData from a image would i need to build a rgb grid with a for loop over the top and work out the selected pixel from the x and y value and then match it.
Really stumped on where to start any help?
Here's #Pointy's good idea put to code:
Illustrating with just 1 of your color wheel wedges. You can expand this starting point to include all wedges in your color wheel.
Example code and a Demo: http://jsfiddle.net/m1erickson/9pc4orw8/
<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" media="all" href="css/reset.css" /> <!-- reset css -->
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<style>
body{ background-color: ivory; }
#wheel{border:1px solid red;}
#results{width:50px;height:25px;background-color:black;border:1px solid green;}
</style>
<script>
$(function(){
var $wheel=$("#wheel");
var wheelOffset=$wheel.offset();
var offsetX=wheelOffset.left;
var offsetY=wheelOffset.top;
var PI=Math.PI;
var cx=0;
var cy=0;
// define the angle & radius of each color in the color wheel
var colors=[];
colors.push({sAngle:0,eAngle:PI/6,sRadius:0,eRadius:15,color:'rgb(255,255,255)'});
colors.push({sAngle:0,eAngle:PI/6,sRadius:15,eRadius:32,color:'rgb(253,237,238)'});
colors.push({sAngle:0,eAngle:PI/6,sRadius:32,eRadius:53,color:'rgb(251,211,212)'});
colors.push({sAngle:0,eAngle:PI/6,sRadius:53,eRadius:87,color:'rgb(246,145,149)'});
colors.push({sAngle:0,eAngle:PI/6,sRadius:87,eRadius:117,color:'rgb(240,73,80)'});
colors.push({sAngle:0,eAngle:PI/6,sRadius:117,eRadius:138,color:'rgb(237,27,36)'});
$("#wheel").mousedown(function(e){handleMouseDown(e);});
// test the current mouse position against the saved angle & radius of each color
// return the colors index of any color under the mouse
function hit(mx,my){
var hitIndex=-1;
for(var i=0;i<colors.length;i++){
var c=colors[i];
var a0=c.sAngle;
var a1=c.eAngle;
var r0=c.sRadius;
var r1=c.eRadius;
var dx=mx-cx;
var dy=my-cy;
var radius=Math.sqrt(dx*dx+dy*dy);
var angle=Math.atan2(dy,dx);
if(angle>a0 && angle<a1 && radius>r0 && radius<r1){
hitIndex=i;
break;
}
}
return(hitIndex);
}
function handleMouseDown(e){
e.preventDefault();
e.stopPropagation();
mx=parseInt(e.clientX-offsetX);
my=parseInt(e.clientY-offsetY);
var colorIndex=hit(mx,my);
if(colorIndex>=0){
$('#results').css('background-color',colors[colorIndex].color);
}
}
}); // end $(function(){});
</script>
</head>
<body>
Click to select color:<div id=results></div>
<img id=wheel src='https://dl.dropboxusercontent.com/u/139992952/multple/colorwheel1.png'/>
</body>
</html>