JS music visulalizer - javascript

I am trying to make a music visualizer in Javascript in the shape of circle, my problem is that even though I call clearRect, the canvas isnt clearing after a completion of a cycle.
$(document).ready(function() {
var canvas = document.getElementsByTagName("canvas")[0];
var context = canvas.getContext("2d");
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
context.translate(window.innerWidth / 2, window.innerHeight / 2);
var audioContext = new AudioContext();
var audio = document.getElementsByTagName('audio')[0];
var source = audioContext.createMediaElementSource(audio);
var analyser = audioContext.createAnalyser();
source.connect(analyser);
analyser.connect(audioContext.destination);
var BLenght = analyser.frequencyBinCount;
var data = new Uint8Array(BLenght);
function Visualizer() {
context.clearRect(0, 0, canvas.width, canvas.height);
analyser.getByteFrequencyData(data);
var fwidth = (canvas.width / BLenght);
var fheight = 0;
var maxCircle = 80;
var radius = 200;
for (var i = 0; i <= maxCircle; i++) {
fheight = (data[i] * (canvas.height * 0.003)) / 2;
context.fillStyle = "#000000";
context.rect(0, radius, fwidth, fheight);
context.rotate(2 * Math.PI / maxCircle);
context.fill();
}
call = requestAnimationFrame(Visualizer);
}
var button = document.getElementById("button");
var isPlaying = false;
button.addEventListener('click', function() {
if (isPlaying == false) {
audio.play();
Visualizer();
isPlaying = true;
button.style.boxShadow = "0px 0px 0px 0px #065e41";
var delay = 400;
setTimeout(function() {
button.style.boxShadow = "0px 5px 0px 0px #065e41";
}, delay);
} else {
audio.pause();
isPlaying = false;
cancelAnimationFrame(call);
button.style.boxShadow = "0px 0px 0px 0px #065e41";
var delay = 400;
setTimeout(function() {
button.style.boxShadow = "0px 5px 0px 0px #065e41";
}, delay);
}
});
});
* {
box-sizing: border-box;
}
canvas {
position: absolute;
top: 10%;
}
#button {
width: 150px;
height: 50px;
background: #0deaa1;
text-align: center;
border-radius: 5px;
box-shadow: 0px 5px 0px 0px #065e41;
cursor: pointer;
user-select: none;
transition: .5s;
}
#button h1 {
padding-top: 7px;
color: white;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<audio src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/1715/the_xx_-_intro.mp3" preload="auto"></audio>
<canvas></canvas>
<div id="button">
<h1>PLAY</h1>
</div>
<p id="width">width</p>
<p id="buffer">buffer</p>
<p id="data">data</p>

It can be fixed by using fillRect, or by using context.beginPath. (currently you are adding every rect to the same path)
context.fillStyle = "#000000";
context.fillRect(0,radius,fwidth,fheight); // rect changed to fillrect
context.rotate(2*Math.PI/maxCircle);
To prevent the lines from spinning: reset the context transformation matrix:
context.setTransform(1, 0, 0, 1, 0, 0);
context.translate(window.innerWidth/2,window.innerHeight/2);
context.clearRect(-canvas.width/2,-canvas.height/2,canvas.width,canvas.height);
The Codepen example you provided was also updated: http://codepen.io/anon/pen/xbMxzY

Related

I cant put canvas into divs without changing the orientation

The problem is that i want the arrows go row and column but only its only on column
html
<div class="grafica" id="grafica">
<div id="x"></div>
<div id="y"></div>
</div>
css
.grafica{
width: 90%;
height: 95vh;
box-shadow: 7px 10px 30px -1px black;
}
Each arrow its inside of a div, if i dont put the arrows inside the div it work well but i need to do it
javascript
function createArrow(){
const div = document.createElement('div');
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
canvas.width = 100;
canvas.height = 100;
canvas.className = 'arrow';
ctx.beginPath();
ctx.strokeStyle = 'black';
ctx.lineWidth = 3;
ctx.moveTo(50, 50);
ctx.lineTo(0, 0);
ctx.moveTo(20, 10);
ctx.lineTo(0, 0);
ctx.lineTo(10, 20);
ctx.stroke();
document.addEventListener('mousemove', ()=> {
let distanceX = getDistanceBetweenElements(canvas, x);
let distanceY = getDistanceBetweenElements(canvas, y);
let f1 = (k*q1*q2)/distanceX;
let f2 = (k*q1*q2)/distanceY;
console.log(f1, f2);
//canvas.style.transform = `rotate(${a}deg)`;
});
grafica.append(div);
div.append(canvas);
}
Please add the following code to your css:
.grafica > div {
float: left;
}

Change canvas background color to transparent

I have a text under canvas, i want to show it when i am erasing background color of canvas. Now it is red, when i wrote transparent it does not work. I need to show that text when i draw with the mouse. I tried with rgba too, but is was not working.
please help me if you can
enter code here
var cont = document.getElementById("spots"), // UI elements
canvas = document.getElementById("canvas"),
alpha = document.getElementById("alpha"),
modes = document.getElementById("modes"),
ctx = canvas.getContext("2d"),
isDown = false, // defaults
color = "red";
// set up color palette using a custom "Spot" object
// This will use a callback function when it is clicked, to
// change current color
function Spot(color, cont, callback) {
var div = document.createElement("div");
div.style.cssText = "width:50px;height:50px;border:1px solid #000;margin:0 1px 1px 0;background:" + color;
div.onclick = function() {callback(color)};
cont.appendChild(div);
}
// add some spot colors to our palette container
new Spot(color, cont, setColor);
// this will set current fill style based on spot clicked
function setColor(c) {ctx.fillStyle = c}
// setup defaults
ctx.fillStyle = color;
ctx.globalAlpha = 1;
// events
canvas.onmousedown = function() {isDown = true};
window.onmouseup = function() {isDown = false};
window.onmousemove = function(e) {
if (!isDown) return;
var r = canvas.getBoundingClientRect(),
x = e.clientX - r.left,
y = e.clientY - r.top;
ctx.beginPath();
ctx.arc(x, y, 25, 0, 2*Math.PI);
ctx.fill();
};
.main-content{
position: relative;
width: 300px;
height: 300px;
}
.main-text{
position: absolute;
right: 0;
left: 0;
text-align: center;
z-index: 8;
font-size: 35px;
}
#canvas{
background-color: green;
position: absolute;
z-index: 9;
}
<div class="main-content">
<p class="main-text">You Won!!!</p>
<canvas id="canvas" width=300 height=300 style="border: 1px solid green;"></canvas>
<div id="spots"></div>
</div>
I think you would like to get something like the solution in the snippet below.
var cont = document.getElementById("spots"), // UI elements
canvas = document.getElementById("canvas"),
alpha = document.getElementById("alpha"),
modes = document.getElementById("modes"),
ctx = canvas.getContext("2d"),
isDown = false, // defaults
color = "green";
// set up color palette using a custom "Spot" object
// This will use a callback function when it is clicked, to
// change current color
function Spot(color, cont, callback) {
var div = document.createElement("div");
div.style.cssText = "width:50px;height:50px;border:1px solid #000;margin:0 1px 1px 0;background:" + color;
div.onclick = function() {
callback(color)
};
cont.appendChild(div);
}
// add some spot colors to our palette container
new Spot(color, cont, setColor);
// this will set current fill style based on spot clicked
function setColor(c) {
ctx.fillStyle = c
}
// setup defaults
ctx.fillStyle = color;
ctx.globalAlpha = 1;
// create a rectangle using canvas functions, not CSS
// background color.
const createRect = (ctx, width, height) => {
ctx.fillRect(0, 0, width, height)
}
createRect(ctx, 300, 300)
// events
canvas.onmousedown = function() {
isDown = true
};
window.onmouseup = function() {
isDown = false
};
window.onmousemove = function(e) {
if (!isDown) return;
var r = canvas.getBoundingClientRect(),
x = e.clientX - r.left,
y = e.clientY - r.top;
// you needed a bit more code here:
ctx.fillStyle = "rgba(255, 255, 255, 0.5)"
ctx.save();
ctx.globalCompositeOperation = 'destination-out';
ctx.beginPath();
ctx.arc(x, y, 25, 0, 2 * Math.PI, false);
ctx.fill();
ctx.restore();
};
.main-content {
position: relative;
width: 300px;
height: 300px;
}
.main-text {
position: absolute;
right: 0;
left: 0;
text-align: center;
z-index: 8;
font-size: 35px;
}
#canvas {
/*background-color: green;*/
position: absolute;
z-index: 9;
}
<div class="main-content">
<p class="main-text">You Won!!!</p>
<canvas id="canvas" width=300 height=300 style="border: 1px solid green;"></canvas>
<div id="spots"></div>
</div>
About canvas global compositions: https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/globalCompositeOperation
You are halfway there, but there are a couple of things to change.
What you're trying to do is to change the appearance of a css property through the canvas, which does not work like that. You also can not alter the transparency of the canvas, however there are solutions to your case, and it is very simple.
You need to apply a background color to your canvas, then remove the pixels by using the exact same drawing function you have, then you set an extra property called globalCompositeOperation, which is basically the "BlendMode" of photoshop.
So here's your updated code:
var cont = document.getElementById("spots"), // UI elements
canvas = document.getElementById("canvas"),
alpha = document.getElementById("alpha"),
modes = document.getElementById("modes"),
ctx = canvas.getContext("2d"),
isDown = false, // defaults
color = "red";
// set up color palette using a custom "Spot" object
// This will use a callback function when it is clicked, to
// change current color
function Spot(color, cont, callback) {
var div = document.createElement("div");
div.style.cssText = "width:50px;height:50px;border:1px solid #000;margin:0 1px 1px 0;background:" + color;
div.onclick = function() {callback(color)};
cont.appendChild(div);
}
// add some spot colors to our palette container
//new Spot(color, cont, setColor);
// this will set current fill style based on spot clicked
function setColor(c) {ctx.fillStyle = c}
// setup defaults
ctx.fillStyle = color;
ctx.globalAlpha = 1;
// draw the background
ctx.fillRect(0, 0, 300, 300);
// add the 'blend mode effect'
ctx.globalCompositeOperation = 'destination-out';
// events
canvas.onmousedown = function() {isDown = true};
window.onmouseup = function() {isDown = false};
window.onmousemove = function(e) {
if (!isDown) return;
var r = canvas.getBoundingClientRect(),
x = e.clientX - r.left,
y = e.clientY - r.top;
ctx.beginPath();
ctx.arc(x, y, 25, 0, 2*Math.PI);
ctx.fill();
};
.main-content{
position: relative;
width: 300px;
height: 300px;
background: blue;
}
.main-text{
position: absolute;
right: 0;
left: 0;
text-align: center;
z-index: 8;
font-size: 35px
}
#canvas{
position: absolute;
z-index: 9;
}
<div class="main-content">
<p class="main-text">You Won!!!</p>
<canvas id="canvas" width=300 height=300 style="border: 1px solid green;"></canvas>
<div id="spots"></div>
</div>
Apart from that tiny change on the JS, I also changed the order of z-index on the CSS. Good luck

Javascript Audio API Visualizer not showing in canvas

So i followed this tutorial: https://youtu.be/IBHpSkGZtNM
And a while back (about a year ago or so) it worked. Now however it doesn't visualize anything. The sound plays but thats it.
I changed the old webkit functions to the new ones as i was getting errors. However now i don't have any errors and still nothing shows up.
Here is my code:
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
div#mp3_player{ width: 500px; height: 60px; background: #000000; padding: 5px; margin: 50px auto;}
div#mp3_player > div > audio{ width: 500px; background: #000000; float: left;}
div#mp3_player > canvas{width: 500px; height: 30px; background: #002D3C; float: left;}
</style>
<script>
var audio = new Audio();
audio.src = "audio/DieForYou-Starset.mp3";
audio.controls = true;
audio.loop = true;
audio.autoplay = false;
var canvas, ctx, source, context, analyser, fbc_array, bars, bar_x, bar_width, bar_height;
window.addEventListener("load", initMp3Player, false);
function initMp3Player(){
document.getElementById("audio_box").appendChild(audio);
context = new AudioContext();
analyser = context.createAnalyser();
canvas = document.getElementById("analyser_renderer");
ctx = canvas.getContext("2d");
source = context.createMediaElementSource(audio);
source.connect(analyser);
analyser.connect(context.destination);
frameLooper()
}
function frameLooper(){
window.requestAnimationFrame(frameLooper);
fbc_array = new Uint8Array(analyser.frequencyBinCount);
ctx.clearRect(0,0 ,canvas.width, canvas.height)
ctx.fillStyle= "#2DCC70";
bars = 100;
for(var i = 0; i < bars; i++){
bar_x = i * 3;
bar_width = 2;
bar_height = -(fbc_array[1] / 2);
ctx.fillRect(bar_x, canvas.height, bar_width, bar_height);
}
}
</script>
</head>
<body>
<div id="mp3_player">
<div id="audio_box"></div>
<canvas id="analyser_renderer"></canvas>
</div>
</body>
</html>
I put everything in the html file because it was easier to post like that. I know it's bad practise.
Note: the sound wont play in the snippet because the audio file is stored locally.
I am also running this trough a local server as just opening the html file would result in MediaElementAudioSource outputs zeroes due to CORS access restrictions for file:///C:/xampp/htdocs/audio/DieForYou-Starset.mp3
You need to populate your array with one of the AnalyserNode methods, here you are only creating an empty one.
For example, you can call analyser.getByteFrequencyData(fbc_array); to get the current frequency data.
var audio = new Audio();
audio.crossOrigin = 'anonymous';
audio.src = "https://dl.dropboxusercontent.com/s/8c9m92u1euqnkaz/GershwinWhiteman-RhapsodyInBluePart1.mp3";
audio.controls = true;
audio.loop = true;
audio.autoplay = false;
window.onload = initMp3Player;
var canvas, ctx, source, context, analyser, fbc_array, bars, bar_x, bar_width, bar_height;
function initMp3Player() {
document.getElementById("audio_box").appendChild(audio);
context = new AudioContext();
analyser = context.createAnalyser();
canvas = document.getElementById("analyser_renderer");
ctx = canvas.getContext("2d");
source = context.createMediaElementSource(audio);
source.connect(analyser);
analyser.connect(context.destination);
// initialise the Uint8Array only once
fbc_array = new Uint8Array(analyser.frequencyBinCount);
frameLooper()
}
function frameLooper() {
window.requestAnimationFrame(frameLooper);
ctx.clearRect(0, 0, canvas.width, canvas.height)
ctx.fillStyle = "#2DCC70";
bars = 100;
// here fill the Uint8Array with audio data
analyser.getByteFrequencyData(fbc_array);
for (var i = 0; i < bars; i++) {
bar_x = i * 3;
bar_width = 2;
bar_height = -(fbc_array[i] / 2); // there was a typo
ctx.fillRect(bar_x, canvas.height, bar_width, bar_height);
}
}
div#mp3_player {
width: 500px;
height: 60px;
background: #000000;
padding: 5px;
margin: 50px auto;
}
div#mp3_player>div>audio {
width: 500px;
background: #000000;
float: left;
}
div#mp3_player>canvas {
width: 500px;
height: 30px;
background: #002D3C;
float: left;
}
<div id="mp3_player">
<div id="audio_box"></div>
<canvas id="analyser_renderer"></canvas>
</div>

Creating an audio visualizer using HTML5

I am trying to use an audio visualisation for the stream of my online radio using the example that I found on this page.
However, similar to the problem found in this post , my audio file (even when testing with a local file) just does not sound and of course the visualisation does nothing as well.
My HTML is the following:
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<audio src="http://50.22.218.101:38838/;steam.mp3" id="audio"
controls>HTML5 Audio element not supported</audio>
<canvas id="canvas" width="800" height="350"></canvas>
<script src="main.js"></script>
</body>
</html>
This is "main.js":
window.AudioContext = window.AudioContext || window.webkitAudioContext || window.mozAudioContext;
window.onload = function() {
var audio = document.getElementById('audio');
var ctx = new AudioContext();
var analyser = ctx.createAnalyser();
var audioSrc = ctx.createMediaElementSource(audio);
// we have to connect the MediaElementSource with the analyser
audioSrc.connect(analyser);
analyser.connect(ctx.destination);
// we could configure the analyser: e.g. analyser.fftSize (for further infos read the spec)
// analyser.fftSize = 64;
// frequencyBinCount tells you how many values you'll receive from the analyser
var frequencyData = new Uint8Array(analyser.frequencyBinCount);
// we're ready to receive some data!
var canvas = document.getElementById('canvas'),
cwidth = canvas.width,
cheight = canvas.height - 2,
meterWidth = 10, //width of the meters in the spectrum
gap = 2, //gap between meters
capHeight = 2,
capStyle = '#fff',
meterNum = 800 / (10 + 2), //count of the meters
capYPositionArray = []; ////store the vertical position of hte caps for the preivous frame
ctx = canvas.getContext('2d'),
gradient = ctx.createLinearGradient(0, 0, 0, 300);
gradient.addColorStop(1, '#0f0');
gradient.addColorStop(0.5, '#ff0');
gradient.addColorStop(0, '#f00');
// loop
function renderFrame() {
var array = new Uint8Array(analyser.frequencyBinCount);
analyser.getByteFrequencyData(array);
var step = Math.round(array.length / meterNum); //sample limited data from the total array
ctx.clearRect(0, 0, cwidth, cheight);
for (var i = 0; i < meterNum; i++) {
var value = array[i * step];
if (capYPositionArray.length < Math.round(meterNum)) {
capYPositionArray.push(value);
};
ctx.fillStyle = capStyle;
//draw the cap, with transition effect
if (value < capYPositionArray[i]) {
ctx.fillRect(i * 12, cheight - (--capYPositionArray[i]), meterWidth, capHeight);
} else {
ctx.fillRect(i * 12, cheight - value, meterWidth, capHeight);
capYPositionArray[i] = value;
};
ctx.fillStyle = gradient; //set the filllStyle to gradient for a better look
ctx.fillRect(i * 12 /*meterWidth+gap*/ , cheight - value + capHeight, meterWidth, cheight); //the meter
}
requestAnimationFrame(renderFrame);
}
renderFrame();
audio.play();
};
Any idea what am I doing wrong?
You can usually fix this by simply adding a crossorigin option to your html audio tag
so this:
<audio src="http://50.22.218.101:38838/;steam.mp3" id="audio" controls>
becomes this:
<audio src="http://50.22.218.101:38838/;steam.mp3" crossorigin="anonymous" id="audio" controls>
Visualize stream using HTML5
Here's full example, combining #miknik's answer, your display code (which is awesome by the way), and a public web radio station
window.AudioContext = window.AudioContext || window.webkitAudioContext || window.mozAudioContext;
let audio = document.getElementById('audio')
let ctx = ""
let audioSrc = ""
function start(){
if (!ctx){
ctx = new AudioContext();
analyser = ctx.createAnalyser();
audioSrc = ctx.createMediaElementSource(audio)
// we have to connect the MediaElementSource with the analyser
audioSrc.connect(analyser)
analyser.connect(ctx.destination)
}
// we could configure the analyser: e.g. analyser.fftSize (for further infos read the spec)
// analyser.fftSize = 64;
// frequencyBinCount tells you how many values you'll receive from the analyser
var frequencyData = new Uint8Array(analyser.frequencyBinCount);
// we're ready to receive some data!
var canvas = document.getElementById('canvas'),
cwidth = canvas.width,
cheight = canvas.height - 2,
meterWidth = 10, //width of the meters in the spectrum
gap = 2, //gap between meters
capHeight = 2,
capStyle = '#fff',
meterNum = 800 / (10 + 2), //count of the meters
capYPositionArray = []; ////store the vertical position of hte caps for the preivous frame
ctx = canvas.getContext('2d'),
gradient = ctx.createLinearGradient(0, 0, 0, 300);
gradient.addColorStop(1, '#0f0');
gradient.addColorStop(0.5, '#ff0');
gradient.addColorStop(0, '#f00');
// loop
function renderFrame() {
var array = new Uint8Array(analyser.frequencyBinCount);
analyser.getByteFrequencyData(array);
var step = Math.round(array.length / meterNum); //sample limited data from the total array
ctx.clearRect(0, 0, cwidth, cheight);
for (var i = 0; i < meterNum; i++) {
var value = array[i * step];
if (capYPositionArray.length < Math.round(meterNum)) {
capYPositionArray.push(value);
};
ctx.fillStyle = capStyle;
//draw the cap, with transition effect
if (value < capYPositionArray[i]) {
ctx.fillRect(i * 12, cheight - (--capYPositionArray[i]), meterWidth, capHeight);
} else {
ctx.fillRect(i * 12, cheight - value, meterWidth, capHeight);
capYPositionArray[i] = value;
};
ctx.fillStyle = gradient; //set the filllStyle to gradient for a better look
ctx.fillRect(i * 12 /*meterWidth+gap*/ , cheight - value + capHeight, meterWidth, cheight); //the meter
}
requestAnimationFrame(renderFrame);
}
renderFrame();
audio.play();
}
function stop(){
audio.pause()
}
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
#container {
position: absolute;
top: 0;
left: 0;
background: #000;
width: 100%;
height: 100%;
}
#canvas {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: black;
z-index: -1;
opacity: .8;
}
.button-container{
padding-top: 5px;
display: grid;
grid-template-columns: repeat(2,300px);
grid-gap: 1px;
width: 100%;
align-items: center;
justify-content: center;
}
button{
width: 300px;
text-align: center;
}
<html>
<link rel="stylesheet" type="text/css" href="style.css">
<body>
<audio src="https://rfcmedia.streamguys1.com/MusicPulse.mp3" crossorigin="anonymous" id="audio" >HTML5 Audio element not supported</audio>
<div class="button-container">
<button onclick="start()">Stream Radio</button>
<button onclick="stop()">Stop Radio</button>
</div>
<canvas id="canvas"></canvas>
<script src="main.js"></script>
</body>
</html>

Canvas width percent in javascript

I have a canvas that I have in html that is supposed to be 25% of the page. I made a variable named width in javascript, and put it's value as 25%. When I make a context.clearRect(); with the width variable as the width parameter, it doesn't fix it what I was trying to do (which I have done tons of times) which is when the player rectangle moves, the clearRect keeps the background circulating so the rectangle isn't drawing (leaving a mark). Here is my width variable:
var width = 25%;
Here is my clearRect();
context.clearRect(0, 0, width, height);
Edit: I guess I will also post my whole entire code, to be easier.
<html>
<head>
<title></title>
<style type="text/css">
body {
background-color: #222222;
}
canvas {
background-color: #000000;
width: 25%;
height: 400px;
}
</style>
</head>
<body>
<canvas id="mainCanvas"></canvas>
<script type="text/javascript">
var canvas = document.getElementById("mainCanvas");
var context = canvas.getContext("2d");
var keys = [];
var speed = 4;
var width = 25%;
var height = 400;
window.addEventListener("keydown", function(e) {
keys[e.keyCode] = true;
}, false);
window.addEventListener("keyup", function(e) {
delete keys[e.keyCode];
}, false);
var player = {
x: 10,
y: 10,
width: 30,
height: 30
};
function game() {
update();
render();
}
function update() {
if (keys[40]) player.y++ * speed;
if (keys[38]) player.y-- * speed;
if (keys[37]) player.x-- * speed;
if (keys[39]) player.x++ * speed;
}
function render() {
context.clearRect(0, 0, (canvas.width * 0.25)), height);
context.fillStyle = "white";
context.fillRect(player.x, player.y, player.width, player.height);
}
setInterval(function() {
game();
}, 1000/30);
</script>
You need to use something like this:
context.clearRect(0, 0, (canvas.width * 0.25), height);
Try this?
<!DOCTYPE html>
<html>
<head>
<title></title>
<style type="text/css">
body {
background-color: #222222;
}
canvas {
background-color: #000000;
width: 25%;
height: 400px;
}
</style>
</head>
<body>
<canvas id="mainCanvas"></canvas>
<script type="text/javascript">
var canvas = document.getElementById("mainCanvas");
var context = canvas.getContext("2d");
var keys = [];
var speed = 4;
// var width = 25%;
var height = 400;
window.addEventListener("keydown", function(e) {
keys[e.keyCode] = true;
}, false);
window.addEventListener("keyup", function(e) {
delete keys[e.keyCode];
}, false);
var player = {
x: 10,
y: 10,
width: 30,
height: 30
};
function game() {
update();
render();
}
function update() {
if (keys[40]) player.y++ * speed;
if (keys[38]) player.y-- * speed;
if (keys[37]) player.x-- * speed;
if (keys[39]) player.x++ * speed;
}
function render() {
context.clearRect(0, 0, (canvas.width * 0.25), height);
context.fillStyle = "white";
context.fillRect(player.x, player.y, player.width, player.height);
}
setInterval(function() {
game();
}, 1000/30);
</script>
</body>
</html>
Not sure what you actually wanted to ask yet your code has two syntax errors - thus it does not execute correctly:
var keys = [];
var speed = 4;
//var width = 25%; //This is no valid assignment and the value is not used..
var height = 400;
and
function render() {
//context.clearRect(0, 0, (canvas.width * 0.25)), height); //One bracket too much, can skip both tho..
context.clearRect(0, 0, canvas.width * 0.25, height);
You need to put your canvas in a container, and set up the container the way you want, then you make your canvas 100% of the containers properties using
clientHeight
and
clientWidth
JSFiddle: https://jsfiddle.net/53n2s0s9/

Categories