I'm trying to re-create the bouncing ball effect but with an arrow.
When the arrow gets to the right wall it points left and come back until it reach the left wall and then point right again. Within a continuous loop.
I'm fairly new to JS and animation. Any help would be appreciated.
So far I have the arrow work fine back and forth, but doesn't reverse/flip when hitting the wall.
Thank you.
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<canvas id="canvas" width="500" height="400" style="border: solid; border-color: black;"></canvas>
<script type="text/javascript">
window.onload = function () {
var context;
var dx = 1;
var w3;
var ctx;
var img;
function setCanvas() {
var canvas = document.getElementById('canvas');
if (canvas.getContext) {
ctx = canvas.getContext('2d');
img = new Image();
img.onload = function (e) {
draw();
}
img.src = '/rightArrow2.png';
w3 = img.width;
draw();
}
}
var startPos = 200;
var endPos = 100;
var x = 100;
var y = 10;
function draw() {
ctx.clearRect(0, 0, 500, 500);
ctx.drawImage(img, x, y);
x += dx;
if (x < endPos || x > startPos) {
ctx.clearRect(0, 0, 500, 500);
var canvas = document.getElementById('canvas');
ctx2 = canvas.getContext('2d');
var img2 = new Image();
img2.src = document.getElementById("canvas").toDataURL();
var w4 = img2.width;
ctx2.save();
ctx2.translate(-w4, 0);
ctx2.scale(-1, 1);
ctx2.drawImage(img2, x , y);
ctx2.restore();
dx = -dx;
}
setTimeout(draw, 15);
}
setCanvas();
}
</script>
</body>
</html>
var context;
var dx= 4;
var dy=4;
var y=150;
var x=10;
function draw(){
context= myCanvas.getContext('2d');
context.clearRect(0,0,300,300);
context.beginPath();
context.fillStyle="#0000ff";
context.arc(x,y,20,0,Math.PI*2,true);
context.closePath();
context.fill();
if( x<0 || x>300)
dx=-dx;
if( y<0 || y>300)
dy=-dy;
x+=dx;
y+=dy;
}
setInterval(draw,10);
<!--
body { background-color:#ededed; font:normal 12px/18px Arial, Helvetica, sans-serif; }
#container { width:600px; margin:0 auto; }
#myCanvas { background:#fff; border:1px solid #cbcbcb; }
#nav { display:block; width:100%; text-align:center; }
#nav li { display:block; font-weight:bold; line-height:21px; text-shadow:1px 1px 1px #fff; width:100px; height:21px; padding:5px; margin:0 10px; background:#e0e0e0; border:1px solid #ccc; -moz-border-radius:4px;-webkit-border-radius:4px; border-radius:4px; float:left; }
#nav li a { color:#000; display:block; text-decoration:none; width:100%; height:100%; }
-->
<div id="container">
<canvas id="myCanvas" width="300" height="300"></canvas>
<ul id="nav">
<li>View Tutorial</li>
<li>Post Comment</li>
</ul>
</div>
Try replacing your draw() function with this:
function draw() {
ctx.clearRect(0, 0, 500, 500);
if (dx > 0) {
ctx.drawImage(img, x, y);
}
else {
ctx.save();
ctx.translate(x + img.width, y);
ctx.scale(-1, 1);
ctx.drawImage(img, 0, 0);
ctx.restore();
}
x += dx;
if (x < endPos || x > startPos) {
dx = -dx;
}
setTimeout(draw, 15);
}
Related
I want make aimbooster. (http://www.aimbooster.com/)
I don't know how to make several circles that change in size at the same time.
My drawing process is...
Create a circle.
Draw a circle changing its size.
Reset the x- and y-coordinates when a circle is clicked.
Repeat this process.
The way I've tried to solve this problem is...
I tried to combine the draw function and the CircleForm function into a class and use a repeat statement.
I keep getting errors.
How do you make multiple circles?
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
// canvas maximum, minimum size
var max_x = 610,
min_x = 30,
min_y = 30,
max_y = 466;
// Initial Circle State
var x = 200,
y = 200,
r = 1,
startAngle = 0,
endAngle = Math.PI*2;
var moving;
var inc = true;
// -------------------------------------------------------------------
class Ball {
move(){
moving = setInterval(draw, 1);
}
stop(){
clearInterval(moving);
}
position(){
x = Math.floor(Math.random() * ((max_x) - (min_x))+min_x);
y = Math.floor(Math.random() * ((max_y) - (min_y))+min_y);
}
first_size(){
r = 1;
}
moving_size(){
var size_fast = 0.09; //0.09
if(inc){
r+=size_fast;
}else{
r-=size_fast;
}
}
}
let ball = new Ball();
// ---------------------------------------------------------------------------
function macroBall(){
ball.stop();
ball.position();
ball.first_size();
ball.move();
}
function CircleForm(x,y,r,startAngle, endAngle){
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
context.beginPath();
context.arc(x,y,r,startAngle, endAngle);
context.fillStyle = "orange";
context.fill();
context.stroke();
}
function draw(){
context.clearRect(0,0,canvas.width,canvas.height);
CircleForm(x,y,r,startAngle, endAngle);
rad_check(r);
ball.moving_size();
}
// Circle radius check
function rad_check(r){
if(r>=30){
inc = false;
}
if(r<=2){
inc = true;
}
}
canvas.addEventListener('mousedown', function(e) {
getCursorPosition(canvas, e)}
);
function getCursorPosition(canvas, event) {
const rect = canvas.getBoundingClientRect()
const xpos = event.clientX - rect.left
const ypos = event.clientY - rect.top
console.log("x: " + xpos + " y: " + ypos);
judgeHit(xpos,ypos);
}
// circle click event
function judgeHit(xpos, ypos,moving){
if(Math.abs(x-xpos)<=r && Math.abs(y-ypos)<=r){
macroBall();
}
}
ball.move();
*{
margin:0;
}
html, body{
height:100%;
}
body{
background:#376481 url(bg.jpg);
background-size: 100% 100%;
}
#page-container{
width:100%;
min-height:100%;
background:url(bg_stripes.png);
}
#column{
width: 640px;
margin-left: auto;
margin-right: auto;
display:grid;
}
#top{
height:80px;
}
.nav{
height:20px;
background-color:#CCCCCC;
}
.nav ul{
padding:0px;
margin-left:220px;
text-align: center;
}
.nav ul li{
font-size:10pt;
list-style:none;
float:left
}
.nav ul li a{
text-decoration:none;
color:#4477BB;
}
#myCanvas{
background-color:white;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Aim_Boost</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div id="page-container">
<div id="top"></div>
<div id="column">
<img src="header.png" style="width: 640px; height: 116px;" alt="AimBooster">
<div id="page">
<div class="nav">
<ul>
<li>Play</li>
<li> • News</li>
<li> • FAQ</li>
<li> • Feedback</li>
<li> • Donate</li>
</ul>
</div>
<div id="thi">
<canvas id="myCanvas" width="640px" height="497px"></canvas>
</div>
</div>
</div>
</div>
<script src="javas.js"></script>
</body>
</html>
You will need to add a constructor() method to the class to start. Read about it here developer.mozilla.org. Once you have that you can use the constructor to assign the objects properties.
Push all of the objects to any array and then iterate over them to animate. This a a very basic example showing how to create multiple circles. You can also create them without a loop.
let ball1 = new Ball();
let ball2 = new Ball();
var canvas = document.getElementById("myCanvas");
var context = canvas.getContext("2d");
let balls = [];
var inc = true;
class Ball {
constructor() {
this.x = Math.random() * canvas.width;
this.y = Math.random() * canvas.height;
this.r = 4;
this.c = "orange";
this.speed = 0.5;
}
draw() {
context.beginPath();
context.arc(this.x, this.y, this.r, 0, Math.PI * 2);
context.fillStyle = this.c;
context.fill();
context.stroke();
}
grow() {
if (inc) {
this.r += this.speed;
} else {
this.r -= this.speed;
}
}
incCheck() {
if (this.r >= 30) {
inc = false;
} else if (this.r < 2) {
inc = true;
}
}
}
function createBalls() {
for (let i = 0; i < 50; i++) {
balls.push(new Ball());
}
}
createBalls();
function drawBalls() {
for (let i = 0; i < balls.length; i++) {
balls[i].draw();
balls[i].grow();
balls[i].incCheck();
}
}
setInterval(() => {
context.clearRect(0, 0, canvas.width, canvas.height);
drawBalls()
}, 50)
*{
margin:0;
}
html, body{
height:100%;
}
body{
background:#376481 url(bg.jpg);
background-size: 100% 100%;
}
#page-container{
width:100%;
min-height:100%;
background:url(bg_stripes.png);
}
#column{
width: 640px;
margin-left: auto;
margin-right: auto;
display:grid;
}
#top{
height:80px;
}
.nav{
height:20px;
background-color:#CCCCCC;
}
.nav ul{
padding:0px;
margin-left:220px;
text-align: center;
}
.nav ul li{
font-size:10pt;
list-style:none;
float:left
}
.nav ul li a{
text-decoration:none;
color:#4477BB;
}
#myCanvas{
background-color:white;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Aim_Boost</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div id="page-container">
<div id="top"></div>
<div id="column">
<img src="header.png" style="width: 640px; height: 116px;" alt="AimBooster">
<div id="page">
<div class="nav">
<ul>
<li>Play</li>
<li> • News</li>
<li> • FAQ</li>
<li> • Feedback</li>
<li> • Donate</li>
</ul>
</div>
<div id="thi">
<canvas id="myCanvas" width="640px" height="497px"></canvas>
</div>
</div>
</div>
</div>
<script src="javas.js"></script>
</body>
</html>
I just recently uploaded my code files to a server. My website is a simple html5 drawing application where users are able to draw freely. I have this part done fine, however I am looking to implement a download button that simply downloads whatever the user has drawn as an image directly to their device i.e. phone, table, desktop. I have been looking for solutions to this for hours now and cant find anything. Is it a problem with my server? or anything like that? any help would be much appreciated. Below is my code
<!DOCTYPE html>
<html>
<head>
<title>Elemental</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style type="text/css">
#import url('https://fonts.googleapis.com/css?family=Montserrat+Alternates');
#media screen and (max-width: 425px){
html,body{
overflow-x: hidden;
width: 100%;
margin: 0;
}
canvas { border: 3px solid #0BF446;
border-radius: 15px 0px 15px 0px;
display: block;
margin: 0 auto;
margin-top: 35px;
background-color:#313131;
position: relative;}
#download{background-color:#04A12B ;
border-radius: 0 15px 0 15px;
padding: 20px 40px;
margin: 0 auto;
display: block;
font-size: 14px;
margin-top: 35px;
color: white;
font-family: 'Montserrat Alternates', sans-serif;}
#clearbutton{background-color:#04A12B ;
border-radius: 0 15px 0 15px;
padding: 20px;
margin: 0 auto;
display: block;
font-size: 14px;
color: white;
font-family: 'Montserrat Alternates', sans-serif;
margin-top: 35px;}
</style>
</head>
<body>
<body onload="init()">
<img src="minilogo.png" id ="logo">
<canvas id="c" width="350px" height="350px"></canvas>
<button id = "download">Download</button>
<input type = "submit" value="Clear Sketchpad" id="clearbutton" onclick="clearCanvas(canvas,ctx);">
<script>
function init() {
// Get the specific canvas element from the HTML document
canvas = document.getElementById('c');
}
function midPointBtw(p1, p2) {
return {
x: p1.x + (p2.x - p1.x) / 2,
y: p1.y + (p2.y - p1.y) / 2
};
}
function getPattern() {
return ctx.createPattern(img, 'repeat');
}
var el = document.getElementById('c');
var ctx = el.getContext('2d');
ctx.lineWidth = 30;
ctx.lineJoin = ctx.lineCap = 'round';
var img = new Image;
img.onload = function() {
ctx.strokeStyle = getPattern();
};
img.src = "https://i.postimg.cc/rF2R0GRY/dick2.png";
var isDrawing, points = [];
var getXY = function(e) {
var source = e.touches ? e.touches[0] : e;
return {
x: source.clientX,
y: source.clientY
};
};
var startDrawing = function(e) {
isDrawing = true;
points.push(getXY(e));
event.preventDefault();
};
var keepDrawing = function(e) {
if (!isDrawing) return;
points.push(getXY(e));
ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
var p1 = points[0];
var p2 = points[1];
ctx.moveTo(p1.x, p1.y);
for (var i = 1, len = points.length; i < len; i++) {
var midPoint = midPointBtw(p1, p2);
ctx.quadraticCurveTo(p1.x, p1.y, midPoint.x, midPoint.y);
p1 = points[i];
p2 = points[i + 1];
}
ctx.lineTo(p1.x, p1.y);
ctx.stroke();
event.preventDefault();
};
var stopDrawing = function() {
isDrawing = false;
points = [];
};
el.addEventListener('touchstart', startDrawing);
el.addEventListener('mousedown', startDrawing);
el.addEventListener('touchmove', keepDrawing);
el.addEventListener('mousemove', keepDrawing);
el.addEventListener('touchend', stopDrawing);
el.addEventListener('mouseup', stopDrawing);
function clearCanvas(canvas,ctx) {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.beginPath()
}
</script>
</body>
</html>
You can use the Canvas#toDataURL method to generate a URL containing all the data of the canvas's current image. This can then be used in place of any URL -- a link's href, a window.open, etc. For a download link, you can use the download attribute on a link, which is an HTML5 addition. The value of the download attribute is the filename that will be used as the default save filename.
So to put all that together:
<a id='downloadLink' download='myDrawing.png'>Download Image</a>
<script>
function createDownload() {
const downloadURL = document.getElementById('c').toDataURL();
document.getElementById('downloadLink').href = downloadURL;
}
</script>
So I'm just trying to make a simple animated HMTL canvas with an animated block that moves around the canvas using WASD. I initially noticed that painting a rectangle on the canvas of size 5,5 made what looked like a rectangle of size 5,10. When testing my redrawing function and printing to the console the x and y location of the element in the canvas, I noticed that my rectangle can go from 1-300 in the X direction, but only 1-150 in the Y direction. This happens even though the canvas is styled as 300,300. Can anyone figure out if I've done something silly?
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
<script type="text/javascript" src="script.js" defer></script>
</head>
<body>
<div class="text-holder holder" id="instruction-holder">
<p class="text" id="instruction">Use WASD to navigate around the viewer</p>
</div>
<div class="holder" id="canvas-holder">
<canvas id="canvas"></canvas>
</div>
</body>
</html>
and the css
#canvas {
width: 300px;
height:300px;
margin-left: auto;
margin-right: auto;
display: block;
border-style: solid;
border-color: grey;
border-radius: 1px;
}
.holder {
display: block;
margin-left: auto;
margin-right: auto;
text-align: center;
}
and the js
var UP = "87", DOWN = "83", LEFT = "65", RIGHT = "68", X = 10, Y = 5, XSIZE = 10, YSIZE = 5;
var c = document.getElementById("canvas");
var ctx = c.getContext("2d");
var xPos, yPos;
window.addEventListener("load",init);
document.addEventListener('keydown',move);
function init() {
xPos = 1;
yPos = 1;
ctx.fillStyle = "black";
ctx.fillRect(xPos,yPos,XSIZE,YSIZE);
}
function clear() {
ctx.clearRect(0,0,300,300);
}
function reDraw(delX, delY) {
console.log(yPos+delY + " " + (xPos+delX));
if (xPos+delX > 0 && xPos+delX < 300 &&
yPos+delY > 0 && yPos+delY < 150) {
clear();
ctx.fillStyle = "black";
xPos = xPos+delX;
yPos = yPos+delY;
ctx.fillRect(xPos,yPos,XSIZE,YSIZE);
}
}
function move(ev) {
var delX, delY;
var key = ev.keyCode;
if (key == UP) {
delX = 0;
delY = -Y;
} else if (key == DOWN) {
delX = 0;
delY = Y;
} else if (key == LEFT) {
delX = -X;
delY = 0;
} else if (key == RIGHT) {
delX = X;
delY = 0;
}
if (delX != undefined && delY != undefined) {
reDraw(delX, delY);
}
}
You have to set the size of canvas explicitly or it will use the default size of 300x150 (CSS only scales the element, not the bitmap - the bitmap of 300x150 is stretched to fit what you see on screen by the CSS rule, but the bitmap will remain the same size internally):
<canvas id="canvas" width=300 height=300></canvas>
Then just remove these:
#canvas {
/* width: 300px; */
/* height:300px; */
...
i have create the canvas which has different background and over that another image in the middle of canvas,now i want to rotate that image at 90 at its place only,i tried lots of code but get nothing as result. how can i do that..??
<style type="text/css" media="screen">
canvas, img { display:block; margin:1em auto; border:1px solid black; }
canvas { background:url(http://i.dailymail.co.uk/i/pix/2013/11/11/article-2500617-007F32C500000258-970_306x423.jpg) }
</style>
</head><body>
<button id="clockwise">Rotate right</button>
<canvas width="300" height="300"></canvas>
<img>
<script type="text/javascript" charset="utf-8">
var can = document.getElementsByTagName('canvas')[0];
var ctx = can.getContext('2d');
ctx.strokeStyle = '#f00';
ctx.lineWidth = 6;
ctx.lineJoin = 'round';
ctx.strokeRect(40,100,150,100);
var angleInDegrees=0;
var img = document.getElementsByTagName('img')[0];
img.src="http://media1.santabanta.com/full1/Miscellaneous/Cartoon%20Characters/cartoon-characters-47a.jpg";
ctx.drawImage(img,40,100,150,100);
function drawRotated(degrees){
ctx.clearRect(40,100,150,100);
ctx.save();
ctx.translate(40,100,150,100);
ctx.rotate(degrees*Math.PI/180);
ctx.drawImage(img,-img.width/2,-img.width/2);
ctx.restore();
}
$("#clockwise").click(function(){
angleInDegrees+=30;
drawRotated(angleInDegrees);
});
</script>
</body></html>
On my website, I want do render a <canvas> on top of a <div> with some other <div>'s in it. This is all working okay, however, drawing in the canvas is not possible, because it's positioned under the main <div>. You can test it in the codepen below. You can only draw on a small strip near the bottom.
Codepen: http://codepen.io/anon/pen/hfmBG
Code:
<html>
<head>
<script type="text/javascript">
var canvas, ctx, flag = false,
prevX = 0,
currX = 0,
prevY = 0,
currY = 0,
dot_flag = false;
var x = "#000",
y = 1;
function init() {
canvas = document.getElementById('can');
ctx = canvas.getContext("2d");
w = canvas.width;
h = canvas.height;
canvas.addEventListener("mousemove", function (e) {
findxy('move', e)
}, false);
canvas.addEventListener("mousedown", function (e) {
findxy('down', e)
}, false);
canvas.addEventListener("mouseup", function (e) {
findxy('up', e)
}, false);
canvas.addEventListener("mouseout", function (e) {
findxy('out', e)
}, false);
}
function draw() {
ctx.beginPath();
ctx.moveTo(prevX, prevY);
ctx.lineTo(currX, currY);
ctx.strokeStyle = x;
ctx.lineWidth = y;
ctx.stroke();
ctx.closePath();
}
function erase() {
var m = confirm("Want to clear");
if (m) {
ctx.clearRect(0, 0, w, h);
document.getElementById("canvasimg").style.display = "none";
}
}
function findxy(res, e) {
if (res == 'down') {
prevX = currX;
prevY = currY;
currX = e.clientX - canvas.offsetLeft;
currY = e.clientY - canvas.offsetTop;
flag = true;
dot_flag = true;
if (dot_flag) {
ctx.beginPath();
ctx.fillStyle = x;
ctx.fillRect(currX, currY, 2, 2);
ctx.closePath();
dot_flag = false;
}
}
if (res == 'up' || res == "out") {
flag = false;
}
if (res == 'move') {
if (flag) {
prevX = currX;
prevY = currY;
currX = e.clientX - canvas.offsetLeft;
currY = e.clientY - canvas.offsetTop;
draw();
}
}
}
function print(){
var c = document.getElementById("can");
var ctx = c.getContext("2d");
var imgData = ctx.getImageData(10,10,50,50);
console.log(imgData);
}
</script>
<style>
.patternlockbutton{
border-color: red;
background-color: transparent;
background-repeat:no-repeat;
display:block;
width:33px;
height:33px;
float:left;
margin:26px;
z-index:1;
-ms-touch-action: none;
border-style: solid;
border-width: 5px;
-webkit-border-top-left-radius: 50px;
-webkit-border-top-right-radius: 50px;
-moz-border-radius-topleft: 50px;
-moz-border-radius-topright: 50px;
border-top-left-radius: 50px;
border-top-right-radius: 50px;
-webkit-border-bottom-left-radius: 50px;
-webkit-border-bottom-right-radius: 50px;
-moz-border-radius-bottomleft: 50px;
-moz-border-radius-bottomright: 50px;
border-bottom-left-radius: 50px;
border-bottom-right-radius: 50px;
}
#can {
z-index: 99;
display: block;
}
</style>
</head>
<body onload="init()">
<div style="width:300px;height:400px;">
<div class="patternlockbutton" id="patternlockbutton1"></div>
<div class="patternlockbutton" id="patternlockbutton2"></div>
<div class="patternlockbutton" id="patternlockbutton3"></div>
<div class="patternlockbutton" id="patternlockbutton4"></div>
<div class="patternlockbutton" id="patternlockbutton5"></div>
<div class="patternlockbutton" id="patternlockbutton6"></div>
<div class="patternlockbutton" id="patternlockbutton7"></div>
<div class="patternlockbutton" id="patternlockbutton8"></div>
<div class="patternlockbutton" id="patternlockbutton9"></div>
<canvas id="can" width="300px" height="400px"></canvas>
</div>
<input type="button" value="clear" id="clr" size="23" onclick="erase()" style="position:absolute;top:55%;left:15%;">
<button onclick="print()">Console.log</button>
</body>
</html>
If you want to position an HTML element on top of other elements, you should set its position: absolute in CSS.
In your case, the parent div of the canvas should have this style applied:
position: relative;
The canvas should have this style applied:
position: absolute;
top: 0;
left: 0;