Moving and rotating with HTML5 - javascript

What needs to be done:
The pink object should move from the left to the right (by itself). And then when it's 5px from the edge it should rotate 90 degrees.
Does anyone know how to do this?
I haven't been learning javascript for a long time, and it's the first time I'm creating something using HTML5. So it's all new. I really hope you can help me understand the code better and how I can make it move and rotate.
<!DOCTYPE html>
<html>
<head>
<script>
var canvas, ctx;
window.onload = function draw() {
canvas = document.getElementById("myCanvas");
ctx = canvas.getContext("2d");
var height = 90;
var width = 40;
var radius = width / 2;
ctx.clearRect(0,0, canvas.width, canvas.height);
ctx.fillStyle = "#FFE2E8";
ctx.strokeStyle = "black";
ctx.beginPath();
ctx.moveTo(20,20);
ctx.lineTo(70,20);
ctx.arc(70,40,20, -Math.PI/2, Math.PI/2);
ctx.lineTo(20,60);
ctx.lineTo(20,20);
ctx.closePath;
ctx.fill();
ctx.stroke();
requestAnimationFrame(draw);
}
function init() {
canvas = document.getElementById("myCanvas");
ctx = canvas.getContext("2d");
draw();
}
</script>
</head>
<body>
<canvas id="myCanvas" width="400" height="300" style="background:#00CC66">
</canvas>
</body>
</html>

var canvas, ctx;
canvas = document.getElementById("myCanvas");
ctx = canvas.getContext("2d");
var radius = 20;
var width = 70;
var margin = 5;
var offsetx = -20
var translate = {
x: 0,
y: 0,
xmax: canvas.width - margin - width + offsetx,
ymax: canvas.height - margin - width
};
var rotate = 0;
var to_radians = Math.PI / 180;
function draw() {
ctx.save();
ctx.translate(translate.x, translate.y);
if (translate.x >= translate.xmax) {
translate.x = translate.xmax;
if (rotate >= 90) {
rotate = 90;
} else {
rotate++;
}
ctx.rotate(rotate * to_radians);
} else {
translate.x++;
}
var height = 90;
var width = 40;
var radius = width / 2;
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = "#FFE2E8";
ctx.strokeStyle = "black";
ctx.beginPath();
ctx.moveTo(20, 20);
ctx.lineTo(70, 20);
ctx.arc(70, 40, 20, -Math.PI / 2, Math.PI / 2);
ctx.lineTo(20, 60);
ctx.lineTo(20, 20);
ctx.closePath;
ctx.fill();
ctx.stroke();
ctx.restore();
requestAnimationFrame(draw);
}
function init() {
canvas = document.getElementById("myCanvas");
ctx = canvas.getContext("2d");
draw();
}
init();
<canvas id="myCanvas" width="400" height="300" style="background:#00CC66">
</canvas>

Related

How to move the text inside the canvas like the text bar animated?

I'm drawing canvas and have put in some shapes and text and I want to move the text inside the canvas like the text bar animated from left to right
As you can see, when I'm moving the text is moving not like it supposed to be.
How can I fix it?
<script>
var pointX, pointY , w , h ;
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
c.width = window.innerWidth;
c.height = window.innerHeight;
ctx.clearRect(0, 0, ctx.canvas.width,ctx.canvas.height);
ctx.beginPath();
ctx.strokeStyle='red';
ctx.strokeRect(10,0,720,576);
ctx.closePath();
ctx.beginPath();
ctx.fillStyle='grey';
ctx.fillRect(10,525,720,50);
ctx.closePath();
ctx.beginPath();
var start = 10;
setInterval(function(){
start += 4;
ctx.font = "30px Arial";
ctx.fillStyle = "red";
ctx.textAlign = "left";
ctx.fillText("Hello World",start, 560);
}, 40);
ctx.closePath();
pointX = 690;
pointY = 550;
w = 30;
h = 20;
ctx.beginPath();
ctx.strokeStyle='red';
ctx.strokeRect(pointX,pointY,w,h);
ctx.closePath();
</script>
<!DOCTYPE html>
<html>
<head>
<script src ="js/jquery-3.3.1.min.js" ></script>
<link href ="css/bootstrap.min.css" rel="stylesheet">
<script src ="js/bootstrap.min.js" ></script>
<meta charset="utf-8">
<meta name = "viewport" content = "width=device-width; initial-scale=1.0; maximum-scale=1.0; user-scalable=0"/>
</head>
<body dir="rtl" id="tbodyid">
<canvas id="myCanvas" width="1050" height="1050" class="col-12 col-s-12" >
</canvas>
</body>
</html>
As I've commented, inside your setInterval function you should add ctx.clearRect(0,0,c.width,c.height). Also you have to redraw everything else. So I've putted your shapes inside functions, and I'm calling those functions inside setInterval too.
var pointX, pointY , w , h ;
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
c.width = 1000;
c.height = 650;
ctx.clearRect(0, 0, ctx.canvas.width,ctx.canvas.height);
function drawShape1(){
ctx.beginPath();
ctx.strokeStyle='red';
ctx.strokeRect(10,0,720,576);
ctx.closePath();
ctx.beginPath();
ctx.fillStyle='grey';
ctx.fillRect(10,525,720,50);
ctx.closePath();
}
function drawShape2(){
pointX = 690;
pointY = 550;
w = 30;
h = 20;
ctx.beginPath();
ctx.strokeStyle='red';
ctx.strokeRect(pointX,pointY,w,h);
ctx.closePath();
}
var start = 10;
setInterval(function(){
ctx.clearRect(0,0,c.width,c.height)
drawShape1()
start += 4;
ctx.font = "30px Arial";
ctx.fillStyle = "red";
ctx.textAlign = "left";
ctx.fillText("Hello World",start, 560);
drawShape2()
}, 40);
<canvas id="myCanvas" width="1000" height="650" class="col-12 col-s-12" ></canvas>
However if you want to try using requestAnimationFrame instead of setInterval this is how to do it:
Since requestAnimationFrame runs at 60 frames per sec I've changed start += 4; to start += 2;
var pointX, pointY , w , h ;
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
c.width = 1000;
c.height = 650;
ctx.clearRect(0, 0, ctx.canvas.width,ctx.canvas.height);
function drawShape1(){
ctx.beginPath();
ctx.strokeStyle='red';
ctx.strokeRect(10,0,720,576);
ctx.closePath();
ctx.beginPath();
ctx.fillStyle='grey';
ctx.fillRect(10,525,720,50);
ctx.closePath();
}
function drawShape2(){
pointX = 690;
pointY = 550;
w = 30;
h = 20;
ctx.beginPath();
ctx.strokeStyle='red';
ctx.strokeRect(pointX,pointY,w,h);
ctx.closePath();
}
var start = 10;
function frame(){
requestAnimationFrame(frame)
ctx.clearRect(0,0,c.width,c.height)
drawShape1()
start += 2;
ctx.font = "30px Arial";
ctx.fillStyle = "red";
ctx.textAlign = "left";
ctx.fillText("Hello World",start, 560);
drawShape2()
}
frame()
<canvas id="myCanvas" width="1050" height="1050" class="col-12 col-s-12" >
</canvas>
<canvas id="myCanvas" width="1050" height="1050" class="col-12 col-s-12" >
</canvas>
<script>
var pointX, pointY , w , h ;
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
c.width = 1000;
c.height = 650;
ctx.clearRect(0, 0, ctx.canvas.width,ctx.canvas.height);
function drawShape1(){
ctx.beginPath();
ctx.strokeStyle='red';
ctx.strokeRect(10,0,720,70);
ctx.closePath();
ctx.beginPath();
ctx.fillStyle='gold';
ctx.fillRect(10,10,720,50);
ctx.closePath();
}
function drawShape2(){
pointX = 690;
pointY = 30;
w = 30;
h = 20;
ctx.beginPath();
ctx.strokeStyle='red';
ctx.strokeRect(pointX,pointY,w,h);
ctx.closePath();
}
var start = 10;
function frame(){
requestAnimationFrame(frame)
ctx.clearRect(0,0,c.width,c.height)
drawShape1()
start += 2;
ctx.font = "30px Arial";
ctx.fillStyle = "red";
ctx.textAlign = "left";
ctx.fillText("Hello World",start, 50);
if (start > 576) start = 0;
drawShape2()
}
frame()
</script>

Making an object move back and forth in javascript [duplicate]

So I have this rectangle that animates across to the right. How can I get the rectangle to reverse it when it hits the boundaries. I'm trying to make it go back and forth.
<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'>
window.onload=function(){
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
var x = 0;
var y = 50;
var width = 10;
var height = 10;
function animate() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.fillRect(x, y, width, height);
x++;
if(x <= 490) {
setTimeout(animate, 33);
}
}
animate();
}
</script>
</head>
<body>
<canvas id="canvas" width="500" height="400"
style="border: 1px solid #000000;"></canvas>
</body>
</html>
https://codepen.io/forTheLoveOfCode/pen/wqdpeg
Is that what you need? (link to codepen above).
var canvas = document.getElementById("canvas_id");
var context = canvas.getContext('2d');
var x=5;
var y=5;
var velocity = 10;
function move(){
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
x =x + velocity
if ((x+50)>canvas.width || x<0){
velocity *=-1;
}
draw()
}
function draw(){
context.fillStyle = "#E80C7A";
context.strokeStyle = "#000000";
context.lineWidth = '3';
context.fillRect(x, y, 50, 100);
context.strokeRect(x, y, 50, 100);
}
setInterval(move, 100);
<html>
<body>
<canvas id = "canvas_id">
</canvas>
</body>
</html>
here's a solution with boundaries detection
window.onload=function(){
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
var x = 0;
var y = 50;
var width = 10;
var height = 10;
var speed = 10; // speed
function animate() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.fillRect(x, y, width, height);
if(
(x >= 500 - width && speed > 0) || // going to the right and bound reached
(x <= 0 && speed < 0) // going to the left and bound reached
) {
speed *= -1; // inverting the direction
}
x += speed;
setTimeout(animate, 33);
}
animate();
}
<canvas id="canvas" width="500" height="400"
style="border: 1px solid #000000;"></canvas>
consider using requestAnimationFrame instead of setTimeout to do this kind of work.

Onclick function for my shape

I need to add click to my star to turn it green. The variable is called "colorchoice" and I can't figure it out. Its a modified pong game i had to do for a project, i just can't figure out the onclick for the shape, and it needs to be vairable for wherever the star moves to.
<!doctype html>
<html>
<head>
<meta charset="UTF-8" />
<title>Mayo's Pong Game</title>
</head>
<body bgcolor="grey">
<section>
<div>
<canvas id="canvas" width="500" height="500">
This text is displayed if your browser
does not support HTML5 Canvas.
</canvas>
</div>
<script type="text/javascript">
var canvas = document.getElementById('canvas');
// var context = canvas.getContext('2d');
canvas.addEventListener('mousemove', function(evt) {
var mousePos = getMousePos(canvas, evt);
message = 'LEVEL '+level+' Score= '+score+' Lives= '+lives;
//writeMessage(canvas, message);
paddley=mousePos.y -(rpheight/2);
if (paddley+60 > 500) {
paddley = 440;
}
paddley2=mousePos.y -(lpheight/2);
if (paddley2+60 > 500) {
paddley2 = 440;
}
}, false);
// var canvas;
var ctx;
var x = 250;
var y = 50;
var WIDTH = 520;
var HEIGHT = 520;
var message;
var level=1;
var score = 0;
var lives = 20;
var colorchoice;
function drawStar(cx, cy, spikes, outerRadius, innerRadius) {
var rot = Math.PI / 2 * 3;
var x = cx;
var y = cy;
var step = Math.PI / spikes;
ctx.strokeSyle = "#000";
ctx.beginPath();
ctx.moveTo(cx, cy - outerRadius)
for (i = 0; i < spikes; i++) {
x = cx + Math.cos(rot) * outerRadius;
y = cy + Math.sin(rot) * outerRadius;
ctx.lineTo(x, y)
rot += step
x = cx + Math.cos(rot) * innerRadius;
y = cy + Math.sin(rot) * innerRadius;
ctx.lineTo(x, y)
rot += step
}
ctx.lineTo(cx, cy - outerRadius)
ctx.closePath();
ctx.lineWidth=3;
ctx.strokeStyle=colorchoice;
ctx.stroke();
ctx.fillStyle=colorchoice;
ctx.fill();
}
function circle(x,y,r) {
ctx.beginPath();
ctx.arc(x, y, r, 0, Math.PI*2, true);
ctx.fill();
}
function rect(x,y,w,h) {
ctx.beginPath();
ctx.rect(x,y,w,h);
ctx.closePath();
ctx.fill();
}
function clear() {
ctx.clearRect(0, 0, WIDTH, HEIGHT);
}
function init() {
canvas = document.getElementById("canvas");
ctx = canvas.getContext("2d");
return setInterval(draw, 15);
}
function draw() {
clear();
ctx.fillStyle = 'grey';
rect(0,0,WIDTH,HEIGHT);
ctx.fillStyle = 'black';
drawStar(x, y,5,20,10);
writeMessage(canvas,message);
}
function writeMessage(canvas, message) {
var context = canvas.getContext('2d');
//context.clearRect(0, 0, canvas.width, canvas.height);
context.font = '18pt Calibri';
context.fillStyle = 'black';
context.fillText(message, 20, 20);
}
init();
function getMousePos(canvas, evt) {
var rect = canvas.getBoundingClientRect();
return {
x: evt.clientX,
y: evt.clientY
};
}
</script>
</section>
<p>AUSTIN MAYO'S PONG GAME<p>
Pick a color for your paddles and balls, then click start.<br>
Warning: If you click the start button more than once, difficulty will increase!!!<p>
<button type="button" onclick="alert('PAUSED')">PAUSE</button>
<button type="button" onclick="location.reload();">RESTART</button>
<button type="button" onclick="init(canvas);">START</button>
<br>
<p>GAME MUSIC<BR>
<audio controls>
<source src="SOUNDTRACK.mp3" type="audio/mpeg">
Your browser does not support the audio element.
</audio>
</body>
</html>

Draw a circle in the middle of canvas

Having -
HTML -
<canvas id="myCanvas" >
</canvas>
<script>
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
var centerX = canvas.width / 2;
var centerY = canvas.height / 2;
var radius = 30;
context.beginPath();
context.arc(centerX,centerY, radius, 0, 2 * Math.PI);
context.fillStyle = 'blue';
context.fill();
</script>
CSS-
#myCanvas {
border:2px solid;
display:inline-block;
width:500px;
height:400px;
}
http://jsfiddle.net/urielz/3E656/
but I get not accurate circle . How can I make it accurate circle ?
Demo Fiddle
If you just want set the canvas size in CSS, change your code to:
<canvas id="myCanvas"></canvas>
<script>
var canvas = document.getElementById('myCanvas');
var style = window.getComputedStyle(canvas);
if (canvas.getContext) {
canvas.width = parseInt(style.getPropertyValue('width'));
canvas.height = parseInt(style.getPropertyValue('height'));
}
var context = canvas.getContext('2d');
var centerX = canvas.width / 2;
var centerY = canvas.height / 2;
var radius = 30;
context.beginPath();
context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
context.fillStyle = 'blue';
context.fill();
context.lineWidth = 5;
context.strokeStyle = '#003300';
context.stroke();
this.arc(x, y, radius, 0, Math.PI * 2, false);
this.fill();
</script>
You need to set explicitly the size of your canvas, otherwise it will get the default size: 300x150.
you should do something like this
<canvas id="myCanvas" width="500" height="400"></canvas>
or via javascript (before getting the context)
canvas.width = 500;
canvas.height = 400;
var context = canvas.getContext('2d');
You need to set the width of your canvas, like so:
<canvas id="myCanvas" width="500" height="400"></canvas>
Place below code after begin path:
var centerX = canvas.width;
var centerY = canvas.height;
context.arc(centerX*0.5,centerY*0.5,10,0 ,radius, 0, 2 * Math.PI);
Css:
#myCanvas {
border:2px solid;
display:inline-block;
width:600px;
height:300px;
}

Adding alert to canvas faces

I'm currently trying to make so that when you click on one of the happy face you get an alert box which says "thanks for the feed back", but I'm currently not sure to to incoperate that in tho my code! Thanks! Here is the fiddle http://jsfiddle.net/bsjs9/
<html lang="en">
<head>
<meta charset="utf-8" />
<title>SmileMore</title>
</head>
<body>
<h1>
Bring your Charts to life with HTML5 Canvas</h1>
</hgroup>
<p>
Rendering Dynamic charts in JS
</p>
<div class="smile">
<canvas id="myDrawing" width="200" height="200" style="border:1px solid #EEE"></canvas>
<canvas id="canvas" width="200" height="200" style="border:1px solid #EEE"></canvas>
</div>
<script>
var FacePainter = function(canvasName)
{
var canvas = document.getElementById(canvasName);
var ctx = canvas.getContext("2d");
var x = canvas.width / 2;
var y = canvas.height / 2;
var radius = 75;
var startAngle = 0;
var endAngle = 2 * Math.PI;
function drawFace() {
ctx.beginPath();
ctx.arc(x, y, radius, startAngle, endAngle);
ctx.stroke();
ctx.fillStyle = "yellow";
ctx.fill();
}
function drawSmile(startAngle, endAngle)
{
var x = canvas.width / 2;
var y = 150;
var radius = 40;
ctx.beginPath();
ctx.arc(x, y, radius, startAngle * Math.PI, endAngle * Math.PI);
ctx.lineWidth = 7;
// line color
ctx.strokeStyle = 'black';
ctx.stroke();
}
function drawEyes() {
var centerX = 40;
var centerY = 0;
var radius = 10;
// save state
ctx.save();
// translate context so height is 1/3'rd from top of enclosing circle
ctx.translate(canvas.width / 2, canvas.height / 3);
// scale context horizontally by 50%
ctx.scale(.5, 1);
// draw circle which will be stretched into an oval
ctx.beginPath();
ctx.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
// restore to original state
ctx.restore();
// apply styling
ctx.fillStyle = 'black';
ctx.fill();
ctx.lineWidth = 2;
ctx.strokeStyle = 'black';
ctx.stroke();
//left eye
var centerX = -40;
var centerY = 0;
var radius = 10;
// save state
ctx.save();
// translate context so height is 1/3'rd from top of enclosing circle
ctx.translate(canvas.width / 2, canvas.height / 3);
// scale context horizontally by 50%
ctx.scale(.5, 1);
// draw circle which will be stretched into an oval
ctx.beginPath();
ctx.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
// restore to original state
ctx.restore();
// apply styling
ctx.fillStyle = 'black';
ctx.fill();
ctx.lineWidth = 2;
ctx.strokeStyle = 'black';
ctx.stroke();
}
this.drawHappyFace = function() {
drawFace();
drawEyes();
drawSmile(1.1, 1.9);
}
this.drawSadFace = function() {
drawFace();
drawEyes();
drawSmile(1.9, 1.1);
;
}
}
new FacePainter('canvas').drawHappyFace();
new FacePainter('myDrawing').drawSadFace();
</script>
</body>
</html>
</body>
</html>
As an extra assignment I would like to know if anyone knows how to fix the "happy" smile, its kinda way off! Thanks all!
Since you draw the happy face on its own canvas, you can simple put an onclick handler on the canvas.
<canvas id="myDrawing" width="200" height="200" style="border:1px solid #EEE" onclick="alert('thanks');"></canvas>
Regarding the smiles, I added a new ofsy parameter to drawSmile, which offsets the arc origin vertically.
Here is the updated fiddle.
If you only want to show the alert, when the user clicks inside the face, you need to get the click coordinates and hittest it against the circle. You can see this in this fiddle.

Categories

Resources