Im just playing around with HTML but when I load my code, I get an error. Error Code: Out of Memory - javascript

the code is short and it cant be because of outdated systems as this laptop was bought 4 months ago.
Every time I click on the index.html file it takes 50 seconds to load and then I get the error. I am not sure what else to do as the Microsoft Help Team was useless. I am not sure if there are any errors in the code as I can't run it. Any help is appreciated.
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<title>A canvas</title>
</head>
<style type="text/css">
canvas {
border: 1px solid black;
}
</style>
<body>
<canvas id="canvas" height="1000px" width="1000px"></canvas>
<script>
var canvas = document.getElementById('canvas');
var c = canvas.getContext('2d');
canvas.addEventListener('mousedown', onDown, false);
var fireWall = false;
var score = 0;
while (score != 10){
c.font = "30px Comic Sans MS"
c.fillText(score, 500, 200)
c.font = "30px Comic Sans MS"
c.fillText("Click the Screen 10 Times to Win the Hardest Game Ever!!!", 50,300);
function onDown(){
console.log('working')
c.score++;
}
if(score === 10){
fireWall = true;
break;
}
}
if(fireWall === true){
c.fill(255, 153, 0);
c.noStroke();
c.ellipse(mouseX-90, mouseY-30, 75, 25);
c.ellipse(mouseX-90, mouseY-80, 85, 35);
c.rect(mouseX-103, mouseY-80, 25,45);
c.rect(mouseX-132, mouseY-155, 85,75);
c.textSize(50);
c.fill(255,0,0);
c.text("YOU WON", mouseX-205, mouseY-170);
}
</script>
</body>
</html>
com/jywPv.png

const c = document.getElementById('canvas').getContext('2d');
const game = { // You could use an Object literal to store stuff
fireWall: false,
score: 0,
mouseX: 0,
mouseY: 0,
};
const draw = () => { // Create a function to handle drawing
// Don't forget to clear the canvas before painting
c.clearRect(0, 0, c.canvas.width, c.canvas.height);
c.font = "30px Comic Sans MS";
if (game.fireWall) {
c.fillText("YOU WON", game.mouseX-80, game.mouseY-5);
} else {
c.fillText(game.score, 500, 200); // Retrieve the score from game Object
c.fillText("Click the Screen 10 Times to Win the Hardest Game Ever!!!", 50, 300);
}
}
const onDown = (ev) => { // Don't forget the ev Event!
if (game.fireWall) return; // Prevent additional clicks if firewall reached
const bcr = c.canvas.getBoundingClientRect();
game.mouseX = ev.clientX - bcr.x;
game.mouseY = ev.clientY - bcr.y;
game.score++;
if (game.score >= 10) {
game.fireWall = true;
}
draw();
}
draw(); // First draw!
c.canvas.addEventListener('mousedown', onDown); // And draw on click
canvas {
border: 1px solid black;
}
<canvas id="canvas" height="1000px" width="1000px"></canvas>

Related

Why do buttons on mobile browsers appear to have a larger click area?

At work, they needed a quick and dirty example to hand-sign a document and append it to JSON as a base64 Data URL. It works all fine and dandy in itself, but my own curiosity got the better of me and I was annoyed to find out, that the area of the buttons appeared to be much larger on mobile than they looked like. But even inspecting buttons in my example project didn't help me a lot to pin down the problems.
Disclaimer: I have to also point out, for people who look for a similar solution to NOT just copy-paste this example here. It's serviceable and works probably in 99% of the cases just fine for this purpose, but the drawing is not optimal. Why? Because I keep adding points indefinitely as long as the finger touches the canvas... and with each move, it goes through the array and REDRAWS all the lines! It becomes pretty noticeable after you covered a fair portion of the small canvas. It would be more elegant to go through the tracked points and kick them out of the array once drawn and not only when we raise the finger from the touchscreen. But if you merely use it to sign something like in my example, the example should be perfectly serviceable with no frills.
I did add a snippet as well. Don't forget, it's only working on mobile browsers or if you use emulation on your chrome browser, for example.
"use strict";
const canvas = document.getElementById('sign');
const context = canvas.getContext('2d');
context.lineCap = 'round';
context.lineJoin = 'round';
context.strokeStyle = 'black';
context.lineWidth = 2;
let points = [];
let isPainting = false;
setup();
function setup() {
if (isMobile() || isIpad()) {
setupMobile();
} else {
// Some other stuff that was supposed to happen, but was canned
return;
}
}
function setupMobile() {
canvas.addEventListener('touchstart', (e) => {
addToDrawingPointsTouch(canvas, e);
if (!isPainting) {
isPainting = !isPainting;
}
const ctx = context;
// Not the most elegant solution for the initial call, but touchmove takes a bit to trigger
const initialStarting = points[0];
ctx.beginPath();
ctx.moveTo(initialStarting.x, initialStarting.y);
ctx.lineTo(initialStarting.x, initialStarting.y);
ctx.stroke();
}, { passive: true })
canvas.addEventListener('touchmove', (e) => {
if (isPainting) {
addToDrawingPointsTouch(canvas, e);
const ctx = context;
points.forEach((v, index) => {
if (points[index + 1]) {
ctx.beginPath();
ctx.moveTo(v.x, v.y);
ctx.lineTo(points[index + 1]?.x, points[index + 1]?.y);
ctx.stroke();
}
})
}
}, { passive: true })
canvas.addEventListener('touchend', () => {
if (isPainting) {
isPainting = !isPainting;
points = [];
}
}, { passive: true })
}
function addToDrawingPointsTouch(canvas, mouseEvent) {
const rect = canvas.getBoundingClientRect();
points.push({
x: (mouseEvent.touches[0].clientX - rect.left) / (rect.right - rect.left) * canvas.width,
y: (mouseEvent.touches[0].clientY - rect.top) / (rect.bottom - rect.top) * canvas.height
});
}
function isMobile() {
if (/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)) {
return true
} else {
return false;
}
}
function isIpad() {
if (navigator.userAgent.match(/Mac/) && navigator.maxTouchPoints && navigator.maxTouchPoints > 2) {
return true;
}
else {
false;
}
}
function clearCanvas() {
context.clearRect(0, 0, canvas.width, canvas.height);
}
function createCanvasPngDataUrl() {
return canvas.toDataURL('image/png');
}
body {
user-select: none;
-webkit-user-select: none;
touch-action: none;
-ms-touch-action: none;
}
<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8'>
<meta http-equiv='X-UA-Compatible' content='IE=edge'>
<title>Page Title</title>
<meta name='viewport' content='width=device-width, initial-scale=1'>
<link rel='stylesheet' type='text/css' media='screen' href='main.css'>
<script defer src='main.js'></script>
</head>
<body>
<form id="form">
<canvas style="border: 1px solid black;" id="sign">
</canvas>
</form>
<div id="menu">
<button onclick="createCanvasPngDataUrl()">Create DataUrl</button>
<button onclick="clearCanvas()" id="clear">Clear</button>
</div>
</body>
</html>

The score is not updating. Can you please tell me what is wrong with the code?

The score is not updating. Please help me make the score update.
When I click the button with the function for 'addScore', the displayed score will not change to a new one.
I have tried a lot of things. Non of which have worked
var score = 0;
function addScore(){ score ++ }
function drawScore() {
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.font = "16px Arial";
ctx.fillStyle = "red";
ctx.fillText("Score: " +score, 8, 20);
}
drawScore();
I am expecting it to update the score, but it does not. It remains at 0.
The problem has been solved bu the text keeps increasing and over laps it.
HTML elements are not reactive to variables changes. When you created the element with drawScore you informed the current score value and inserted this into DOM, however, updating score will not update this because it is not a reference.
To make this work you will need to updated ctx text on every click.
One simple example would be:
var score = 0;
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
function addScore(){
score++;
setScore();
}
function drawScore() {
ctx.font = "16px Arial";
ctx.fillStyle = "red";
setScore();
}
function setScore() {
ctx.clearRect(0, 0, c.width, c.height);
ctx.fillText("Score: " +score, 8, 20);
}
drawScore();
The canvas does not maintain a reference to your variable (or any values for that matter). Canvas is like an image, it does not have a DOM. You will need to call drawScore() again and maybe clear that portion of the canvas before drawing.
function addScore(){
score++;
drawScore();
}
Demo
You should use a different coding approach, keeping your CSS, and JavaScript separate from your HTML.
//<![CDATA[
/* external.js */
var doc, bod, M, I, S, Q, score = 0, addScore, drawScore; // for use on other loads
addEventListener('load', function(){ // make yourself a tiny library
doc = document; bod = doc.body;
M = function(tag){
return doc.createElement(tag);
}
I = function(id){
return doc.getElementById(id);
}
S = function(selector, within){
var w = within || doc;
return w.querySelector(selector);
}
Q = function(selector, within){
var w = within || doc;
return w.querySelectorAll(selector);
}
addScore = function(){
return ++score;
}
var canvas = I('canvas'), ctx = canvas.getContext('2d'), add = I('add');
ctx.font = '16px Arial'; ctx.fillStyle = 'red';
drawScore = function(){
ctx.clearRect(0, 0, 160, 90); ctx.fillText('Score: '+score, 8, 20);
}
add.onclick = function(){
addScore(); drawScore();// other functions or code here
};
}); // end load
//]]>
/* external.css */
*{
box-sizing:border-box; padding:0; margin:0;
}
html,body{
width:100%; height:100%;
}
body{
background:#ccc;
}
#content{
padding:7px;
}
#canvas{
background:#fff;
}
#add{
display:block; padding:3px 5px;
}
<!DOCTYPE html>
<html xmlns='http://www.w3.org/1999/xhtml' xml:lang='en' lang='en'>
<head>
<meta charset='UTF-8' /><meta name='viewport' content='width=device-width, height=device-height, initial-scale:1' />
<title>Test Template</title>
<link type='text/css' rel='stylesheet' href='external.css' />
<script type='text/javascript' src='external.js'></script>
</head>
<body>
<div id='content'>
<canvas id='canvas' width='160' height='90'></canvas>
<input id='add' type='button' value='add score' />
</div>
</body>
</html>

Javascript how to make object appear over a background image

Hello I am trying to create a guitar hero sort of program with red circles appearing over a violin image when the corresponding key presses are pressed but I can't seem to be able to make them appear over the image even if I write the code after the canvas code. Can someone help me with this? I would also like to make the circles disappear after a while but timeout won't do the trick here because the image is not one color only for example changing the red circles to the background color after a while. How would i do this?
<html>
<head>
<title>Violin Hero</title>
<canvas id="myCanvas" width="1024" height="768"></canvas>
<style>
body {
background-image: url("violin.jpg");
background-size: 2500px 1300px;
}
</style>
</head>
<body>
<canvas id="myCanvas" width="1024" height="768"></canvas>
<img id="bow" src="bow.jpg" style="display:none;" />
<script>
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
window.addEventListener("keydown", soundPlay);
function fillRed() {
ctx.fillStyle = "red";
ctx.fill();
}
function keyQ(){
ctx.beginPath();
ctx.arc(1200, 300, 15, 0, Math.PI*2);
ctx.fillStyle = "red";
ctx.fill();
}
function keyW(){
ctx.beginPath();
ctx.arc(300, 300, 15, 0, Math.PI*2);
ctx.fillStyle = "red";
ctx.fill();
}
function keyE(){
ctx.beginPath();
ctx.arc(900, 500, 15, 0, Math.PI*2);
ctx.fillStyle = "red";
ctx.fill();
}
function keyR(){
ctx.beginPath();
ctx.arc(950, 100, 15, 0, Math.PI*2);
ctx.fillStyle = "red";
ctx.fill();
}
//var x = event.keyCode;
//<input type="text" onkeydown="pressedKey(event)">
function soundPlay(event) {
var x = event.keyCode;
if (x == 27) { // 27 is the ESC key
alert ("You pressed the Escape key!");
}
else if (x == 81) {
keyQ();
var sound = new Audio('1.mp3');
sound.play();
setTimeout(fillRed, 200);
}
else if (event.keyCode == 87) {
keyW();
var sound = new Audio("2.mp3");
sound.play();
setTimeout(fillRed, 200);
}
else if (event.keyCode == 69) {
keyE();
var sound = new Audio("3.mp3");
sound.play();
setTimeout(fillRed, 200);
}
else if (event.keyCode == 82) {
keyR();
var sound = new Audio("4.mp3");
sound.play();
setTimeout(fillRed, 200);
}
}
</script>
</body>
</html>
To bring something in front of images/To bring something always behind elements, one should use z-index.
Make a css for background image like this:
#backgroundImg{
position: absolute;
left: 0px;
top: 0px;
z-index: -1;
}
In this way, the background image will always be behind. Please check this or this for more details.
For your second question, I suggest you should make another post and keep this question focused on one issue only.
I've created a simple Plunkr example for you on how to achieve this kind of functionality in JS.
Click s, a or any other to show a red dot.
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css">
<script src="script.js"></script>
</head>
<body id='mybody'>
<img id='violin' src='http://cdn.shopify.com/s/files/1/0704/3831/products/Antoni_Debut_Violin_Outfit_3677b25a-7618-46f7-9313-6080c2a51e27_grande.jpg?v=1444483336'>
<script>
document.addEventListener('keydown', (event) => {
console.log(event);
if (event.key.toLowerCase() === 's') {
showRedDot(110, 420);
} else if (event.key.toLowerCase() === 'a') {
showRedDot(150, 350);
} else {
showRedDot(200, 300);
}
});
var showRedDot = (top, left) => {
var oldDot = document.getElementById('redDot');
if (oldDot) {
oldDot.remove();
}
var dot = document.createElement('DIV');
dot.id = 'redDot';
dot.style.width = '10px';
dot.style.height = '10px';
dot.style.position = 'absolute';
dot.style.borderRadius = '100%';
dot.style.background = 'red';
dot.style.top = top + 'px';
dot.style.left = left + 'px';
document.getElementById('mybody').appendChild(dot);
};
</script>
</body>
</html>
Here's a working Plunkr

How can I reverse the direction of an element on a canvas?

I tried to make it so that when my 'Player' reaches a jumpDistance of 50, it falls down, so he makes a small ' jump ' .
The code might not be exactly "clean" at this point, but I'm getting started with Javascript.
I made the player jump by using a for loop with a delay. I tried to make him go down the same way, but this didn't work out the way I planned.
Fiddle demo
** NOTE : Press space to start!
<!DOCTYPE html>
<html>
<style>
#canvas {
background-color: rgba(177, 177, 177, 1);
}
</style>
<body>
<div>
<p id="jumpDistance"></p>
<p id="jumpDirection"></p>
</div>
<canvas id="canvas" width="800" height="400"></canvas>
<script>
var canvas = document.querySelector('#canvas');
var context = canvas.getContext('2d');
var xPos = 150;
var yPos = 375;
var jumpDistance = 0;
function spelerObj() {
canvas.width=canvas.width;
context.rect(xPos, yPos, 25, 25);
context.stroke();
context.fillStyle = "#FF0000";
context.fillRect(xPos, yPos, 25, 25);
}
function jump(e) { //Here the player jumps, with a loop that calculates it's jump-distance.
//alert(e.keyCode);
if (e.keyCode == 32) {//
function upLoop() {
setTimeout(function () {
if(jumpDistance < 50) {
yPos -= 1;
jumpDistance++;
upLoop();
spelerObj();
document.getElementById("jumpDistance").innerHTML = jumpDistance.toString();
}
}, 1)
}
upLoop();
spelerObj();
}
}
document.onkeydown = jump;
</script>
</body>
</html>
You'd need a downloop that you can switch to at the top of the jump:
function upLoop() {
setTimeout(function() {
if (jumpDistance < 50) {
yPos -= 1;
jumpDistance++;
upLoop();
} else {
downLoop();
}
spelerObj();
document.getElementById("jumpDistance").innerHTML = jumpDistance.toString();
}, 1)
}
function downLoop() {
setTimeout(function() {
if (jumpDistance > 0) {
yPos += 1;
jumpDistance--;
downLoop();
}
spelerObj();
document.getElementById("jumpDistance").innerHTML = jumpDistance.toString();
}, 1)
}
Demo 1
You could also vary the timeout duration to add a pseudo-gravity effect.
Demo 2

Toggle Onclick Issue in Javascript

Simply put, I'm trying to toggle a button to make a line bold (or not). I read a few questions here similar to this problem, but the solutions haven't helped me. Here's my code:
<!DOCTYPE HTML>
<html>
<head>
<style>
body {
margin: 0px;
padding: 0px;
}
</style>
</head>
<body>
<div id="DrawLineDiv">
<canvas id="DrawLineCanvas" width="578" height="200"></canvas>
<script>
var canvas = document.getElementById('DrawLineCanvas');
var context = canvas.getContext('2d');
// Use beginPath() to declare that a new path is to be drawn
context.beginPath();
// Place the drawing cursor at the desired point
context.moveTo(100, 150);
// Determine where to stop drawing
context.lineTo(450,50);
//Draw the line
context.stroke();
</script>
</div>
<script>
var canvas = document.getElementById("DrawLineCanvas");
//var context = canvas.getContext('2d');
function toggleLineBold(button) {
var button;
if (button == "BoldNow") {
context.lineWidth = 15;
context.stroke();
document.getElementById("BoldLineButton").onclick = function(){
toggleLineBold('Regular');
};
} else {
context.lineWidth = 1;
context.stroke();
document.getElementById("BoldLineButton").onclick = function(){
toggleLineBold('BoldNow');
};
return;
};
};
</script>
<div id="BoldLineButton" style="height:50px; width:120px; border:2px solid #6495ed; background-color:#bcd2ee; border-radius:10px; margin-left: 5px; text-align:center" onclick="toggleLineBold('BoldNow')">
<br/>Toggle Bold Line<br/>
</div>
</body>
</html>
The line changes to bold, but triggers an error in the javascript at the line trying to change the onclick event. I know I've got something wrong, I'm just not sure what.
Thank's in advance for your assistance.
LIVE DEMO
HTML:
<canvas id="DrawLineCanvas" width="578" height="200"></canvas>
<button id="BoldLineButton">Line size: <b>1</b></button>
JS:
var doc = document,
canvas = doc.querySelector('#DrawLineCanvas'),
boldBtn = doc.querySelector('#BoldLineButton'),
ctx = canvas.getContext('2d'),
size = [1, 3, 5, 10, 15], // use only [1, 15] if you want
currSize = 0; // size[0] = 1 // Index pointer to get the value out of the
// size Array
function draw(){
canvas.width = canvas.width;
ctx.beginPath();
ctx.moveTo(100, 150);
ctx.lineTo(450,50);
ctx.lineWidth = size[currSize]; // Use currSize Array index
ctx.stroke();
}
draw();
function toggleLineBold() {
++currSize; // Increase size and
currSize %= size.length; // loop if needed.
boldBtn.getElementsByTagName('b')[0].innerHTML = size[currSize];
draw();
}
boldBtn.addEventListener("click", toggleLineBold);

Categories