Canvas Spinning Cube - html

I have an HTML5 Canvas Spinning Cube on this codePen:
http://codepen.io/celli/pen/xwvnb
Can someone help to show how to remove the black background ? It looks like the ctx.fillStyle="#000000"; property in the JS is needed (try changing or removing it in the CodePen), but I'd like to have a transparent background, and can't seem to find a way to make that happen.
window.onload = startDemo;
function Point3D(x,y,z) {
this.x = x;
this.y = y;
this.z = z;
this.rotateX = function(angle) {
var rad, cosa, sina, y, z
rad = angle * Math.PI / 180
cosa = Math.cos(rad)
sina = Math.sin(rad)
y = this.y * cosa - this.z * sina
z = this.y * sina + this.z * cosa
return new Point3D(this.x, y, z)
}
this.rotateY = function(angle) {
var rad, cosa, sina, x, z
rad = angle * Math.PI / 180
cosa = Math.cos(rad)
sina = Math.sin(rad)
z = this.z * cosa - this.x * sina
x = this.z * sina + this.x * cosa
return new Point3D(x,this.y, z)
}
this.rotateZ = function(angle) {
var rad, cosa, sina, x, y
rad = angle * Math.PI / 180
cosa = Math.cos(rad)
sina = Math.sin(rad)
x = this.x * cosa - this.y * sina
y = this.x * sina + this.y * cosa
return new Point3D(x, y, this.z)
}
this.project = function(viewWidth, viewHeight, fov, viewDistance) {
var factor, x, y
factor = fov / (viewDistance + this.z)
x = this.x * factor + viewWidth / 2
y = this.y * factor + viewHeight / 2
return new Point3D(x, y, this.z)
}
}
var vertices = [
new Point3D(-1,1,-1),
new Point3D(1,1,-1),
new Point3D(1,-1,-1),
new Point3D(-1,-1,-1),
new Point3D(-1,1,1),
new Point3D(1,1,1),
new Point3D(1,-1,1),
new Point3D(-1,-1,1)
];
// Define the vertices that compose each of the 6 faces. These numbers are
// indices to the vertex list defined above.
var faces = [[0,1,2,3],[1,5,6,2],[5,4,7,6],[4,0,3,7],[0,4,5,1],[3,2,6,7]]
var angle = 0;
function startDemo() {
canvas = document.getElementById("cubeSpin");
if( canvas && canvas.getContext ) {
ctx = canvas.getContext("2d");
setInterval(loop,33);
}
}
function loop() {
var t = new Array();
ctx.fillStyle="#000000";
ctx.fillRect(0,0,320,200);
for( var i = 0; i < vertices.length; i++ ) {
var v = vertices[i];
var r = v.rotateX(angle).rotateY(angle).rotateZ(angle);
var p = r.project(320,200,128,3.5);
t.push(p)
}
ctx.strokeStyle = "rgb(255,255,255)"
for( var i = 0; i < faces.length; i++ ) {
var f = faces[i]
ctx.beginPath()
ctx.moveTo(t[f[0]].x,t[f[0]].y)
ctx.lineTo(t[f[1]].x,t[f[1]].y)
ctx.lineTo(t[f[2]].x,t[f[2]].y)
ctx.lineTo(t[f[3]].x,t[f[3]].y)
ctx.closePath()
ctx.stroke()
}
angle += 2
}

Change:
ctx.fillStyle="#FF0000";
ctx.fillRect(0,0,320,200);
To:
ctx.clearRect(0,0,320,200);

Related

Setting a correct angular velocity to a canvas object

I am building a space shooter game and would like the ship to fire rockets at the direction of the cursor. Therefore, I grab the radian value of the angle it should fire at, multiply it by the ship's speed and set it's x and y velocities respectively.
I have this as a Bullet class:
function Bullet(x, y) {
this.x = x;
this.y = y;
this.rotation = 0;
this.width = 6;
this.height = 3;
this.color = utils.getRandomColor();
this.speed = 80;
}
And here is the function which updates the movement of all instances of the bullet class:
function drawBullet(bullet) {
var dx = mouse.x - bullet.x,
dy = mouse.y - bullet.y,
angle = Math.atan2(dy, dx);
bullet.vx = Math.cos(angle) * bullet.speed;
bullet.vy = Math.sin(angle) * bullet.speed;
bullet.x += bullet.vx;
bullet.y += bullet.vy;
bullet.draw(ctx);
}
It starts okay, going in the right direction and velocity and stuff. But as soon as it reaches the mouse, it stops dead there and starts flickering. NOW, I realise that this is because of the way I am getting the angle, using the mouse position as a value - the problem is that I can't figure out a way to use just the angle for the velocity, not the distance to the mouse position. So it doesn't slow down.
All suggestions are welcome, thanks in advance!
If you don't need homing missile type behavior just pass the mouse coordinates when you create the bullet.
Example:
new Bullet(shooterX, shooterY, mouseX, mouseY)
I included an over engineered stack snippet but the relevant part is below.
var Bullet = function(x,y,tx,ty){
this.speed = 15;
this.x = x;
this.y = y;
var radians = Math.atan2(ty-y, tx-x);
// we now have our velX and velY we can just refer to
this.velX = Math.cos(radians) * this.speed;
this.velY = Math.sin(radians) * this.speed;
}
Bullet.prototype.update = function(){
// just update by our previous calculated velX and velY.
this.x += this.velX;
this.y += this.velY;
};
var canvas = document.getElementById("canvas"),
ctx = canvas.getContext("2d"),
width = 250,
height = 250,
output = document.getElementById("radians"),
output2 = document.getElementById("degrees"),
cX = 0,
cY = 0,
mX = 0,
mY = 0,
bullets = [];
canvas.width = width;
canvas.height = height;
canvas.addEventListener("mousemove", function (e) {
mX = e.pageX;
mY = e.pageY;
});
var Ball = function (x, y, radius, color) {
this.x = x || 0;
this.y = y || 0;
this.radius = radius || 10;
// makes our x and y the center of the circle.
this.x = (this.x-this.radius/2);
this.y = (this.y-this.radius/2);
// how far out do we want the point
this.pointLength = 50;
this.px = 0;
this.py = 0;
this.color = color || "rgb(255,0,0)";
}
Ball.prototype.shoot = function(tx, ty){
bullets.push(new Bullet(this.x, this.y, tx, ty));
}
Ball.prototype.update = function (x, y) {
// get the target x and y
this.targetX = x;
this.targetY = y;
var x = this.x - this.targetX,
y = this.y - this.targetY,
radians = Math.atan2(y,x);
this.px = this.x - this.pointLength * Math.cos(radians);
this.py = this.y - this.pointLength * Math.sin(radians);
// -y will make 0 the top, y will 0 us at the bottom.
output.textContent = radians;
output2.textContent = radians/Math.PI * 180
};
Ball.prototype.render = function () {
ctx.fillStyle = this.color;
ctx.beginPath();
ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2);
ctx.closePath();
ctx.fill();
ctx.strokeStyle = "rgb(0,0,255)";
ctx.beginPath();
ctx.moveTo(this.x, this.y);
ctx.lineTo(this.px, this.py);
ctx.closePath();
ctx.stroke();
};
var Bullet = function(x,y,tx,ty){
this.speed = 15;
this.x = x;
this.y = y;
var radians = Math.atan2(ty-y, tx-x);
this.velX = Math.cos(radians) * this.speed;
this.velY = Math.sin(radians) * this.speed;
}
Bullet.prototype.update = function(){
this.x += this.velX;
this.y += this.velY;
};
Bullet.prototype.render = function(){
ctx.fillStyle = '#000';
ctx.beginPath();
ctx.arc(this.x, this.y, 2, 0, Math.PI * 2);
ctx.closePath();
ctx.fill();
};
var ball1 = new Ball(width/2, height/2, 10);
canvas.addEventListener("click", function (e) {
ball1.shoot(e.pageX, e.pageY);
});
function render() {
ctx.clearRect(0, 0, width, height);
ball1.update(mX, mY);
ball1.render();
bullets.forEach(function(b){
b.update();
b.render();
});
requestAnimationFrame(render);
}
render();
ol{list-style:none;}
<canvas id="canvas"></canvas>
<div>
<ol>
<li>
<span>Radians : </span><span id="radians"></span>
</li>
<li>
<span>Degrees : </span><span id="degrees"></span>
</li>
</ol>
</div>
Add a new property on bullet that stores the angle of motion, initialize it to -1. Then, on the very first drawBullet call, check if it has been initialized first. If not, set the angle...
function Bullet(x, y) {
this.x = x;
this.y = y;
this.rotation = 0;
this.width = 6;
this.height = 3;
this.color = utils.getRandomColor();
this.speed = 80;
this.angle = -1; // New, angle property initialized to -1
}
function drawBullet(bullet) {
if (bullet.angle === -1) { // Only pull the mouse cursor and get an angle
var dx = mouse.x - bullet.x, // If it hasn't already done so.
dy = mouse.y - bullet.y,
angle = Math.atan2(dy, dx);
bullet.angle = angle;
}
bullet.vx = Math.cos(bullet.angle) * bullet.speed; // Re-use the angle value.
bullet.vy = Math.sin(bullet.angle) * bullet.speed;
bullet.x += bullet.vx;
bullet.y += bullet.vy;
bullet.draw(ctx);
}

drawing a smooth line on html5 canvas for mobile app using jquery mobile

I am trying to draw on canvas, like drawing using pencil tool in the paint using jquery mobile.
I searched for many links and most of them were for the desktop, i tried to implement the same logic for the mobile app, i am able to obtain only the click events but not able to draw the line on the canvas.
This is what i was trying to implement on the mobile http://jsfiddle.net/loktar/dQppK/23/
This is my code
$(document).on(
'pageshow',
'#canvaspage',
function() {
var painting = false;
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
// ctx.fillStyle="#FF0000";
// ctx.fillRect(0,0,150,75);
// ctx.drawImage(icons-18-black.png)
ctx.canvas.width = window.innerWidth * 0.8;
ctx.canvas.height = window.innerHeight * 0.8;
var imageObj = new Image();
imageObj.onload = function() {
ctx.drawImage(imageObj, 0, 0, ctx.canvas.width * 0.8,
ctx.canvas.height * 0.7);
};
imageObj.src = 'Image.png';
// c.addEventListener('touchstart', function(e) {
$("#myCanvas").on("touchstart",function(e){
painting = true;
e.preventDefault();
ctx.fillStyle = "#FF0000";
lastX = e.pageX - this.offsetLeft;
lastY = e.pageY - this.offsetTop;
});
// c.addEventListener('touchend', function(e) {
$("#myCanvas").on("touchend",function(e){
painting = false;
});
// c.addEventListener('touchmove', function(e) {
$("#myCanvas").on("touchmove",function(e){
if (painting) {
mouseX = e.pageX - this.offsetLeft;
mouseY = e.pageY - this.offsetTop;
// find all points between
var x1 = mouseX,
x2 = lastX,
y1 = mouseY,
y2 = lastY;
var steep = (Math.abs(y2 - y1) > Math.abs(x2 - x1));
if (steep){
var x = x1;
x1 = y1;
y1 = x;
var y = y2;
y2 = x2;
x2 = y;
}
if (x1 > x2) {
var x = x1;
x1 = x2;
x2 = x;
var y = y1;
y1 = y2;
y2 = y;
}
var dx = x2 - x1,
dy = Math.abs(y2 - y1),
error = 0,
de = dy / dx,
yStep = -1,
y = y1;
if (y1 < y2) {
yStep = 1;
}
lineThickness = 5 - Math.sqrt((x2 - x1) *(x2-x1) + (y2 - y1) * (y2-y1))/10;
if(lineThickness < 1){
lineThickness = 1;
}
alert(painting +" " +x1 +" "+x2);
for (var x = x1; x < x2; x++) {
// alert(x +" "+ y +" "+ lineThickness);
if (steep) {
ctx.fillRect(y, x, lineThickness , lineThickness );
} else {
ctx.fillRect(x, y, lineThickness , lineThickness );
}
alert(steep);
error += de;
if (error >= 0.5) {
y += yStep;
error -= 1.0;
}
}
lastX = mouseX;
lastY = mouseY;
}
// ctx.fillRect(0, 0, 150, 75);
e.preventDefault();
}, false);
});
In the above code i am able to obtain all the touch events but the unable to draw the line.
How can i draw the lines on the canvas??..
Thanks:)
You can use sketch.js (http://intridea.github.io/sketch.js/) with a small modification to make it work on mobile. The modification is given in the comment by leonth here: https://github.com/intridea/sketch.js/issues/1; you basically add 3 lines to the plugin on the mousedown/touchstart event:
switch (e.type) {
case 'mousedown':
case 'touchstart':
if (this.painting) { //add
this.stopPainting(); //add
} //add
this.startPainting();
break;
...
Here is a DEMO FIDDLE, try it from mobile device.

Rotate and move ball image Html 5

now image will be moved but not rotating. i'm implementing moving functionalities. but supporting only IE10.
This is my script,
var ball = new Image;
window.onload = function () {
var c = document.getElementsByTagName('canvas')[0];
var w = c.width = 800;
var h = c.height = 600;
var ctx = c.getContext('2d');
var dx = -1, dy = 0;
var x = 400, y = 200, a = 0;
var deg2rad = Math.PI / 180;
var da = 10 * deg2rad;
var bw = ball.width;
var bh = ball.height;
setInterval(function () {
ctx.clearRect(0, 0, w, h);
ctx.translate(x, y);
ctx.rotate(a);
ctx.drawImage(ball, -bw, -bh);
ctx.rotate(-a);
ctx.translate(-x, -y);
x += dx;
y += dy;
if ((x - bw < 0) || (x + bw > w)) {
dx *= -1; da *= -1;
}
if ((y - bh < 0) || (y + bh > h)) {
dy *= -1; da *= -1;
}
}, 30);
}
ball.src = 'images/beachball.png';
and, this is my Html design,
<canvas id="canvas" width="300" height="300"></canvas>
anybody can help me thanks in advance
You are forgetting to increment your rotation variable:
x += dx;
y += dy;
should also have:
a += da;
Note though that rotating it in the way you are doing it isn't going to rotate around the center of the image; it will rotate around the corner. You will need to adjust the placement by changing the line:
ctx.drawImage(ball, -bw, -bh);
to
ctx.drawImage(ball, -bw/2, -bh/2);
Check your rotation method... Here is link to same question that i answered earlier,
HTML5 canvas image rotate left rotate right

animated "blob" in as3

I am currently playing around with a blob code and have a small problem.
The problem is that sometimes the blob gets inverted so the white color gets inside the blob itself and makes a white hole in it which I don't really want.
Any suggestions on how to fix this, so the blob stays all the time as one little nice piece?
This is the one im playing around with:
http://wonderfl.net/c/rYzh
class Blob extends Sprite
{
private var speed :Number = .01;
private var grav :Number = .25;
private var dist :Number = 27;
private var k :Number = .55;
private var damp :Number = .99;
private var cx :Number = 370;
private var cy :Number = 0;
private var points :Array = [];
private var mids :Array = [];
private var numPoints:Number = 30;
private var oneSlice :Number = Math.PI * 2 / numPoints;
private var radius :Number = 100;
public function Blob()
{
for (var i:Number = 0; i < numPoints; i++)
{
var angle:Number = oneSlice * i;
var obj:Object = {x:Math.cos(angle) * radius + cx, y:Math.sin(angle) * radius + cy, a:angle - Math.PI / 2, wave:i*.08, vx:0, vy:0};
points[i] = obj;
}
this.addEventListener(Event.ENTER_FRAME, update);
}
private function update(event:Event):void
{
this.graphics.clear();
this.graphics.lineStyle(1, 0x666666, 50);
this.graphics.beginFill(0x000000, 100);
for (var i:Number = 0; i < numPoints-1; i++)
{
mids[i] = {x:(points[i].x + points[i + 1].x) / 2, y:(points[i].y + points[i + 1].y) / 2};
}
mids[i] = {x:(points[i].x + points[0].x) / 2, y:(points[i].y + points[0].y) / 2};
this.graphics.moveTo(mids[0].x, mids[0].y);
for (var j:Number = 0; j < numPoints - 1; j++)
{
this.graphics.curveTo(points[j+1].x, points[j+1].y, mids[j+1].x, mids[j+1].y);
}
this.graphics.curveTo(points[0].x, points[0].y, mids[0].x, mids[0].y);
this.graphics.endFill();
var point:Object;
for (var k:Number = 0; k < numPoints - 1; k++)
{
point = points[k];
spring(point, points[k + 1]);
mouseSpring(point);
}
spring(points[k], points[0]);
mouseSpring(points[k]);
for (var l:Number = 0; l < numPoints; l++)
{
point = points[l];
point.vx *= damp;
point.vy *= damp;
point.vy += grav;
point.x += point.vx;
point.y += point.vy;
if (point.y > stage.stageHeight)
{
point.y = stage.stageHeight;
point.vy = 0;
}
if (point.x < 20)
{
point.x = 20;
point.vx = 0;
}
else if (point.x > stage.stageWidth)
{
point.x = stage.stageWidth;
point.vx = 0;
}
}
}
private function spring(p0:Object, p1:Object):void
{
var dx:Number = p0.x - p1.x;
var dy:Number = p0.y - p1.y;
var angle:Number = p0.a+Math.sin(p0.wave += speed)*2;
var tx:Number = p1.x + dist * Math.cos(angle);
var ty:Number = p1.y + dist * Math.sin(angle);
var ax:Number = (tx - p0.x) * k;
var ay:Number = (ty - p0.y) * k;
p0.vx += ax * .5;
p0.vy += ay * .5;
p1.vx -= ax * .5;
p1.vy -= ay * .5;
}
private function mouseSpring(p:Object):void
{
var dx:Number = p.x - stage.mouseX;
var dy:Number = p.y - stage.mouseY;
var dist:Number = Math.sqrt(dx * dx + dy * dy);
if (dist < 40)
{
var angle:Number = Math.atan2(dy, dx);
var tx:Number = stage.mouseX + Math.cos(angle) * 40;
var ty:Number = stage.mouseY + Math.sin(angle) * 40;
p.vx += (tx - p.x) * k;
p.vy += (ty - p.y) * k;
}
}
}
By default, the Graphics APIs use an evenOdd winding, which means if a filled path overlaps itself, it negates the fill.
You need to use the Graphics.drawPath function with a winding value of "nonZero". This will cause it not to negate when the path overlaps itself. Check out this little demo, make a shape that overlaps itself, and switch the winding from evenOdd to nonZero to see how it works.
As for translating your code, instead of using graphics.moveTo() and .curveTo() calls in your update() routine, you'll need to build up a description of your path (aka, the inputs to drawPath) and pass them into graphics.drawPath() last. Adobe shows an example here.

canvas.onmousedown function to add a shape won't work

I have some code, which can be seen below. At the bottom is a block of code to add a shape. For some reason it won't work unless the very first lines of code are different. Up until I added the 'addShape' code, it was all working fine, so I wandered if anyone on here could have a look and perhaps figure out a solution?
Cheers
Jon
EDIT Also available on jsFiddle http://jsfiddle.net/pukster/mfNq4/1/
$(document).ready(function() {
var canvas = $('#myCanvas');
var ctx = canvas.get(0).getContext("2d");
var context = new webkitAudioContext();
var canvasWidth = canvas.width();
var canvasHeight = canvas.height();
$(window).resize(resizeCanvas);
function resizeCanvas() {
canvas.attr("width", $(window).get(0).innerWidth - 2);
canvas.attr("height", $(window).get(0).innerHeight - 2);
canvasWidth = canvas.width();
canvasHeight = canvas.height();
};
resizeCanvas();
ctx.strokeStyle = "rgb(255, 0, 0)";
ctx.lineWidth = 2;
var playAnimation = true;
var Ring = function(x, y, radius, vx, vy) {
this.x = x;
this.y = y;
this.radius = radius;
this.vx = vx;
this.vy = vy;
};
var rings = [];
for (var i = 0; i < 10; i++) {
var x = Math.random()*ctx.canvas.width;
var y = Math.random()*ctx.canvas.height;
var vx = Math.random()*6-3;
var vy = Math.random()*6-3;
rings.push(new Ring(x, y, 40, vx, vy));
};
function animate() {
var ringsLength = rings.length;
ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
for (var i = 0; i < ringsLength; i++) {
var tmpRing = rings[i];
for (var j = i+1; j < ringsLength; j++) {
var tmpRingB = rings[j];
var dx = tmpRingB.x - tmpRing.x;
var dy = tmpRingB.y - tmpRing.y;
var dist = Math.sqrt((dx * dx) + (dy * dy));
if(dist < tmpRing.radius + tmpRingB.radius) {
var sinewave = new SineWave(context);
var angle = Math.atan2(dy, dx);
var sine = Math.sin(angle);
var cosine = Math.cos(angle);
var x = 0;
var y = 0;
var xb = dx * cosine + dy * sine;
var yb = dy * cosine - dx * sine;
var vx = tmpRing.vx * cosine + tmpRing.vy * sine;
var vy = tmpRing.vy * cosine - tmpRing.vx * sine;
var vxb = tmpRingB.vx * cosine + tmpRingB.vy * sine;
var vyb = tmpRingB.vy * cosine - tmpRingB.vx * sine;
vx *= -1;
vxb *= -1;
xb = x + (tmpRing.radius + tmpRingB.radius);
tmpRing.x = tmpRing.x + (x * cosine - y * sine);
tmpRing.y = tmpRing.y + (y * cosine + x * sine);
tmpRingB.x = tmpRing.x + (xb * cosine - yb * sine);
tmpRingB.y = tmpRing.y + (yb * cosine + xb * sine);
tmpRing.vx = vx * cosine - vy * sine;
tmpRing.vy = vy * cosine + vx * sine;
tmpRingB.vx = vxb * cosine - vyb * sine;
tmpRingB.vy = vyb * cosine + vxb * sine;
tmpRing.loop = true;
};
};
tmpRing.x += tmpRing.vx;
tmpRing.y += tmpRing.vy;
if (tmpRing.x - tmpRing.radius < 0) {
var sinwave = new SinWave(context);
tmpRing.x = tmpRing.radius;
tmpRing.vx *= -1;
} else if (tmpRing.x + tmpRing.radius > ctx.canvas.width) {
var sinwave = new SinWave(context);
tmpRing.x = ctx.canvas.width - tmpRing.radius;
tmpRing.vx *= -1;
};
if (tmpRing.y - tmpRing.radius < 0) {
var sinwave = new SinWave(context);
tmpRing.y = tmpRing.radius;
tmpRing.vy *= -1;
} else if (tmpRing.y + tmpRing.radius > ctx.canvas.height) {
var sinwave = new SinWave(context);
tmpRing.y = ctx.canvas.height - tmpRing.radius;
tmpRing.vy *= -1;
};
ctx.beginPath();
ctx.arc(tmpRing.x, tmpRing.y, 40, 0, Math.PI*2, false);
ctx.closePath();
ctx.stroke();
//-------------------- The addRing Function Code --------------------//
var mx, my;
var offsetX, offsetY;
//canvas.onmousedown = sglClick;
function addRing(x, y, radius, vx, vy) {
var x = mx-5;
var y = my-5;
var vx = Math.random()*6-3;
var vy = Math.random()*6-3;
rings.push(new Ring(x, y, 40, vx, vy));
}
function sglClick(e) {
getMouse(e);
addRing();
}
function getMouse(e) {
var element = ctx, offsetX = 0, offsetY = 0;
if (element.offsetParent !== undefined) {
do {
offsetX += element.offsetLeft;
offsetY += element.offsetTop;
} while ((element = element.offsetParent));
}
mx = e.pageX - offsetX;
my = e.pageY - offsetY;
}
};
if(playAnimation) {
setTimeout(animate, 33);
};
};
animate();
});
I noticed a couple of problems.
First, you misspelled SineWave in a few places. Second, you are trying to bind an event to the canvas using canvas.onmousedown = sglClick;. You should try canvas.bind('mousedown', sglClick); instead and you shouldn't do the binding inside of your animate method. It will add a new event each iteration of the animation.