How to make Pottermore-like animated cursor - javascript

I've tried CSS cursor property
How to create a cursor like this webpage
https://my.pottermore.com/patronus

You can create such effects using css and JavaScript:
var standardbody=(document.compatMode=="CSS1Compat")? document.documentElement : document.body //create reference to common "body" across doctypes
var nav = (!document.all || window.opera);
var tmr = null;
var spd = 50;
var x = 0;
var x_offset = 5;
var y = 0;
var y_offset = 15;
document.onmousemove = get_mouse;
function get_mouse(e)
{
x = (nav) ? e.pageX : event.clientX+standardbody.scrollLeft;
y = (nav) ? e.pageY : event.clientY+standardbody.scrollTop;
x += x_offset;
y += y_offset;
beam(1);
}
function beam(n)
{
if(n<5)
{
document.getElementById('div'+n).style.top=y+'px'
document.getElementById('div'+n).style.left=x+'px'
document.getElementById('div'+n).style.visibility='visible'
n++;
tmr=setTimeout("beam("+n+")",spd);
}
else
{
clearTimeout(tmr);
fade(4);
}
}
function fade(n)
{
if(n>0)
{
document.getElementById('div'+n).style.visibility='hidden'
n--;
tmr=setTimeout("fade("+n+")",spd);
}
else clearTimeout(tmr);
}
body{
overflow-x:hidden;
}
.s1
{
position : absolute;
font-size : 10pt;
color : blue;
visibility: hidden;
}
.s2
{
position : absolute;
font-size : 18pt;
color : red;
visibility : hidden;
}
.s3
{
position : absolute;
font-size : 14pt;
color : gold;
visibility : hidden;
}
.s4
{
position : absolute;
font-size : 12pt;
color : lime;
visibility : hidden;
}
<div id="div1" class="s1">*</div>
<div id="div2" class="s2">*</div>
<div id="div3" class="s3">*</div>
<div id="div4" class="s4">*</div>
This code can be found at: http://www.javascriptkit.com/script/script2/sparkler.shtml
OR if you do not want to use any HTML elements for your mouse trails you can use the following CSS and JS:
var dots = [],
mouse = {
x: 0,
y: 0
};
var Dot = function() {
this.x = 0;
this.y = 0;
this.node = (function(){
var n = document.createElement("div");
n.className = "tail";
document.body.appendChild(n);
return n;
}());
};
Dot.prototype.draw = function() {
this.node.style.left = this.x + "px";
this.node.style.top = this.y + "px";
};
for (var i = 0; i < 12; i++) {
var d = new Dot();
dots.push(d);
}
function draw() {
var x = mouse.x,
y = mouse.y;
dots.forEach(function(dot, index, dots) {
var nextDot = dots[index + 1] || dots[0];
dot.x = x;
dot.y = y;
dot.draw();
x += (nextDot.x - dot.x) * .6;
y += (nextDot.y - dot.y) * .6;
});
}
addEventListener("mousemove", function(event) {
mouse.x = event.pageX;
mouse.y = event.pageY;
});
function animate() {
draw();
requestAnimationFrame(animate);
}
animate();
.tail {
position: absolute;
height: 6px; width: 6px;
border-radius: 3px;
background: tomato;
}
This Code Can be found at : https://codepen.io/falldowngoboone/pen/PwzPYv

Related

trail without a canvas

I've created the following code and I would like to have a trail following the dropped ball.
JSFiddle: https://jsfiddle.net/uj896hmq/72/
Code
var generateGame = function(){
var string = "";
var discAmount = 0;
for(var x = 0; x < 13; x++){
discAmount++;
string += "<div class='row'>";
for(var y = 1; y <= discAmount; y++){
string += "<div class='disc'></div>";
}
string += "</div>";
}
$('.board .wrapper').append(string);
var getPosition = $('.board').find('.disc').eq(0),
top = getPosition.position().top,
left = getPosition.position().left;
var $el = $('<div class="falling"></div>');
$('.board .wrapper').prepend($el);
$el.css({
top: top,
left: left
});
}
generateGame();
$(document).on('click', 'button', function(){
startGame();
});
var startGame = function(){
var $board = $('.board .wrapper'),
$el = $(".falling");
var currentRow = 0,
path = generatePath();
setInterval(function(){
var getPosition = $board.find('.row').eq(currentRow).find('.disc').eq(path[currentRow]),
top = getPosition.position().top,
left = getPosition.position().left;
$el.animate({
top: top,
left: left
}, 500);
//random between 1-2, 3-5, 4-8
currentRow++;
}, 500);
}
var generatePath = function(){
var path = [0];
for(var x = 1; x < 13; x++){
var previousPath = path[x - 1];
var randomPath = generateNext(previousPath, (previousPath + 1));
path.push(randomPath);
}
return path;
}
function generateNext(min,max){
return Math.floor(Math.random()*(max-min+1)+min);
}
console.log(generatePath());
Point is I have no idea how I would achieve this with regular javascript and or jQuery, I thought of maybe placing a lot of divs at the position of the ball but that didn't seem proper.
Anyone has any ideas?
You can use SVG to dynamically add lines to the HTML without canvas. I've created a crude example that you can refer to. Basically it is just some calculations to position the lines.
var generateGame = function() {
var string = "";
var discAmount = 0;
for (var x = 0; x < 13; x++) {
discAmount++;
string += "<div class='row'>";
for (var y = 1; y <= discAmount; y++) {
string += "<div class='disc'></div>";
}
string += "</div>";
}
$('.board .wrapper').append(string);
var getPosition = $('.board').find('.disc').eq(0),
top = getPosition.position().top,
left = getPosition.position().left;
var $el = $('<div class="falling"></div>');
$('.board .wrapper').prepend($el);
$el.css({
top: top,
left: left
});
}
generateGame();
$(document).on('click', 'button', function() {
startGame();
});
var startGame = function() {
var $board = $('.board .wrapper'),
$el = $(".falling"),
$trail = $('.trail'),
$prevDisc = null;
var currentRow = 0,
path = generatePath();
$trail.empty();
setInterval(function() {
var getPosition = $board.find('.row').eq(currentRow).find('.disc').eq(path[currentRow])
if (getPosition.length > 0) {
var top = getPosition.position().top,
left = getPosition.position().left;
if ($prevDisc) {
var isLeft = left < $prevDisc.position().left;
drawPath($prevDisc.position().left, currentRow - 1, isLeft);
}
$prevDisc = getPosition;
$el.animate({
top: top,
left: left
}, 500);
//random between 1-2, 3-5, 4-8
currentRow++;
}
}, 500);
}
var generatePath = function() {
var path = [0];
for (var x = 1; x < 13; x++) {
var previousPath = path[x - 1];
var randomPath = generateNext(previousPath, (previousPath + 1));
path.push(randomPath);
}
return path;
}
function generateNext(min, max) {
return Math.floor(Math.random() * (max - min + 1) + min);
}
function drawPath(xPos, prevRow, isLeft) {
if (prevRow >= 0) {
var svgTopOffSet = 12;
var svgHeight = 22;
var svgWidth = 22;
var $trail = $('.trail');
var $newTrail = $(document.createElementNS('http://www.w3.org/2000/svg', 'svg'));
$newTrail.attr({
x: xPos,
y: prevRow * svgHeight + svgTopOffSet
});
var $line = $(document.createElementNS('http://www.w3.org/2000/svg', 'line'));
$line.attr({
x1: svgWidth / 2,
y1: 0,
x2: isLeft ? 0 : svgWidth,
y2: svgWidth,
style: 'stroke:orange;stroke-width:3'
});
$newTrail.append($line);
$trail.append($newTrail);
}
}
body {
background: rgb(26, 30, 35);
}
.board {
width: 500px;
height: 300px;
margin: auto;
display: flex;
justify-content: center;
align-items: center;
}
.row {
display: flex;
justify-content: center;
}
.row .disc {
height: 6px;
width: 6px;
border-radius: 50%;
background: gray;
margin: 8px;
}
.wrapper .falling {
position: absolute;
height: 11px;
width: 11px;
border-radius: 50%;
background: orange;
transform: translate(50%, 50%);
z-index: 1;
}
.wrapper {
position: relative;
}
.trail {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
}
line { stroke-dasharray: 25; stroke-dashoffset: 25; animation: offset 0.5s linear forwards; }
#keyframes offset {
to {
stroke-dashoffset: 0;
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='board'>
<div class='wrapper'>
<svg class="trail">
</svg>
</div>
<button>
test game
</button>
</div>

How to make my random generated div appear inside container div?

HTML
<div id="container">
<div id="wrapper">
</div>
<span id = "waveNum">Current Wave: 0</span>
<input type = "button" value = "Start Game" onclick = "startGame()"></input>
</div>
<script src="https://code.jquery.com/jquery-2.1.3.js"></script>
<script src="main.js"></script>
</body>
Javascript
var keyArray = [];
var currentWave = 1;
var player;
var player2;
function initiate(){
player = new createPlayer(150,50,"player1","relative","blue");
player2 = new createPlayer(150,0,"player2","relative","green");
}
function startGame() {
point();
}
function createPlayer(l,t,id,pos,color){
this.speed = 3;
this.width = 25;
this.height = 25;
this.left = l;
this.top = t;
this.id = id;
this.model = $("<div id=" + id + "/>")
.css({"backgroundColor":color,"height":this.height,"width":this.width,
"left":this.left,"top":this.top,"position":pos})
$('#wrapper').append($(this.model));
}
function point(){
leftP = parseInt(Math.random()*970);
topP = parseInt(Math.random()*580);
$points = $("<div class=point/>")
.css({"backgroundColor":"yellow","height":"10px","width":"10px","left":0,
"top":0,"position":"relative"})
$('#wrapper').append($points)
}
function update(){
//left
if(keyArray[65]){
var newLeft = parseInt(player.left)-player.speed+"px"
player.left = newLeft;
document.getElementById(player.id).style.left = newLeft;
}
//right
if(keyArray[68]){
var newLeft = parseInt(player.left)+player.speed+"px"
player.left = newLeft;
document.getElementById(player.id).style.left = newLeft;
}
//up
if(keyArray[87]){
var newTop = parseInt(player.top)-player.speed+"px"
player.top = newTop;
document.getElementById(player.id).style.top = newTop;
}
//down
if(keyArray[83]){
var newTop = parseInt(player.top)+player.speed+"px"
player.top = newTop;
document.getElementById(player.id).style.top = newTop;
}
//player2
//left
if(keyArray[37]){
var newLeft = parseInt(player2.left)-player2.speed+"px"
player2.left = newLeft;
document.getElementById(player2.id).style.left = newLeft;
}
//right
if(keyArray[39]){
var newLeft = parseInt(player2.left)+player2.speed+"px"
player2.left = newLeft;
document.getElementById(player2.id).style.left = newLeft;
}
//up
if(keyArray[38]){
var newTop = parseInt(player2.top)-player2.speed+"px"
player2.top = newTop;
document.getElementById(player2.id).style.top = newTop;
}
//down
if(keyArray[40]){
var newTop = parseInt(player2.top)+player2.speed+"px"
player2.top = newTop;
document.getElementById(player2.id).style.top = newTop;
}
blockade();
requestAnimationFrame(update);
}
function blockade(){
var elemLeft = parseInt($('#wrapper').css('left'));
var elemWidth = parseInt($('#wrapper').css('width'));
var elemTop= parseInt($('#wrapper').css('height'));
//blocks players from moving outside of game
if(parseInt(player.left) + player.width >= elemLeft+elemWidth){
player.left = elemWidth - player.width - 2;
}
if(parseInt(player.top) + player.height >= elemTop){
player.top = elemTop - player.height - 2;
}
if(parseInt(player.top) < 3){
player.top = 3;
}
if(parseInt(player.left) < 3){
player.left = 3;
}
if(parseInt(player2.left) + player2.width >= elemLeft+elemWidth){
player2.left = elemWidth - player2.width - 2;
}
if(parseInt(player2.top) + player2.height >= elemTop){
player2.top = elemTop - player2.height - 2;
}
if(parseInt(player2.top) < 3){
player2.top = 3;
}
if(parseInt(player2.left) < 3){
player2.left = 3;
}
}
window.onkeydown = function(page){
keyArray[page.keyCode] = page.type === 'keydown';
}
window.onkeyup = function(page){
keyArray[page.keyCode] = page.type === 'keydown'
}
CSS
html, body {margin: 0; height: 100%; overflow: hidden}
#container{
width:80%;
height:60%;
display: block;
text-align:center;
margin: 0 auto;
}
#wrapper{
left:0px;
width:1000px; /* 100% */
height:600px;
border:1px solid lime;
margin:0 auto;
background-color:black;
}
#player1, .point {
float: left;
clear: both;
}
body{
background-color:black;
}
#waveNum{
color:white;
font-size:200%;
}
.point {
overflow: auto;
}
So currently I need my point() function to generate a random div within the <div id="wrapper"> which it is but after a few different spawns, does not stay within the wrapper div eventually. It seems like the container of the point() seems to be shifting down. The more that is generated the more often it appears to the bottom and outside of the container.
Eventually my idea is for all of them to have the same top and left original positions in that way I could use my player and player2 to touch them (match left and top positions) and make them disappear like they are being collected like points. I also cant get them to have the same origin point. I think these issues might be related
You can use to make appeared specific div
z-index: 0
Try adding absolute positioning to your wrapper div and relative positioning to the container div:
#container {
position: relative;
}
#wrapper {
position: absolute;
top: 0;
left: 0;
}
This takes the div out of normal flow from the rest of the document.
See here for more explanations on why this works.

Can't draw canvas

I have a few problem with html5. I created a new webpage and add canvas at the middle of that page.Then created new js file that have a script for canvas and import it to webpage but webpage's canvas still nothing happen.
This is my code. index.html in root folder, style.css in css/ , script.js in js/
function startnewgame(){
score =0;
player.hp =10;
timewhenlasthit = Date.now();
timewhengamestart = Date.now();
frameCount =0;
enemylist ={} ;
bulletlist ={};
upgradelist ={};
randomspwanenemy();
}
function update(){
ctx.clearRect(0,0,WIDTH,HEIGHT);
ctx.fillText("Score = "+score,200,30);
score ++;
frameCount++;
if(frameCount % 100 === 0)random
spwanenemy();
if(frameCount % 75 === 0)randomspwanupgrade();
player.attackcounter += player.atkspd;
updateplayerposition();
drawplayer(player);
for(var i in bulletlist){
updateplayer(bulletlist[i]);
bulletlist[i].timer++;
var toRemove = false ;
if (bulletlist[i].timer > 100) {
toRemove = true;
}
for (var j in enemylist) {
var cod = getdistant(bulletlist[i],enemylist[j]);
if(cod){
toRemove = true;
delete enemylist[j];
score+=1000;
break;
}
}
if(toRemove)delete bulletlist[i];
}
for(var i in upgradelist){
updateplayer(upgradelist[i]);
var temp = getdistant(player,upgradelist[i]);
if(temp){
if(upgradelist[i].type === 'score'){
score += 100;
}
if(upgradelist[i].type ==='atkspd'){
player.atkspd +=5;
}
delete upgradelist[i];
}
}
for(var i in enemylist){
updateplayer(enemylist[i]);
var temp = getdistant(player,enemylist[i]);
death(temp);
}
}
function drawplayer(x){
ctx.save();
ctx.fillStyle = x.color;
ctx.fillRect(x.x-x.width/2,x.y-x.height/2,x.width,x.height);
ctx.restore();
ctx.fillText("HP = "+player.hp,20,30);
ctx.fillText("bullet = "+player.attackcounter,20,80);
}
function drawenemy(x){
ctx.save();
ctx.fillStyle = x.color;
ctx.fillRect(x.x-x.width/2,x.y-x.height/2,x.width,x.height);
ctx.restore();
}
function updateplayer(x){
if(x.x+x.width/2>=WIDTH){
x.x=WIDTH-x.width/2;
x.spdX=-x.spdX;
}
if(x.x-x.width/2<=0){
x.x = x.width/2;
x.spdX=-x.spdX;
}
if(x.y+x.height/2>=HEIGHT){
x.y = HEIGHT-x.height/2;
x.spdY=-x.spdY;
}
if(x.y-x.height/2<=0){
x.y = x.height/2;
x.spdY=-x.spdY;
}
x.x+=x.spdX;
x.y+=x.spdY;
drawenemy(x);
}
function adde(id,x,y,spdX,spdY,width,height){
var earth ={
name:'A',
x : x,
spdX :spdX,
y : y,
spdY : spdY,
id : id,
width : width,
height : height,
color : 'red'
};
enemylist[id]= earth;
}
function addupgrade(id,x,y,spdX,spdY,width,height,color,type){
var earth ={
name:'A',
x : x,
spdX :spdX,
y : y,
spdY : spdY,
id : id,
width : width,
height : height,
color : color,
type : type
};
upgradelist[id]= earth;
}
function addbullet(id,x,y,spdX,spdY,width,height){
var earth ={
name:'A',
x : x,
spdX :spdX,
y : y,
spdY : spdY,
id : id,
width : width,
height : height,
color : 'black',
timer: 0
};
bulletlist[id]= earth;
}
function getdistant(earth1,earth2){
var rect1 ={
x:earth1.x-earth1.width/2,
y:earth1.y-earth1.height/2,
width:earth1.width,
height:earth1.height
};
var rect2 ={
x:earth2.x-earth2.width/2,
y:earth2.y-earth2.height/2,
width:earth2.width,
height:earth2.height
};
return testcol(rect1,rect2);
}
function death(x){
if(x){
player.hp -= 1;
if(player.hp == 0){
var ttime = Date.now() - timewhengamestart;
timewhengamestart = Date.now();
console.log("DEAD!! you score "+ score );
startnewgame();
}
}
}
function randomspwanenemy(){
var x = Math.random()*WIDTH;
var y = Math.random()*HEIGHT;
var height = 10 +Math.random()*30;
var width= 10 + Math.random()*30;
var spdY = Math.random()*5 +5;
var spdX = Math.random()*5 +5;
var id = Math.random();
//console.log(x,y,height,width,spdX,spdY);
adde(id,x,y,spdX,spdY,width,height);
}
function randomspwanupgrade(){
var x = Math.random()*WIDTH;
var y = Math.random()*HEIGHT;
var height = 10 ;
var width= 10 ;
var spdY = 0;
var spdX = 0;
var id = Math.random();
var sample = Math.random();
if(sample >0.5){
var type = 'score';
var color ='lightblue';
}
else {
var type = 'atkspd';
var color = 'purple';
}
addupgrade(id,x,y,spdX,spdY,width,height,color,type);
}
function randomspwanbullet(earth,overangle){
var x = player.x;
var y = player.y;
var height = 10 ;
var width= 10 ;
//var tid = pp(Math.random());
var angle = earth.aimAngle;
if (overangle !== undefined) {
angle = overangle;
}
var spdY = (Math.sin(angle)*10 );
var spdX = (Math.cos(angle)*10 );
var id = Math.random();
addbullet(id,x,y,spdX,spdY,width,height);
}
function testcol(earth1,earth2){
var lasthit = Date.now()-timewhenlasthit;
if( earth1.x <= earth2.x+earth2.width
&& earth2.x <= earth1.x+earth1.width
&& earth1.y <= earth2.y+earth2.height
&& earth2.y <= earth1.y+earth1.height
&& lasthit >= 1000)
{
timewhenlasthit=Date.now();
return 1;
}
}
function pp(x){
if(x>0.5)return 1;
else return -1;
}
var canvas = document.getElementById("ctx")
var ctx = canvas.getContext('2d');
var frameCount =0;
ctx.font = '30 px Arial';
var score =0
var HEIGHT = 500;
var WIDTH = 500;
var timewhengamestart = Date.now();
var timewhenlasthit = Date.now();
document.onmousemove = function(mouse){
var mouseX = mouse.clientX- document.getElementById('ctx').getBoundingClientRect().left;
var mouseY = mouse.clientY-document.getElementById('ctx').getBoundingClientRect().top;;
mouseX -= player.x;
mouseY -= player.y;
player.aimAngle = Math.atan2(mouseY,mouseX) ;
/* if(mouseX <player.width/2)mouseX=player.width/2;
if(mouseX>WIDTH-player.width/2)mouseX = WIDTH-player.width/2;
if(mouseY<player.height/2)mouseY=player.height/2;
if(mouseY>HEIGHT-player.height/2)mouseY = HEIGHT-player.height/2;
player.x = mouseX;
player.y = mouseY;*/
}
document.onclick = function(mouse){
if (player.attackcounter > 25) {
randomspwanbullet(player,player.aimAngle);
player.attackcounter = 0;
}
}
document.oncontextmenu = function(mouse){
if (player.attackcounter > 1000) {
for (var i = 1; i < 361; i++) {
randomspwanbullet(player,i);
}
player.attackcounter = 0;
}
mouse.preventDefault();
}
document.onkeydown = function(event){
if (event.keyCode===68) {
player.pressingRight = true;
}
else if (event.keyCode===83) {
player.pressingDown = true ;
}
else if (event.keyCode===65) {
player.pressingLeft = true ;
}
else if (event.keyCode===87) {
player.pressingUp = true ;
}
}
document.onkeyup = function(event){
if (event.keyCode===68) {
player.pressingRight = false;
}
else if (event.keyCode===83) {
player.pressingDown = false ;
}
else if (event.keyCode===65) {
player.pressingLeft = false ;
}
else if (event.keyCode===87) {
player.pressingUp = false ;
}
}
function updateplayerposition() {
if(player.pressingRight)player.x+=10
if(player.pressingLeft)player.x-=10
if(player.pressingUp)player.y-=10
if(player.pressingDown)player.y+=10
if(player.x <player.width/2)player.x=player.width/2;
if(player.x>WIDTH-player.width/2)player.x = WIDTH-player.width/2;
if(player.y<player.height/2)player.y=player.height/2;
if(player.y>HEIGHT-player.height/2)player.y = HEIGHT-player.height/2;
}
var player = {
name :'E' ,
x : 40 ,
spdX : 30 ,
y : 40 ,
spdY : 5 ,
hp : 10 ,
width : 20 ,
height : 20,
atkspd : 1,
color : 'green',
attackcounter : 0,
pressingDown : false,
pressingUp : false,
pressingLeft : false,
pressingRight : false,
aimAngle : 0
};
var enemylist ={};
var upgradelist = {};
var bulletlist = {};
function drawCanvas() {
startnewgame();
setInterval(update,40);
}
#header{
background: #202020 ;
font-size: 36px;
text-align: center;
padding:0;
margin: 0;
font-style: italic;
color: #FFFFFF;
}
#ctx{
border: 2px solid #000000;
margin-left: auto;
margin-right: auto;
left: 0;
right: 0;
margin-top: 20px;
position: absolute;
background: #ffffff;
}
#leftmenu{
margin-top: 20px;
margin-bottom: 65px;
padding-right: 10px;
float: left;
width: 300px;
height: 580px;
background: #C8C8C8;
border-radius: 10px;
border: 10px solid #002699;
}
nav#leftmenu h2{
text-align: center;
font-size: 30px;
}
nav#leftmenu ul{
list-style: none;
padding: 0;
}
nav#leftmenu li{
list-style: none;
font-size: 24px;
margin-top: 20px;
border-bottom: 2px dashed #000;
margin-left: 0px;
text-align: center;
}
nav#leftmenu a{
text-decoration: none;
font-weight: bold;
color: #1c478e;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>A Awesome Game</title>
<link href="css/style.css" rel="stylesheet">
<script src="js/script.js" type="text/javascript"></script>
</head>
<body onload="drawCanvas();" style="background: linear-gradient(to bottom left, #0000ff -10%, #33ccff 100%);">
<h1 id="header">Welcome to my GAME!!</h1>
<!--Canvas-->
<canvas id ="ctx" width ="800" height="600" style = "border:1px solid #000000;"></canvas>
<!--leftMenu-->
<section>
<nav id="leftmenu">
<h2>Menu</h2>
<ul>
<li>New Game</li>
<li>Pause Game</li>
<li>Option</li>
<li>End it now</li>
</ul>
</nav>
</section>
</body>
</html>
Ps. this ti my first post,Sorry if I did something wrong.
Edit: canvas id from canvas to ctx
Here's a snippet that's working and drawing correctly. It was just a little typo in the update function, writing it like:
if (frameCount % 100 === 0) random
spwanenemy();
instead of:
if (frameCount % 100 === 0) randomspwanenemy();
So, yea, just a little typo! Understanding errors from the developer console (F12) and spotting what's wrong is a vital skill. Keep practicing!
function startnewgame() {
score = 0;
player.hp = 10;
timewhenlasthit = Date.now();
timewhengamestart = Date.now();
frameCount = 0;
enemylist = {};
bulletlist = {};
upgradelist = {};
randomspwanenemy();
}
function update() {
ctx.clearRect(0, 0, WIDTH, HEIGHT);
ctx.fillText("Score = " + score, 200, 30);
score++;
frameCount++;
if (frameCount % 100 === 0) randomspwanenemy();
if (frameCount % 75 === 0) randomspwanupgrade();
player.attackcounter += player.atkspd;
updateplayerposition();
drawplayer(player);
for (var i in bulletlist) {
updateplayer(bulletlist[i]);
bulletlist[i].timer++;
var toRemove = false;
if (bulletlist[i].timer > 100) {
toRemove = true;
}
for (var j in enemylist) {
var cod = getdistant(bulletlist[i], enemylist[j]);
if (cod) {
toRemove = true;
delete enemylist[j];
score += 1000;
break;
}
}
if (toRemove) delete bulletlist[i];
}
for (var i in upgradelist) {
updateplayer(upgradelist[i]);
var temp = getdistant(player, upgradelist[i]);
if (temp) {
if (upgradelist[i].type === 'score') {
score += 100;
}
if (upgradelist[i].type === 'atkspd') {
player.atkspd += 5;
}
delete upgradelist[i];
}
}
for (var i in enemylist) {
updateplayer(enemylist[i]);
var temp = getdistant(player, enemylist[i]);
death(temp);
}
}
function drawplayer(x) {
ctx.save();
ctx.fillStyle = x.color;
ctx.fillRect(x.x - x.width / 2, x.y - x.height / 2, x.width, x.height);
ctx.restore();
ctx.fillText("HP = " + player.hp, 20, 30);
ctx.fillText("bullet = " + player.attackcounter, 20, 80);
}
function drawenemy(x) {
ctx.save();
ctx.fillStyle = x.color;
ctx.fillRect(x.x - x.width / 2, x.y - x.height / 2, x.width, x.height);
ctx.restore();
}
function updateplayer(x) {
if (x.x + x.width / 2 >= WIDTH) {
x.x = WIDTH - x.width / 2;
x.spdX = -x.spdX;
}
if (x.x - x.width / 2 <= 0) {
x.x = x.width / 2;
x.spdX = -x.spdX;
}
if (x.y + x.height / 2 >= HEIGHT) {
x.y = HEIGHT - x.height / 2;
x.spdY = -x.spdY;
}
if (x.y - x.height / 2 <= 0) {
x.y = x.height / 2;
x.spdY = -x.spdY;
}
x.x += x.spdX;
x.y += x.spdY;
drawenemy(x);
}
function adde(id, x, y, spdX, spdY, width, height) {
var earth = {
name: 'A',
x: x,
spdX: spdX,
y: y,
spdY: spdY,
id: id,
width: width,
height: height,
color: 'red'
};
enemylist[id] = earth;
}
function addupgrade(id, x, y, spdX, spdY, width, height, color, type) {
var earth = {
name: 'A',
x: x,
spdX: spdX,
y: y,
spdY: spdY,
id: id,
width: width,
height: height,
color: color,
type: type
};
upgradelist[id] = earth;
}
function addbullet(id, x, y, spdX, spdY, width, height) {
var earth = {
name: 'A',
x: x,
spdX: spdX,
y: y,
spdY: spdY,
id: id,
width: width,
height: height,
color: 'black',
timer: 0
};
bulletlist[id] = earth;
}
function getdistant(earth1, earth2) {
var rect1 = {
x: earth1.x - earth1.width / 2,
y: earth1.y - earth1.height / 2,
width: earth1.width,
height: earth1.height
};
var rect2 = {
x: earth2.x - earth2.width / 2,
y: earth2.y - earth2.height / 2,
width: earth2.width,
height: earth2.height
};
return testcol(rect1, rect2);
}
function death(x) {
if (x) {
player.hp -= 1;
if (player.hp == 0) {
var ttime = Date.now() - timewhengamestart;
timewhengamestart = Date.now();
console.log("DEAD!! you score " + score);
startnewgame();
}
}
}
function randomspwanenemy() {
var x = Math.random() * WIDTH;
var y = Math.random() * HEIGHT;
var height = 10 + Math.random() * 30;
var width = 10 + Math.random() * 30;
var spdY = Math.random() * 5 + 5;
var spdX = Math.random() * 5 + 5;
var id = Math.random();
//console.log(x,y,height,width,spdX,spdY);
adde(id, x, y, spdX, spdY, width, height);
}
function randomspwanupgrade() {
var x = Math.random() * WIDTH;
var y = Math.random() * HEIGHT;
var height = 10;
var width = 10;
var spdY = 0;
var spdX = 0;
var id = Math.random();
var sample = Math.random();
if (sample > 0.5) {
var type = 'score';
var color = 'lightblue';
} else {
var type = 'atkspd';
var color = 'purple';
}
addupgrade(id, x, y, spdX, spdY, width, height, color, type);
}
function randomspwanbullet(earth, overangle) {
var x = player.x;
var y = player.y;
var height = 10;
var width = 10;
//var tid = pp(Math.random());
var angle = earth.aimAngle;
if (overangle !== undefined) {
angle = overangle;
}
var spdY = (Math.sin(angle) * 10);
var spdX = (Math.cos(angle) * 10);
var id = Math.random();
addbullet(id, x, y, spdX, spdY, width, height);
}
function testcol(earth1, earth2) {
var lasthit = Date.now() - timewhenlasthit;
if (earth1.x <= earth2.x + earth2.width && earth2.x <= earth1.x + earth1.width && earth1.y <= earth2.y + earth2.height && earth2.y <= earth1.y + earth1.height && lasthit >= 1000) {
timewhenlasthit = Date.now();
return 1;
}
}
function pp(x) {
if (x > 0.5) return 1;
else return -1;
}
var canvas = document.getElementById("ctx")
var ctx = canvas.getContext('2d');
var frameCount = 0;
ctx.font = '30 px Arial';
var score = 0
var HEIGHT = 500;
var WIDTH = 500;
var timewhengamestart = Date.now();
var timewhenlasthit = Date.now();
document.onmousemove = function(mouse) {
var mouseX = mouse.clientX - document.getElementById('ctx').getBoundingClientRect().left;
var mouseY = mouse.clientY - document.getElementById('ctx').getBoundingClientRect().top;;
mouseX -= player.x;
mouseY -= player.y;
player.aimAngle = Math.atan2(mouseY, mouseX);
/* if(mouseX <player.width/2)mouseX=player.width/2;
if(mouseX>WIDTH-player.width/2)mouseX = WIDTH-player.width/2;
if(mouseY<player.height/2)mouseY=player.height/2;
if(mouseY>HEIGHT-player.height/2)mouseY = HEIGHT-player.height/2;
player.x = mouseX;
player.y = mouseY;*/
}
document.onclick = function(mouse) {
if (player.attackcounter > 25) {
randomspwanbullet(player, player.aimAngle);
player.attackcounter = 0;
}
}
document.oncontextmenu = function(mouse) {
if (player.attackcounter > 1000) {
for (var i = 1; i < 361; i++) {
randomspwanbullet(player, i);
}
player.attackcounter = 0;
}
mouse.preventDefault();
}
document.onkeydown = function(event) {
if (event.keyCode === 68) {
player.pressingRight = true;
} else if (event.keyCode === 83) {
player.pressingDown = true;
} else if (event.keyCode === 65) {
player.pressingLeft = true;
} else if (event.keyCode === 87) {
player.pressingUp = true;
}
}
document.onkeyup = function(event) {
if (event.keyCode === 68) {
player.pressingRight = false;
} else if (event.keyCode === 83) {
player.pressingDown = false;
} else if (event.keyCode === 65) {
player.pressingLeft = false;
} else if (event.keyCode === 87) {
player.pressingUp = false;
}
}
function updateplayerposition() {
if (player.pressingRight) player.x += 10
if (player.pressingLeft) player.x -= 10
if (player.pressingUp) player.y -= 10
if (player.pressingDown) player.y += 10
if (player.x < player.width / 2) player.x = player.width / 2;
if (player.x > WIDTH - player.width / 2) player.x = WIDTH - player.width / 2;
if (player.y < player.height / 2) player.y = player.height / 2;
if (player.y > HEIGHT - player.height / 2) player.y = HEIGHT - player.height / 2;
}
var player = {
name: 'E',
x: 40,
spdX: 30,
y: 40,
spdY: 5,
hp: 10,
width: 20,
height: 20,
atkspd: 1,
color: 'green',
attackcounter: 0,
pressingDown: false,
pressingUp: false,
pressingLeft: false,
pressingRight: false,
aimAngle: 0
};
var enemylist = {};
var upgradelist = {};
var bulletlist = {};
function drawCanvas() {
startnewgame();
setInterval(update, 40);
}
#header {
background: #202020;
font-size: 36px;
text-align: center;
padding: 0;
margin: 0;
font-style: italic;
color: #FFFFFF;
}
#ctx {
border: 2px solid #000000;
margin-left: auto;
margin-right: auto;
left: 0;
right: 0;
margin-top: 20px;
position: absolute;
background: #ffffff;
}
#leftmenu {
margin-top: 20px;
margin-bottom: 65px;
padding-right: 10px;
float: left;
width: 300px;
height: 580px;
background: #C8C8C8;
border-radius: 10px;
border: 10px solid #002699;
}
nav#leftmenu h2 {
text-align: center;
font-size: 30px;
}
nav#leftmenu ul {
list-style: none;
padding: 0;
}
nav#leftmenu li {
list-style: none;
font-size: 24px;
margin-top: 20px;
border-bottom: 2px dashed #000;
margin-left: 0px;
text-align: center;
}
nav#leftmenu a {
text-decoration: none;
font-weight: bold;
color: #1c478e;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>A Awesome Game</title>
<link href="css/style.css" rel="stylesheet">
<script src="js/script.js" type="text/javascript"></script>
</head>
<body onload="drawCanvas();" style="background: linear-gradient(to bottom left, #0000ff -10%, #33ccff 100%);">
<h1 id="header">Welcome to my GAME!!</h1>
<!--Canvas-->
<canvas id="ctx" width="800" height="600" style="border:1px solid #000000;"></canvas>
<!--leftMenu-->
<section>
<nav id="leftmenu">
<h2>Menu</h2>
<ul>
<li>New Game
</li>
<li>Pause Game
</li>
<li>Option
</li>
<li>End it now
</li>
</ul>
</nav>
</section>
</body>
</html>

After rotate image how to find correct position to crop in specific area

I want to crop image in specific area, I made below example
it is work when the inner not been rotate
my problem is after rotate the inner, I don't get how to find correct sx,sy,sw,sh to crop
UPDATE
base on this answer fix the draw rotate image part, I update in fiddle.
but I still don't get how to find correct position to crop rotated image ...
https://jsfiddle.net/ve219z34/3/
var crop = function() {
var transformMediaBlock = $('.mediaBlock');
var transformCropInner = $('.transformCropInner');
var transformCropLimit = $('.transformCropLimit');
var canvasContainer = $('.canvasContainer')
var limitLeft = transformCropLimit.offset().left;
var limitTop = transformCropLimit.offset().top;
var limitRight = limitLeft + transformCropLimit.width();
var limitBottom = limitTop + transformCropLimit.height();
var imageRatio = transformMediaBlock.find('img')[0].naturalWidth/transformMediaBlock.find('img').width();
// draw rotate image
var deg2Rad = Math.PI/180;
var rotateDegree = -20;
$('<canvas/>',{'class':'rotate'}).appendTo($(canvasContainer));
var canvas = $('.canvasContainer canvas')[0];
var ctx = canvas.getContext("2d");
var width = 0;
var height = 0;
var diagonal = 0;
var angleInDegrees = 0;
width = transformMediaBlock.find('img')[0].naturalWidth;
height = transformMediaBlock.find('img')[0].naturalHeight;
diagonal = Math.sqrt(Math.pow(width,2)+Math.pow(height,2));
ctx.canvas.width = diagonal;
ctx.canvas.height = diagonal;
ctx.clearRect(0,0,canvas.width,canvas.height);
ctx.save();
ctx.translate(diagonal/2,diagonal/2);
ctx.rotate(0*Math.PI/180);
ctx.drawImage(transformMediaBlock.find('img')[0],-width/2,-height/2);
ctx.restore();
var drawRotated = function(degrees){
ctx.clearRect(0,0,canvas.width,canvas.height);
ctx.save();
ctx.translate(diagonal/2,diagonal/2);
ctx.rotate(degrees*Math.PI/180);
ctx.drawImage(transformMediaBlock.find('img')[0],-width/2,-height/2);
ctx.restore();
};
drawRotated(rotateDegree);
// problem is here don't know how to get correct sx sy sw sh with image been rotate
// draw crop rotate image
var imageLeft = transformMediaBlock.find('img').offset().left;
var imageTop = transformMediaBlock.find('img').offset().top;
var imageRight = imageLeft + transformMediaBlock.find('img').width();
var imageBottom = imageTop + transformMediaBlock.find('img').height();
if (limitLeft <= imageLeft) {
var sx = 0;
} else {
var sx = limitLeft - imageLeft;
}
if (limitTop <= imageTop) {
var sy = 0;
} else {
var sy = limitTop - imageTop;
}
if (limitLeft <= imageLeft) {
var l = imageLeft;
} else {
var l = limitLeft;
}
if (limitRight <= imageRight) {
var r = limitRight;
} else {
var r = imageRight;
}
var sw = r - l;
if (limitTop <= imageTop) {
var t = imageTop;
} else {
var t = limitTop;
}
if (limitBottom <= imageBottom) {
var b = limitBottom;
} else {
var b = imageBottom;
}
var sh = b - t;
sx = sx*imageRatio;
sy = sy*imageRatio;
sw = sw*imageRatio;
sh = sh*imageRatio;
var dx = 0;
var dy = 0;
var dw = sw;
var dh = sh;
};
$('#container').on('click', '.action.crop', function (e) {
var transformMediaBlock = $('.mediaBlock');
transformMediaBlock.find('img').on('load', function() {
$('.transformCropInner').addClass('rotate');
crop();
}).each(function() {
if(this.complete) $(this).load();
});
});
.mediaBlock {
position: relative;
display: block;
overflow: hidden;
}
.mediaBlock img {
max-width: 100%;
}
.transformCropLimit {
position: relative;
top: 20px;
left: 20px;
width: 200px;
height: 200px;
border: 1px solid blue;
}
.transformCropInner {
width: 100px;
cursor: pointer;
position: relative;
top: 10px;
left: 100px;
}
.transformCropInner.rotate {
transform: rotate(9-2deg);
-ms-transform: rotate(-20deg); /* IE 9 */
-moz-transform: rotate(-20deg); /* Firefox */
-webkit-transform: rotate(-20deg); /* Safari and Chrome */
-o-transform: rotate(-20deg); /* Opera */
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="container">
<div class="canvasContainer"></div>
<div class="content main">
<div class="action crop">Crop</div>
<div class="transformCropLimit">
<div class="transformCropInner">
<div class="mediaBlock">
<img src="http://image.vsco.co/1/55210eb4aceed3144059/57f2471df662677e548b4568/300x400/25e7b55c-6ed9-490c-95c2-6d69520eb7bd1835072132.jpg">
</div>
</div>
</div>
</div>
</div>
Please don't provide plugin as an answer, and css crop is not what I'm looking for.

Drag an HTML box and make another box follow it with JavaScript

I am trying to create something like drag a box (Hello World) to any location, and the second box (Follow World) will follow slowly.
In the code below, the drag box is fine, but the follow box will not follow properly. Also, the drag box cannot drop.
function startDrag(e) {
// determine event object
if (!e) {
var e = window.event;
}
// IE uses srcElement, others use target
var targ = e.target ? e.target : e.srcElement;
if (targ.className != 'dragme') {
return
};
// calculate event X, Y coordinates
offsetX = e.clientX;
offsetY = e.clientY;
// assign default values for top and left properties
if (!targ.style.left) {
targ.style.left = '0px'
};
if (!targ.style.top) {
targ.style.top = '0px'
};
// calculate integer values for top and left
// properties
coordX = parseInt(targ.style.left);
coordY = parseInt(targ.style.top);
drag = true;
// move div element
document.onmousemove = dragDiv;
return false;
}
function dragDiv(e) {
if (!drag) {
return
};
if (!e) {
var e = window.event
};
var targ = e.target ? e.target : e.srcElement;
// move div element
targ.style.left = coordX + e.clientX - offsetX + 'px';
targ.style.top = coordY + e.clientY - offsetY + 'px';
return false;
}
function stopDrag() {
timer();
drag = false;
}
window.onload = function() {
document.onmousedown = startDrag;
document.onmouseup = stopDrag;
}
function disp() {
var step = 1;
var y = document.getElementById('followme').offsetTop;
var x = document.getElementById('followme').offsetLeft;
var ty = document.getElementById('draggable').offsetTop;
var ty = document.getElementById('draggable').offsetLeft;
if (y < ty) {
y = y + step;
document.getElementById('followme').style.top = y + "px"; // vertical movment
} else {
if (x < tx) {
x = x + step;
document.getElementById('followme').style.left = x + "px"; // horizontal movment
}
}
}
function timer() {
disp();
var y = document.getElementById('followme').offsetTop;
var x = document.getElementById('followme').offsetLeft;
document.getElementById("msg").innerHTML = "X: " + tx + " Y : " + ty
my_time = setTimeout('timer()', 10);
}
.dragme {
position: relative;
width: 60px;
height: 80px;
cursor: move;
}
.followme {
position: relative;
width: 60px;
height: 80px;
}
#draggable {
background-color: #ccc;
border: 1px solid #000;
}
#followme {
background-color: #ccc;
border: 1px solid #000;
}
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Drag and drop</title>
</head>
<body>
<div id='msg'></div>
<div id="draggable" class="dragme">"Hello World!"</div>
<div id="followme" class="followme">"Follow World!"</div>
Fix yours disp and timer functions to this:
function disp()
{
var step = 1;
// in dragDiv() you modifying style.left/style.top properties, not offsetTop/offsetLeft
var x = parseInt(document.getElementById('followme').style.left) || 0;
var y = parseInt(document.getElementById('followme').style.top) || 0;
var tx = parseInt(document.getElementById('draggable').style.left) || 0;
var ty = parseInt(document.getElementById('draggable').style.top) || 0;
// properly calculate offset
var dx = ((dx = tx - x) == 0) ? 0 : Math.abs(dx) / dx;
var dy = ((dy = ty - y) == 0) ? 0 : Math.abs(dy) / dy;
document.getElementById('followme').style.left = (x + dx * step) + "px"; // horisontal movment
document.getElementById('followme').style.top = (y + dy * step) + "px"; // vertical movment
}
function timer()
{
disp();
var y=document.getElementById('followme').offsetTop;
var x=document.getElementById('followme').offsetLeft;
document.getElementById("msg").innerHTML="X: " + x + " Y : " + y; // typo was here
my_time = setTimeout(function () {
clearTimeout(my_time); // need to clear timeout or it'll be adding each time 'Hello world' clicked
timer();
},10);
}
In the following snippet, the pink box is draggable and the blue box follows it around. You can change pixelsPerSecond to adjust the speed of movement.
function message(s) {
document.getElementById('messageContainer').innerHTML = s;
}
window.onload = function () {
var pixelsPerSecond = 80,
drag = document.getElementById('drag'),
follow = document.getElementById('follow'),
wrapper = document.getElementById('wrapper'),
messageContainer = document.getElementById('messageContainer'),
leftMax,
topMax;
function setBoundaries() {
leftMax = wrapper.offsetWidth - drag.offsetWidth;
topMax = wrapper.offsetHeight - drag.offsetHeight;
drag.style.left = Math.min(drag.offsetLeft, leftMax) + 'px';
drag.style.top = Math.min(drag.offsetTop, topMax) + 'px';
}
setBoundaries();
window.onresize = setBoundaries;
[drag, follow, messageContainer].forEach(function (element) {
element.className += ' unselectable';
element.ondragstart = element.onselectstart = function (event) {
event.preventDefault();
};
});
var start = Date.now();
drag.onmousedown = function (event) {
event = event || window.event;
var x0 = event.pageX || event.clientX,
y0 = event.pageY || event.clientY,
left0 = drag.offsetLeft,
top0 = drag.offsetTop;
window.onmousemove = function (event) {
var x = event.pageX || event.clientX,
y = event.pageY || event.clientY;
drag.style.left = Math.max(0, Math.min(left0 + x - x0, leftMax)) + 'px';
drag.style.top = Math.max(0, Math.min(top0 + y - y0, topMax)) + 'px';
};
window.onmouseup = function () {
window.onmousemove = window.onmouseup = undefined;
};
};
follow.x = follow.offsetLeft;
follow.y = follow.offsetTop;
function update() {
var elapsed = Date.now() - start;
if (elapsed === 0) {
window.requestAnimationFrame(update);
return;
}
var x1 = drag.offsetLeft,
y1 = drag.offsetTop + (drag.offsetTop + drag.offsetHeight <= topMax ?
drag.offsetHeight : -drag.offsetHeight),
x0 = follow.x,
y0 = follow.y,
dx = x1 - x0,
dy = y1 - y0,
distance = Math.sqrt(dx*dx + dy*dy),
angle = Math.atan2(dy, dx),
dd = Math.min(distance, pixelsPerSecond * elapsed / 1000);
message('x: ' + x1 + ', y: ' + y1);
follow.x += Math.cos(angle) * dd;
follow.style.left = follow.x + 'px';
follow.y += Math.sin(angle) * dd;
follow.style.top = follow.y + 'px';
start = Date.now();
window.requestAnimationFrame(update);
}
window.requestAnimationFrame(update);
};
#wrapper {
position: absolute;
left: 0;
top: 0;
width: 100%;
height: 100%;
background: #eee;
font-family: sans-serif;
text-align: center;
}
.unselectable {
-webkit-user-select: none;
-khtml-user-drag: none;
-khtml-user-select: none;
-moz-user-select: none;
-moz-user-select: -moz-none;
-ms-user-select: none;
user-select: none;
}
#messageContainer {
position: absolute;
left: 80px;
top: 50px;
font-size: 36px;
color: #aaa;
cursor: default;
}
.box {
position: absolute;
width: 60px;
height: 80px;
}
.label {
margin: 30px auto;
font-size: 14px;
}
#drag {
left: 100px;
top: 120px;
background: #f0dddb;
border: 2px solid #deb7bb;
cursor: move;
}
#follow {
left: 0;
top: 0;
background-color: #ddebf3;
border: 2px solid #bfd5e1;
cursor: default;
}
<div id="wrapper">
<div id="messageContainer"></div>
<div class="box" id="follow"> <div class="label">it follows</div> </div>
<div class="box" id="drag"> <div class="label">drag me</div> </div>

Categories

Resources