Related
var sketcher = null;
var brush = null;
function Sketcher(canvasID, brushImage) {
this.renderFunction = (brushImage == null || brushImage == undefined) ? this.updateCanvasByLine : this.updateCanvasByBrush;
this.brush = brushImage;
this.touchSupported = Modernizr.touch;
this.canvasID = canvasID;
this.canvas = $("#" + canvasID);
this.context = this.canvas.get(0).getContext("2d");
this.context.strokeStyle = "#000000";
this.context.lineWidth = 3;
this.lastMousePoint = {
x: 0,
y: 0
};
if (this.touchSupported) {
this.mouseDownEvent = "touchstart";
this.mouseMoveEvent = "touchmove";
this.mouseUpEvent = "touchend";
} else {
this.mouseDownEvent = "mousedown";
this.mouseMoveEvent = "mousemove";
this.mouseUpEvent = "mouseup";
}
this.canvas.bind(this.mouseMoveEvent, this.onCanvasMouseMove());
}
Sketcher.prototype.onCanvasMouseMove = function() {
var self = this;
return function(event) {
self.mouseMoveHandler = self.onCanvasMouseMove()
self.mouseUpHandler = self.onCanvasMouseUp()
$(document).bind(self.mouseMoveEvent, self.mouseMoveHandler);
$(document).bind(self.mouseUpEvent, self.mouseUpHandler);
self.updateMousePosition(event);
self.renderFunction(event);
}
}
Sketcher.prototype.onCanvasMouseMove = function() {
var self = this;
return function(event) {
self.renderFunction(event);
event.preventDefault();
return false;
}
}
Sketcher.prototype.onCanvasMouseUp = function(event) {
var self = this;
return function(event) {
$(document).unbind(self.mouseMoveEvent, self.mouseMoveHandler);
$(document).unbind(self.mouseUpEvent, self.mouseUpHandler);
self.mouseMoveHandler = null;
self.mouseUpHandler = null;
}
}
Sketcher.prototype.updateMousePosition = function(event) {
var target;
if (this.touchSupported) {
target = event.originalEvent.touches[0]
} else {
target = event;
}
var offset = this.canvas.offset();
this.lastMousePoint.x = target.pageX - offset.left;
this.lastMousePoint.y = target.pageY - offset.top;
}
Sketcher.prototype.updateCanvasByLine = function(event) {
this.context.beginPath();
this.context.moveTo(this.lastMousePoint.x, this.lastMousePoint.y);
this.updateMousePosition(event);
this.context.lineTo(this.lastMousePoint.x, this.lastMousePoint.y);
this.context.stroke();
}
Sketcher.prototype.updateCanvasByBrush = function(event) {
var halfBrushW = this.brush.width / 2;
var halfBrushH = this.brush.height / 2;
var start = {
x: this.lastMousePoint.x,
y: this.lastMousePoint.y
};
this.updateMousePosition(event);
var end = {
x: this.lastMousePoint.x,
y: this.lastMousePoint.y
};
var distance = parseInt(Trig.distanceBetween2Points(start, end));
var angle = Trig.angleBetween2Points(start, end);
var x, y;
for (var z = 0;
(z <= distance || z == 0); z++) {
x = start.x + (Math.sin(angle) * z) - halfBrushW;
y = start.y + (Math.cos(angle) * z) - halfBrushH;
//console.log( x, y, angle, z );
this.context.drawImage(this.brush, x, y);
}
}
Sketcher.prototype.toString = function() {
var dataString = this.canvas.get(0).toDataURL("image/png");
var index = dataString.indexOf(",") + 1;
dataString = dataString.substring(index);
return dataString;
}
Sketcher.prototype.toDataURL = function() {
var dataString = this.canvas.get(0).toDataURL("image/png");
return dataString;
}
var Trig = {
distanceBetween2Points: function ( point1, point2 ) {
var dx = point2.x - point1.x;
var dy = point2.y - point1.y;
return Math.sqrt( Math.pow( dx, 2 ) + Math.pow( dy, 2 ) );
},
angleBetween2Points: function ( point1, point2 ) {
var dx = point2.x - point1.x;
var dy = point2.y - point1.y;
return Math.atan2( dx, dy );
}
}
var canvas = document.getElementById("sketch");
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
brush = new Image();
brush.src = "https://upload.wikimedia.org/wikipedia/commons/thumb/e/eb/Ash_Tree_-_geograph.org.uk_-_590710.jpg/440px-Ash_Tree_-_geograph.org.uk_-_590710.jpg";
brush.onload = function() {
sketcher = new Sketcher("sketch", brush);
};
body {
margin: 0;
padding: 0;
}
* {
box-sizing: border-box;
}
.sketch-container {
position: relative;
position: absolute;
height: 100vh;
width: 100%;
}
#sketch {
background: none yellow;
position: absolute;
height: 100vh;
width: 100%;
}
.button-container {
position: absolute;
left: 10px;
top: 10px;
opacity: .5;
background: none blue;
font-size: 50px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/modernizr/2.8.3/modernizr.min.js"></script>
<div class="sketch-container">
<canvas id="sketch"></canvas>
<button type="button" class="button-container">Can you draw below me?</button>
</div>
I am drawing an image using this javascript code:
var sketcher = null;
var brush = null;
function Sketcher(canvasID, brushImage) {
this.renderFunction = (brushImage == null || brushImage == undefined) ? this.updateCanvasByLine : this.updateCanvasByBrush;
this.brush = brushImage;
this.touchSupported = Modernizr.touch;
this.canvasID = canvasID;
this.canvas = $("#" + canvasID);
this.context = this.canvas.get(0).getContext("2d");
this.context.strokeStyle = "#000000";
this.context.lineWidth = 3;
this.lastMousePoint = {
x: 0,
y: 0
};
if (this.touchSupported) {
this.mouseDownEvent = "touchstart";
this.mouseMoveEvent = "touchmove";
this.mouseUpEvent = "touchend";
} else {
this.mouseDownEvent = "mousedown";
this.mouseMoveEvent = "mousemove";
this.mouseUpEvent = "mouseup";
}
this.canvas.bind(this.mouseMoveEvent, this.onCanvasMouseMove());
}
Sketcher.prototype.onCanvasMouseMove = function() {
var self = this;
return function(event) {
self.mouseMoveHandler = self.onCanvasMouseMove()
self.mouseUpHandler = self.onCanvasMouseUp()
$(document).bind(self.mouseMoveEvent, self.mouseMoveHandler);
$(document).bind(self.mouseUpEvent, self.mouseUpHandler);
self.updateMousePosition(event);
self.renderFunction(event);
}
}
Sketcher.prototype.onCanvasMouseMove = function() {
var self = this;
return function(event) {
self.renderFunction(event);
event.preventDefault();
return false;
}
}
Sketcher.prototype.onCanvasMouseUp = function(event) {
var self = this;
return function(event) {
$(document).unbind(self.mouseMoveEvent, self.mouseMoveHandler);
$(document).unbind(self.mouseUpEvent, self.mouseUpHandler);
self.mouseMoveHandler = null;
self.mouseUpHandler = null;
}
}
Sketcher.prototype.updateMousePosition = function(event) {
var target;
if (this.touchSupported) {
target = event.originalEvent.touches[0]
} else {
target = event;
}
var offset = this.canvas.offset();
this.lastMousePoint.x = target.pageX - offset.left;
this.lastMousePoint.y = target.pageY - offset.top;
}
Sketcher.prototype.updateCanvasByLine = function(event) {
this.context.beginPath();
this.context.moveTo(this.lastMousePoint.x, this.lastMousePoint.y);
this.updateMousePosition(event);
this.context.lineTo(this.lastMousePoint.x, this.lastMousePoint.y);
this.context.stroke();
}
Sketcher.prototype.updateCanvasByBrush = function(event) {
var halfBrushW = this.brush.width / 2;
var halfBrushH = this.brush.height / 2;
var start = {
x: this.lastMousePoint.x,
y: this.lastMousePoint.y
};
this.updateMousePosition(event);
var end = {
x: this.lastMousePoint.x,
y: this.lastMousePoint.y
};
var distance = parseInt(Trig.distanceBetween2Points(start, end));
var angle = Trig.angleBetween2Points(start, end);
var x, y;
for (var z = 0;
(z <= distance || z == 0); z++) {
x = start.x + (Math.sin(angle) * z) - halfBrushW;
y = start.y + (Math.cos(angle) * z) - halfBrushH;
//console.log( x, y, angle, z );
this.context.drawImage(this.brush, x, y);
}
}
Sketcher.prototype.toString = function() {
var dataString = this.canvas.get(0).toDataURL("image/png");
var index = dataString.indexOf(",") + 1;
dataString = dataString.substring(index);
return dataString;
}
Sketcher.prototype.toDataURL = function() {
var dataString = this.canvas.get(0).toDataURL("image/png");
return dataString;
}
var Trig = {
distanceBetween2Points: function ( point1, point2 ) {
var dx = point2.x - point1.x;
var dy = point2.y - point1.y;
return Math.sqrt( Math.pow( dx, 2 ) + Math.pow( dy, 2 ) );
},
angleBetween2Points: function ( point1, point2 ) {
var dx = point2.x - point1.x;
var dy = point2.y - point1.y;
return Math.atan2( dx, dy );
}
}
var canvas = document.getElementById("sketch");
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
brush = new Image();
brush.src = "https://upload.wikimedia.org/wikipedia/commons/thumb/e/eb/Ash_Tree_-_geograph.org.uk_-_590710.jpg/440px-Ash_Tree_-_geograph.org.uk_-_590710.jpg";
brush.onload = function() {
sketcher = new Sketcher("sketch", brush);
};
It works well and draws an image exactly as I would like. However, I have divs on top with text for which I have onclick functions on.
Picture of how the image is being drawn
The problem is the image is not being drawn underneath the divs because the canvas is under them. I understand I may need to add a listener to the window and draw according to that, but I have tried and tried and do not understand where something like that goes/what needs to be replaced.
Something that I've tried is to get rid of pointer events, which of course works to maintain the continuity of the image being dragged, but prevents me from clicking on the button.
Thanks
I am trying to make my cloud draggable. It works but as can be seen in the example that i have, the cloud always clippes from the center to the mouse possition.
Here is my current set-up.
$(document).ready(function () {
var canvas = document.getElementById("background-canvas");
canvas.width = $(window).width();
canvas.height = $(window).height();
canvas.style.zIndex = -1;
var ctx = canvas.getContext("2d");
var mousePosition = new Vector2d(0,0);
var background = new Background(ctx, canvas.width, canvas.height, new Color(224,247,250,0.8));
var cloud = new Cloud(background, 300, 100, new Vector2d(10,10), 20, 1000);
img=new Image();
img.src="https://i.imgur.com/hIVsoho.png";
background.addCloud(cloud);
for (var i = 0; i < background.allClouds.length; i++){
var selectedCloud = background.allClouds[i];
for (var j = 0; j < selectedCloud.maxNumberofPixels; j++){
var pixel = cloud.createPixel(); // TODO: cloud shall not define pixel.
//new Pixel(2, 4, getRandomLocationWithinParent(selectedCloud), new Vector2d(0,5), new Vector2d(0,0), new Color(0,0,128,1));
cloud.addPixel(pixel);
}
}
/*
* Input listeners
*/
document.addEventListener("mousemove", function (evt) {
mousePosition = getMousePos(canvas, evt);
}, false);
document.addEventListener("mousedown", function (evt){
console.log(mousePosition);
for(var i = 0; i < background.allClouds.length; i++)
if(background.allClouds[i].hover(mousePosition))
background.allClouds[i].isClicked = true;
}, false)
document.addEventListener("mouseup", function (evt){
for(var i = 0; i < background.allClouds.length; i++)
if(background.allClouds[i].hover(mousePosition))
background.allClouds[i].isClicked = false;
}, false)
setInterval(updateBackground, 20);
function updateBackground() {
// paint background color.
ctx.fillStyle = background.color.getColorString();
ctx.fillRect(0,0,background.width, background.height);
// paint clouds
for(var i = 0; i < background.allClouds.length; i++){
var selectedCloud = background.allClouds[i];
//ctx.fillStyle = selectedCloud.color.getColorString();
//ctx.fillRect(0, 0, selectedCloud.width, selectedCloud.height); rectangle view of cloud.
// paint rain
var deadPixelContainer = [];
for (var j = 0; j < selectedCloud.allPixels.length; j++){
var selectedPixel = selectedCloud.allPixels[j];
ctx.fillStyle = selectedPixel.color.getColorString();
ctx.save();
ctx.translate(selectedPixel.location.x, selectedPixel.location.y);
ctx.fillRect(-selectedPixel.width / 2, -selectedPixel.height / 2, selectedPixel.width, selectedPixel.height);
ctx.restore();
if(!selectedPixel.alive){
deadPixelContainer.push(selectedPixel);
continue;
}
selectedPixel.update();
selectedPixel.checkEdges(background);
}
if(deadPixelContainer.length > 0){
selectedCloud.removePixels(deadPixelContainer);
}
ctx.save();
ctx.translate(selectedCloud.location.x, selectedCloud.location.y);
ctx.drawImage(img,0,0,img.width,img.height,-25, -10,350,100);
ctx.restore();
cloud.update(mousePosition);
}
}
// TODO: Create object for mouse
function getMousePos(canvas, evt) {
var rect = canvas.getBoundingClientRect();
return new Vector2d(evt.clientX - rect.left, evt.clientY - rect.top);
}
});
function Cloud(background, width, height, location, startNumberOfPixels, maxNumberofPixels){
this.width = width;
this.height = height;
this.location = location;
this.allPixels = [];
this.maxNumberofPixels = maxNumberofPixels;
this.color = new Color(255,255,255,0.5);
this.isClicked = false;
this.rainStrength = 5; // how often cloud spawns new pixels per update cycle.
this.addPixel = function(pixel){
if(this.allPixels.length <= startNumberOfPixels)
this.allPixels.push(pixel);
}
this.update = function(mousePosition){
// make cloud draggable
if(this.isClicked){
var offsetX = mousePosition.x - this.location.x;
var offsetY = mousePosition.y - this.location.y;
this.location = new Vector2d(this.location.x + offsetX - this.width/2, this.location.y + offsetY - this.height/2);
}
// add more pixels overtime.
if(this.allPixels.length <= this.maxNumberofPixels)
for(var i = 0; i < this.rainStrength; i++)
this.allPixels.push(this.createPixel());
}
this.hover = function(mousePosition){
if(mousePosition.x > this.location.x
&& mousePosition.x < this.location.x + this.width
&& mousePosition.y > this.location.y
&& mousePosition.y < this.location.y + this.height)
return true;
return false;
}
this.createPixel = function(){
return new Pixel(2, 4, this.getRandomLocation(), new Vector2d(0,7), new Vector2d(0,0.05), new Color(0,0,128,1));
}
this.removePixels = function(deadPixelContainer){
for(var i = 0; i < deadPixelContainer.length; i++){
try{
var pixelContainer = this.allPixels.slice();
pixelContainer.splice(this.allPixels.findIndex(v => v === deadPixelContainer[i]), 1).slice();
this.allPixels = pixelContainer.slice();
}catch(e){
console.log(e);
}
}
}
this.getRandomLocation = function(){
var minWidth = this.location.x;
var maxWidth = this.location.x + this.width;
var minHeight = this.location.y + this.height/2; // don't count upper part of cloud. Rain forms at the bottom.
var maxHeight = this.location.y + this.height;
var randomWidthLocation = Math.random() * (maxWidth - minWidth + 1)+minWidth;
var randomHeightLocation = Math.random() * (maxHeight - minHeight + 1) + minHeight;
return new Vector2d(randomWidthLocation, randomHeightLocation);
}
}
function Background(ctx, width, height, color){
this.width = width;
this.height = height;
this.color = color; //"#191919"
this.isPaused = false;
this.allPixels = []; // might need to be removed.
this.allClouds = [];
this.pixelCount = 150;
this.addCloud = function(cloud){
this.allClouds.push(cloud);
};
this.refreshCanvas = function(){
this.width = $(window).width();
this.height = $(window).height();
};
this.addPixelOn = function(pixelWidht, pixelHeight, location, velocity, acceleration, color) { // might need to be removed.
var pixel = new Pixel(pixelWidht, pixelHeight, location, velocity, acceleration, color);
this.allPixels.push(pixel);
};
this.addPixel = function(pixelWidht, pixelHeight, velocity, acceleration, color) { // might need to be removed.
var location = new Vector2d(Math.random() * this.width, Math.random() * this.height);
this.addPixelOn(pixelWidht, pixelHeight, location, velocity, acceleration, color);
};
}
function Pixel(widht, height, location, velocity, acceleration, color) {
this.height = height;
this.width = widht;
this.color = color; //"#00CC33"
this.location = location;
this.velocity = velocity;
this.acceleration = acceleration;
this.alive = true;
this.update = function () {
this.velocity.add(this.acceleration);
//this.velocity.limit(topspeed);
this.location.add(this.velocity);
};
this.checkEdges = function (background) {
if (this.location.y > background.height) {
this.alive = false;
}
};
this.setColor = function(color){
this.color = color;
};
this.setHeight = function(height){
this.height = height;
};
this.setWidth = function(width){
this.width = width;
}
}
function Color(r,g,b,o){
this.red = r;
this.green = g;
this.blue = b;
this.opacity = o;
this.getColorString = function(){
return "rgba("+this.red+","+this.green+","+this.blue+","+this.opacity+")";
}
}
function Vector2d(x, y) {
this.x = x;
this.y = y;
this.add = function (vector2d) {
this.x += vector2d.x;
this.y += vector2d.y;
};
this.sub = function (vector2d) {
this.x -= vector2d.x;
this.y -= vector2d.y;
};
this.mult = function (mult) {
this.x *= mult;
this.y *= mult;
};
this.div = function (div) {
this.x /= div;
this.y /= div;
};
this.mag = function () {
return Math.sqrt(this.x * this.x, this.y * this.y);
};
this.norm = function () {
var m = this.mag();
if (m !== 0) {
this.div(m);
}
}
}
#background-canvas {
position: fixed;
width: 100%;
height: 100%
background-color:red;
top:0;
left:0;
}
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<canvas id="background-canvas" />
</body>
</html>
The code that sets the location of the cloud when dragged is this:
// make cloud draggable
if(this.isClicked){
var offsetX = mousePosition.x - this.location.x;
var offsetY = mousePosition.y - this.location.y;
this.location = new Vector2d(this.location.x + offsetX - this.width/2, this.location.y + offsetY - this.height/2);
}
This does not work correctly. I want it not to clip to the center.
Can any one help me with this ?
If its not completely clear what the question is or if you need any extra information please ask.
You need to remember the click location within the cloud's local coordinate system:
if(background.allClouds[i].hover(mousePosition)) {
background.allClouds[i].isClicked = true;
background.allClouds[i].clickLocalPosition = new Vector2d(mousePosition.x, mousePosition.y);
background.allClouds[i].clickLocalPosition.sub(background.allClouds[i].location);
}
Then, when you update, you calculate the new position based on the click location:
this.location.x = mousePosition.x - this.clickLocalPosition.x;
this.location.y = mousePosition.y - this.clickLocalPosition.y;
$(document).ready(function () {
var canvas = document.getElementById("background-canvas");
canvas.width = $(window).width();
canvas.height = $(window).height();
canvas.style.zIndex = -1;
var ctx = canvas.getContext("2d");
var mousePosition = new Vector2d(0,0);
var background = new Background(ctx, canvas.width, canvas.height, new Color(224,247,250,0.8));
var cloud = new Cloud(background, 300, 100, new Vector2d(10,10), 20, 1000);
img=new Image();
img.src="https://i.imgur.com/hIVsoho.png";
background.addCloud(cloud);
for (var i = 0; i < background.allClouds.length; i++){
var selectedCloud = background.allClouds[i];
for (var j = 0; j < selectedCloud.maxNumberofPixels; j++){
var pixel = cloud.createPixel(); // TODO: cloud shall not define pixel.
//new Pixel(2, 4, getRandomLocationWithinParent(selectedCloud), new Vector2d(0,5), new Vector2d(0,0), new Color(0,0,128,1));
cloud.addPixel(pixel);
}
}
/*
* Input listeners
*/
document.addEventListener("mousemove", function (evt) {
mousePosition = getMousePos(canvas, evt);
}, false);
document.addEventListener("mousedown", function (evt){
console.log(mousePosition);
for(var i = 0; i < background.allClouds.length; i++)
if(background.allClouds[i].hover(mousePosition)) {
background.allClouds[i].isClicked = true;
background.allClouds[i].clickLocalPosition = new Vector2d(mousePosition.x, mousePosition.y);
background.allClouds[i].clickLocalPosition.sub(background.allClouds[i].location);
}
}, false)
document.addEventListener("mouseup", function (evt){
for(var i = 0; i < background.allClouds.length; i++)
if(background.allClouds[i].hover(mousePosition))
background.allClouds[i].isClicked = false;
}, false)
setInterval(updateBackground, 20);
function updateBackground() {
// paint background color.
ctx.fillStyle = background.color.getColorString();
ctx.fillRect(0,0,background.width, background.height);
// paint clouds
for(var i = 0; i < background.allClouds.length; i++){
var selectedCloud = background.allClouds[i];
//ctx.fillStyle = selectedCloud.color.getColorString();
//ctx.fillRect(0, 0, selectedCloud.width, selectedCloud.height); rectangle view of cloud.
// paint rain
var deadPixelContainer = [];
for (var j = 0; j < selectedCloud.allPixels.length; j++){
var selectedPixel = selectedCloud.allPixels[j];
ctx.fillStyle = selectedPixel.color.getColorString();
ctx.save();
ctx.translate(selectedPixel.location.x, selectedPixel.location.y);
ctx.fillRect(-selectedPixel.width / 2, -selectedPixel.height / 2, selectedPixel.width, selectedPixel.height);
ctx.restore();
if(!selectedPixel.alive){
deadPixelContainer.push(selectedPixel);
continue;
}
selectedPixel.update();
selectedPixel.checkEdges(background);
}
if(deadPixelContainer.length > 0){
selectedCloud.removePixels(deadPixelContainer);
}
ctx.save();
ctx.translate(selectedCloud.location.x, selectedCloud.location.y);
ctx.drawImage(img,0,0,img.width,img.height,-25, -10,350,100);
ctx.restore();
cloud.update(mousePosition);
}
}
// TODO: Create object for mouse
function getMousePos(canvas, evt) {
var rect = canvas.getBoundingClientRect();
return new Vector2d(evt.clientX - rect.left, evt.clientY - rect.top);
}
});
function Cloud(background, width, height, location, startNumberOfPixels, maxNumberofPixels){
this.width = width;
this.height = height;
this.location = location;
this.allPixels = [];
this.maxNumberofPixels = maxNumberofPixels;
this.color = new Color(255,255,255,0.5);
this.isClicked = false;
this.rainStrength = 5; // how often cloud spawns new pixels per update cycle.
this.addPixel = function(pixel){
if(this.allPixels.length <= startNumberOfPixels)
this.allPixels.push(pixel);
}
this.update = function(mousePosition){
// make cloud draggable
if(this.isClicked){
this.location.x = mousePosition.x - this.clickLocalPosition.x;
this.location.y = mousePosition.y - this.clickLocalPosition.y;
}
// add more pixels overtime.
if(this.allPixels.length <= this.maxNumberofPixels)
for(var i = 0; i < this.rainStrength; i++)
this.allPixels.push(this.createPixel());
}
this.hover = function(mousePosition){
if(mousePosition.x > this.location.x
&& mousePosition.x < this.location.x + this.width
&& mousePosition.y > this.location.y
&& mousePosition.y < this.location.y + this.height)
return true;
return false;
}
this.createPixel = function(){
return new Pixel(2, 4, this.getRandomLocation(), new Vector2d(0,7), new Vector2d(0,0.05), new Color(0,0,128,1));
}
this.removePixels = function(deadPixelContainer){
for(var i = 0; i < deadPixelContainer.length; i++){
try{
var pixelContainer = this.allPixels.slice();
pixelContainer.splice(this.allPixels.findIndex(v => v === deadPixelContainer[i]), 1).slice();
this.allPixels = pixelContainer.slice();
}catch(e){
console.log(e);
}
}
}
this.getRandomLocation = function(){
var minWidth = this.location.x;
var maxWidth = this.location.x + this.width;
var minHeight = this.location.y + this.height/2; // don't count upper part of cloud. Rain forms at the bottom.
var maxHeight = this.location.y + this.height;
var randomWidthLocation = Math.random() * (maxWidth - minWidth + 1)+minWidth;
var randomHeightLocation = Math.random() * (maxHeight - minHeight + 1) + minHeight;
return new Vector2d(randomWidthLocation, randomHeightLocation);
}
}
function Background(ctx, width, height, color){
this.width = width;
this.height = height;
this.color = color; //"#191919"
this.isPaused = false;
this.allPixels = []; // might need to be removed.
this.allClouds = [];
this.pixelCount = 150;
this.addCloud = function(cloud){
this.allClouds.push(cloud);
};
this.refreshCanvas = function(){
this.width = $(window).width();
this.height = $(window).height();
};
this.addPixelOn = function(pixelWidht, pixelHeight, location, velocity, acceleration, color) { // might need to be removed.
var pixel = new Pixel(pixelWidht, pixelHeight, location, velocity, acceleration, color);
this.allPixels.push(pixel);
};
this.addPixel = function(pixelWidht, pixelHeight, velocity, acceleration, color) { // might need to be removed.
var location = new Vector2d(Math.random() * this.width, Math.random() * this.height);
this.addPixelOn(pixelWidht, pixelHeight, location, velocity, acceleration, color);
};
}
function Pixel(widht, height, location, velocity, acceleration, color) {
this.height = height;
this.width = widht;
this.color = color; //"#00CC33"
this.location = location;
this.velocity = velocity;
this.acceleration = acceleration;
this.alive = true;
this.update = function () {
this.velocity.add(this.acceleration);
//this.velocity.limit(topspeed);
this.location.add(this.velocity);
};
this.checkEdges = function (background) {
if (this.location.y > background.height) {
this.alive = false;
}
};
this.setColor = function(color){
this.color = color;
};
this.setHeight = function(height){
this.height = height;
};
this.setWidth = function(width){
this.width = width;
}
}
function Color(r,g,b,o){
this.red = r;
this.green = g;
this.blue = b;
this.opacity = o;
this.getColorString = function(){
return "rgba("+this.red+","+this.green+","+this.blue+","+this.opacity+")";
}
}
function Vector2d(x, y) {
this.x = x;
this.y = y;
this.add = function (vector2d) {
this.x += vector2d.x;
this.y += vector2d.y;
};
this.sub = function (vector2d) {
this.x -= vector2d.x;
this.y -= vector2d.y;
};
this.mult = function (mult) {
this.x *= mult;
this.y *= mult;
};
this.div = function (div) {
this.x /= div;
this.y /= div;
};
this.mag = function () {
return Math.sqrt(this.x * this.x, this.y * this.y);
};
this.norm = function () {
var m = this.mag();
if (m !== 0) {
this.div(m);
}
}
}
#background-canvas {
position: fixed;
width: 100%;
height: 100%
background-color:red;
top:0;
left:0;
}
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<canvas id="background-canvas" />
</body>
</html>
Here is a site, in it a canvas (airplane), which lags when scrolling, appear artifacts, and in different ways, depending on what you scroll - with the mouse wheel or scrollbar. If you comment out parallax or video at the beginning, nothing changes. During the scrolling of calls to the house does not happen. Lags either from behind the airplane script, or because of a clearRect. How can I optimize and get rid of artifacts? The code on the codepen (it works fine)
var scrolled;
var positionsArr = [];
var commonHeight = 0;
var canvas = document.querySelector('#canvas');
var canvasB = document.querySelector('#canvasback');
var ctx = canvas.getContext('2d');
var ctxB = canvasB.getContext('2d');
var centerX, centerY, radius, pointsOffset, radiusRatio, centerXRatio,
firstPoint, lastPoint, jet, blocksPosition, jetPositionY, jetTop, tabletOffset, headerHeight, canvasClearWidth;
var wWidth, mediaMobile, mediaTablet, mediaDesktop1, mediaDesktop2, mediaDesktop3;
jet = new Image();
jet.src = 'http://silencer.website/alkor/images/jet.png';
jet.onload = function () {
adaptive();
}
$(window).on('resize', function () {
adaptive();
});
function adaptive() {
mediaMobile = mediaTablet = mediaDesktop1 = mediaDesktop2 = mediaDesktop3 = false;
wWidth = $(window).width();
// Параметры для дуги по умолчанию
tabletOffset = 0;
radiusRatio = .95;
centerXRatio = 1.25;
// Параметры для дуги на разных разрешениях (перезаписывают параметры по умолчанию)
if (wWidth < 768) {
mediaMobile = true;
}
if (wWidth >= 768 && wWidth < 1024) {
mediaTablet = true;
tabletOffset = 120;
}
if (wWidth >= 1024 && wWidth < 1280) {
mediaDesktop1 = true;
tabletOffset = -40;
radiusRatio = 1.1;
centerXRatio = 1.03;
}
if (wWidth >= 1280 && wWidth < 1440) {
mediaDesktop2 = true;
tabletOffset = -20;
}
if (wWidth >= 1440) {
mediaDesktop3 = true;
tabletOffset = -20;
}
if (!mediaMobile) {
setTimeout(function () {
doCanvas();
}, 500);
} else {
ctx.clearRect(0, 0, canvas.width, canvas.height);
$(window).off('scroll', onScroll);
}
}
function doCanvas() {
$(window).on('scroll', onScroll);
var marginBottom = 120;
commonHeight = 0;
$('.history__item').each(function () {
commonHeight = commonHeight + $(this).height() + marginBottom;
});
commonHeight = commonHeight - marginBottom;
canvasWidth = $('.history').width() * .3;
canvasHeight = $('.history__blocks').height();
canvas.width = canvasWidth;
canvas.height = canvasHeight;
canvasB.width = canvas.width;
canvasB.height = canvas.height;
offsetLeft = $('.history__blocks')[0].offsetLeft;
$('#canvas, #canvasback').css('marginLeft', -offsetLeft);
radius = commonHeight * radiusRatio;
centerX = -commonHeight / centerXRatio + offsetLeft + tabletOffset;
centerY = commonHeight / 2;
pointsOffset = 100;
canvasClearWidth = centerX + radius + 110;
blocksPosition = $('.history__blocks')[0].offsetTop;
jetPositionY = $('.history')[0].offsetTop;
headerHeight = $('.history__title').height();
jetTop = $(window).height() / 2;
jetOnScroll = jetTop - headerHeight - jetPositionY;
positionsArr = [];
lastIndex = $('.history__item').length - 1;
darkened = $('.history__item');
for (var i = 0; i < $('.history__item').length; i++) {
var position = $('.history__item').eq(i)[0].offsetTop - blocksPosition + pointsOffset;
positionsArr.push(position);
if (i == 0) {
firstPoint = position;
}
if (i == $('.history__item').length - 1) {
lastPoint = position;
}
}
draw();
drawBackground();
setTimeout(function () {
if (mediaTablet) {
jetPositionLine(firstPoint);
} else {
jetPosition(firstPoint);
}
}, 100);
}
function drawBackground() {
if (mediaTablet) {
drawLine();
} else {
drawArc();
}
}
function draw(currentY) {
for (var i = 0; i < positionsArr.length; i++) {
addPoint(positionsArr[i], currentY, i);
}
}
function drawArc() {
var firstPointRad = Math.asin((centerY - firstPoint) / radius);
var lastPointRad = Math.asin((centerY - lastPoint) / radius);
ctxB.beginPath();
ctxB.lineWidth = 3;
ctxB.save();
ctxB.arc(centerX, centerY, radius, 1.5, lastPointRad, true);
ctxB.strokeStyle = '#99daf0';
ctxB.setLineDash([8, 5]);
ctxB.lineDashOffset = 1;
ctxB.globalCompositeOperation = 'destination-over';
ctxB.stroke();
ctxB.restore();
}
function drawLine() {
ctxB.beginPath();
ctxB.lineWidth = 3;
ctxB.save();
ctxB.lineTo(tabletOffset, firstPoint);
ctxB.lineTo(tabletOffset, lastPoint);
ctxB.strokeStyle = '#99daf0';
ctxB.setLineDash([8, 5]);
ctxB.lineDashOffset = 1;
ctxB.globalCompositeOperation = 'destination-over';
ctxB.stroke();
ctxB.restore();
}
function addPoint(y, currentY, i) {
if (mediaTablet) {
var currentX = tabletOffset;
} else {
var angle = Math.asin((centerY - y) / radius);
var currentX = centerX + radius * (Math.cos(angle));
}
ctx.beginPath();
ctx.arc(currentX, y, 8, 0, 2 * Math.PI, false);
ctx.lineWidth = 3;
ctx.fillStyle = '#00a3da';
ctx.globalCompositeOperation = 'source-over';
if (currentY + 10 >= y) {
ctx.strokeStyle = '#fff';
darkened.eq(i).removeClass('darkened');
} else {
ctx.strokeStyle = '#99daf0';
darkened.eq(i).addClass('darkened');
}
ctx.fill();
ctx.stroke();
}
function jetPosition(y) {
var angle = Math.asin((centerY - y) / radius);
var currentX = centerX + radius * (Math.cos(angle) - 1);
var firstPointRad = Math.asin((centerY - firstPoint) / radius);
// if (toUp) { // Самолетик вверх-вниз
var jetAngle = Math.acos((centerY - y) / radius);
// } else {
// var jetAngle = Math.acos((centerY - y) / radius) + Math.PI;
// }
ctx.beginPath();
ctx.arc(centerX, centerY, radius, -angle, -firstPointRad, true);
ctx.globalCompositeOperation = 'source-over';
ctx.lineWidth = 3;
ctx.strokeStyle = '#fff';
ctx.stroke();
draw(y);
ctx.save();
ctx.translate(currentX + radius, y)
ctx.rotate(jetAngle - 1.6);
ctx.globalCompositeOperation = 'source-over';
ctx.drawImage(jet, -106, -80, 212, 160);
ctx.restore();
}
function jetPositionLine(y) {
ctx.beginPath();
ctx.lineTo(tabletOffset, firstPoint);
ctx.lineTo(tabletOffset, y);
ctx.lineWidth = 3;
ctx.strokeStyle = '#fff';
ctx.stroke();
draw(y);
ctx.beginPath();
ctx.save();
ctx.globalCompositeOperation = 'source-over';
ctx.drawImage(jet, tabletOffset - 106, y - 80, 212, 160);
ctx.restore();
}
function onScroll() {
requestAnimationFrame(scrollCanvas);
};
function scrollCanvas() {
var prevScroll = scrolled;
scrolled = window.pageYOffset;
toUp = prevScroll < scrolled;
var positionY = scrolled + jetOnScroll;
if (positionY >= firstPoint) {
if (positionY <= lastPoint) {
ctx.clearRect(0, 0, canvasClearWidth, canvasHeight);
if (mediaTablet) {
jetPositionLine(positionY);
} else {
jetPosition(positionY);
}
} else {
$('.history__item').eq(lastIndex).removeClass('darkened');
}
}
if (!mediaMobile && !mediaTablet) {
parallaxScroll();
}
}
I am working on a college project that requires me to build a 2D game in javascript. A problem that I'm having at the moment is that it cannot read the 'addEventListener'. This error has caused my game to not work completely.
document.getElementById('restart').addEventListener('click', startGame);
Here is the full code that I have used. The error is down the very bottom.
(function()
{
//Define variables
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
var player, score, stop, ticker;
var ground = [], water = [], enemies = [], environment = [];
//Platform variables
var platformHeight, platformLength, gapLength;
var platformWidth = 32;
var platformBase = canvas.height - platformWidth;
var platformSpacer = 64;
//Randomly generates a number
function random(low, high)
{
return Math.floor(Math.random() * (high - low + 1) + low);
}
//Bounds a number
function bound(num, low, high)
{
return Math.max(Math.min(num, high), low);
}
//Loads all of the assets
var assetLoader = (function()
{
this.imgs = {
'bg' : 'Images/bg.png',
'sky' : 'Images/sky.png',
'backdrop' : 'Images/backdrop.png',
'backdrop2' : 'Images/backdrop_ground.png',
'grass' : 'Images/grass.png',
'avatar_normal' : 'Images/normal_walk.png',
'water' : 'imgs/water.png',
'grass1' : 'imgs/grassMid1.png',
'grass2' : 'imgs/grassMid2.png',
'bridge' : 'imgs/bridge.png',
'plant' : 'imgs/plant.png',
'bush1' : 'imgs/bush1.png',
'bush2' : 'imgs/bush2.png',
'cliff' : 'imgs/grassCliffRight.png',
'spikes' : 'imgs/spikes.png',
'box' : 'imgs/boxCoin.png',
'slime' : 'imgs/slime.png'
};
var assetsLoaded = 0; //How many assets have been loaded
var numImgs = Object.keys(this.imgs).length; //Total number of image assets
this.totalAssest = numImgs; //Total number of assets
function assetLoaded(dic, name)
{
if(this[dic][name].status !== 'loading')
{
return;
}
this[dic][name].status = 'loaded';
assetsLoaded++;
if(assetsLoaded === this.totalAssest && typeof this.finished === 'function')
{
this.finished();
}
}
this.downloadAll = function()
{
var _this = this;
var src;
for (var img in this.imgs)
{
if (this.imgs.hasOwnProperty(img))
{
src = this.imgs[img];
(function(_this, img)
{
_this.imgs[img] = new Image();
_this.imgs[img].status = 'loading';
_this.imgs[img].name = img;
_this.imgs[img].onload = function() {assetLoaded.call(_this, 'imgs', img)};
_this.imgs[img].src = src;
})(_this, img);
}
}
}
return{
imgs: this.imgs,
totalAssest: this.totalAssest,
downloadAll: this.downloadAll
};
})();
assetLoader.finished = function()
{
startGame();
}
function SpriteSheet(path, frameWidth, frameHeight)
{
this.image = new Image();
this.frameWidth = frameWidth;
this.frameHeight = frameHeight;
var self = this;
this.image.onload = function()
{
self.framesPerRow = Math.floor(self.image.width / self.frameWidth);
};
this.image.src = path;
}
function Animation(spritesheet, frameSpeed, startFrame, endFrame)
{
var animationSequence = [];
var currentFrame = 0;
var counter = 0;
for (var frameNumber = startFrame; frameNumber <= endFrame; frameNumber++)
{
animationSequence.push(frameNumber);
}
this.update = function()
{
if (counter == (frameSpeed - 1))
{
currentFrame = (currentFrame + 1) % animationSequence.length;
}
counter = (counter + 1) % frameSpeed;
};
this.draw = function(x, y)
{
var row = Math.floor(animationSequence[currentFrame] / spritesheet.framesPerRow);
var col = Math.floor(animationSequence[currentFrame] % spritesheet.framesPerRow);
ctx.drawImage
(
spritesheet.image,
col * spritesheet.frameWidth, row * spritesheet.frameHeight,
spritesheet.frameWidth, spritesheet.frameHeight,
x, y,
spritesheet.frameWidth, spritesheet.frameHeight);
};
}
var background = (function()
{
var sky = {};
var backdrop = {};
var backdrop2 = {};
this.draw = function()
{
ctx.drawImage(assetLoader.imgs.bg, 0, 0);
sky.x -= sky.speed;
backdrop.x -= backdrop.speed;
backdrop2.x -= backdrop2.speed;
ctx.drawImage(assetLoader.imgs.sky, sky.x, sky.y);
ctx.drawImage(assetLoader.imgs.sky, sky.x + canvas.width, sky.y);
ctx.drawImage(assetLoader.imgs.backdrop, backdrop.x, backdrop.y);
ctx.drawImage(assetLoader.imgs.backdrop, backdrop.x + canvas.width, backdrop.y);
ctx.drawImage(assetLoader.imgs.backdrop2, backdrop2.x, backdrop2.y);
ctx.drawImage(assetLoader.imgs.backdrop2, backdrop2.x + canvas.width, backdrop2.y);
if (sky.x + assetLoader.imgs.sky.width <= 0)
{
sky.x = 0;
}
if (backdrop.x + assetLoader.imgs.backdrop.width <= 0)
{
backdrop.x = 0;
}
if (backdrop2.x + assetLoader.imgs.backdrop2.width <= 0)
{
backdrop2.x = 0;
}
};
this.reset = function()
{
sky.x = 0;
sky.y = 0;
sky.speed = 0.2;
backdrop.x = 0;
backdrop.y = 0;
backdrop.speed = 0.4;
backdrop2.x = 0;
backdrop2.y = 0;
backdrop2.speed = 0.6;
}
return{
draw: this.draw,
reset: this.reset
};
})();
//A vector for 2D space
function Vector(x, y, dx, dy)
{
// position
this.x = x || 0;
this.y = y || 0;
// direction
this.dx = dx || 0;
this.dy = dy || 0;
}
//Advances the vector's position
Vector.prototype.advance = function()
{
this.x += this.dx;
this.y += this.dy;
};
//Gets the minimum distance between two vectors
Vector.prototype.minDist = function(vec)
{
var minDist = Infinity;
var max = Math.max(Math.abs(this.dx), Math.abs(this.dy),Math.abs(vec.dx), Math.abs(vec.dy));
var slice = 1 / max;
var x, y, distSquared;
// get the middle of each vector
var vec1 = {}, vec2 = {};
vec1.x = this.x + this.width/2;
vec1.y = this.y + this.height/2;
vec2.x = vec.x + vec.width/2;
vec2.y = vec.y + vec.height/2;
for(var percent = 0; percent < 1; percent += slice)
{
x = (vec1.x + this.dx * percent) - (vec2.x + vec.dx * percent);
y = (vec1.y + this.dy * percent) - (vec2.y + vec.dy * percent);
distSquared = x * x + y * y;
minDist = Math.min(minDist, distSquared);
}
return Math.sqrt(minDist);
};
//The player object
var player = (function(player)
{
//Player properties
player.width = 60;
player.height = 96;
player.speed = 6;
//Jumping
player.gravity = 1;
player.dy = 0;
player.jumpDy = -10;
player.isFalling = false;
player.isJumping = false;
//Spritesheets
player.sheet = new SpriteSheet('Images/normal_walk.png', player.width, player.height);
player.walkAnim = new Animation(player.sheet, 4, 0, 15);
player.jumpAnim = new Animation(player.sheet, 4, 15, 15);
player.fallAnim = new Animation(player.sheet, 4, 11, 11);
player.anim = player.walkAnim;
Vector.call(player, 0, 0, 0, player.dy);
var jumpCounter = 0;
player.update = function()
{
//Jump if not currently jumping or falling
if(KEY_STATUS.space && player.dy === 0 && !player.isJumping)
{
player.isJumping = true;
player.dy = player.jumpDy;
jumpCounter = 12;
}
//Jump higher if the spacebar is continually pressed
if(KEY_STATUS.space && jumpCounter)
{
player.dy = player.jumpDy;
}
jumpCounter = Math.max(jumpCounter - 1, 0);
this.advance();
//Gravity
if(player.isFalling || player.isJumping)
{
player.dy += player.gravity;
}
//Falling Animation
if(player.dy > 0)
{
player.anim = player.fallAnim;
}
// change animation is jumping
else if(player.dy < 0)
{
player.anim = player.jumpAnim;
}
else
{
player.anim = player.walkAnim;
}
player.anim.update();
};
//Draw the player's current position
player.draw = function()
{
player.anim.draw(player.x, player.y);
};
//Resets the player's position
player.reset = function()
{
player.x = 64;
player.y = 250;
};
return player;
})(Object.create(Vector.prototype));
//Sprites
function Sprite(x, y, type)
{
this.x = x;
this.y = y;
this.width = platformWidth;
this.height = platformWidth;
this.type = type;
Vector.call(this, x, y, 0, 0);
//Updating the sprites
this.update = function()
{
this.dx = -player.speed;
this.advancer();
}
//Drawing the sprites
this.draw = function()
{
ctx.save();
ctx.translate(0.5, 0.5);
ctx.drawImage(assetLoader.imgs[this.type], this.x, this.y);
ctx.restore();
}
}
Sprite.prototype = Object.create(Vector.prototype);
//Platforms
function getType()
{
var type;
switch(platformHeight)
{
case 0:
case 1:
type = Math.random() > 0.5 ? 'grass1' : 'grass2';
break;
case 2:
type = 'grass';
break;
case 3:
type = 'bridge';
break;
case 4:
type = 'box';
break;
}
if (platformLength === 1 && platformHeight < 3 && rand(0, 3) === 0)
{
type = 'cliff';
}
return type;
}
//Update and draw all ground positions
function updateGround()
{
//Animate ground
player.isFalling = true;
for(var i = 0; i < ground.length; i++)
{
ground[i].update();
ground[i].draw();
//Stop the player going through the platforms when landing
var angle;
if(player.minDist(ground[i]) <= player.height/2 + platformWidth/2 && (angle = Math.atan2(player.y - ground[i].y, player.x - ground[i].x) * 180/Math.PI) > -130 &&angle < -50)
{
player.isJumping = false;
player.isFalling = false;
player.y = ground[i].y - player.height + 5;
player.dy = 0;
}
}
//Remove the ground that has gone off screen
if(ground[0] && ground[0].x < -platformWidth)
{
ground.splice(0, 1);
}
}
//Update and draw all water positions
function updateWater()
{
//Animate water
for(var i = 0; i < water.length; i++)
{
water[i].update();
water[i].draw();
}
//Remove water that has gone off screen
if (water[0] && water[0].x < -platformWidth)
{
var w = water.splice(0, 1)[0];
w.x = water[water.length-1].x + platformWidth;
water.push(w);
}
}
//Update and draw all environment positions
function updateEnvironment()
{
//Animate environment
for(var i = 0; i < environment.length; i++)
{
environment[i].update();
environment[i].draw();
}
//R emove environment that have gone off screen
if(environment[0] && environment[0].x < -platformWidth)
{
environment.splice(0, 1);
}
}
//Update and draw all enemies position. Also check for collision against the player.
function updateEnemies()
{
//Animate enemies
for(var i = 0; i < enemies.length; i++)
{
enemies[i].update();
enemies[i].draw();
//Player ran into enemy
if(player.minDist(enemies[i]) <= player.width - platformWidth/2)
{
gameOver();
}
}
//Remove enemies that have gone off screen
if(enemies[0] && enemies[0].x < -platformWidth)
{
enemies.splice(0, 1);
}
}
//Update and draw the players position
function updatePlayer()
{
player.update();
player.draw();
//Game over
if(player.y + player.height >= canvas.height)
{
gameOver();
}
}
//Spawn new sprites off screen
function spawnSprites()
{
//Increase score
score++;
//First create a gap
if(gapLength > 0)
{
gapLength--;
}
//Then create the ground
else if(platformLength > 0)
{
var type = getType();
ground.push(new Sprite(
canvas.width + platformWidth % player.speed,
platformBase - platformHeight * platformSpacer,
type
));
platformLength--;
//Add random environment sprites
spawnEnvironmentSprites();
//Add random enemies
spawnEnemySprites();
}
//Start over
else
{
//Increase gap length every speed increase of 4
gapLength = rand(player.speed - 2, player.speed);
// only allow a ground to increase by 1
platformHeight = bound(rand(0, platformHeight + rand(0, 2)), 0, 4);
platformLength = rand(Math.floor(player.speed/2), player.speed * 4);
}
}
//Spawn new environment sprites off screen
function spawnEnvironmentSprites()
{
if(score > 40 && rand(0, 20) === 0 && platformHeight < 3)
{
if (Math.random() > 0.5)
{
environment.push(new Sprite(canvas.width + platformWidth % player.speed, platformBase - platformHeight * platformSpacer - platformWidth, 'plant'));
}
else if(platformLength > 2)
{
environment.push(new Sprite(canvas.width + platformWidth % player.speed, platformBase - platformHeight * platformSpacer - platformWidth, 'bush1'));
environment.push(new Sprite(canvas.width + platformWidth % player.speed + platformWidth, platformBase - platformHeight * platformSpacer - platformWidth, 'bush2'));
}
}
}
//Spawn new enemy sprites off screen
function spawnEnemySprites()
{
if(score > 100 && Math.random() > 0.96 && enemies.length < 3 && platformLength > 5 && (enemies.length ? canvas.width - enemies[enemies.length-1].x >= platformWidth * 3 || canvas.width - enemies[enemies.length-1].x < platformWidth : true))
{
enemies.push(new Sprite(canvas.width + platformWidth % player.speed, platformBase - platformHeight * platformSpacer - platformWidth, Math.random() > 0.5 ? 'spikes' : 'slime'));
}
}
//Game Loop
function animate()
{
if(!stop)
{
requestAnimFrame(animate);
ctx.clearRect(0, 0, canvas.width, canvas.height);
background.draw();
//Update entities
updateWater();
updateEnvironment();
updatePlayer();
updateGround();
updateEnemies();
//Draw the score
ctx.fillText('Score: ' + score + 'm', canvas.width - 140, 30);
//Spawn a new Sprite
if(ticker % Math.floor(platformWidth / player.speed) === 0)
{
spawnSprites();
}
//Increase player's speed only when player is jumping
if(ticker > (Math.floor(platformWidth / player.speed) * player.speed * 20) && player.dy !== 0)
{
player.speed = bound(++player.speed, 0, 15);
player.walkAnim.frameSpeed = Math.floor(platformWidth / player.speed) - 1;
//Reset ticker
ticker = 0;
//Spawn a platform to fill in gap created by increasing player speed
if(gapLength === 0)
{
var type = getType();
ground.push(new Sprite(canvas.width + platformWidth % player.speed, platformBase - platformHeight * platformSpacer, type));
platformLength--;
}
}
ticker++;
}
}
//Spacebar events
var KEY_CODES = {
32: 'space'
};
var KEY_STATUS = {};
for(var code in KEY_CODES)
{
if(KEY_CODES.hasOwnProperty(code))
{
KEY_STATUS[KEY_CODES[code]] = false;
}
}
document.onkeydown - function(e)
{
var keyCode = (e.keyCode) ? e.keyCode : e.charCode;
if(KEY_CODES[keyCode])
{
e.preventDefault();
KEY_STATUS[KEY_CODES[keyCode]] = true;
}
};
document.onkeydown - function(e)
{
var keyCode = (e.keyCode) ? e.keyCode : e.charCode;
if(KEY_CODES[keyCode])
{
e.preventDefault();
KEY_STATUS[KEY_CODES[keyCode]] = false;
}
};
//Request Animation Polyfill
var requestAnimFrame = (function()
{
return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame || function(callback, element)
{
window.setTimeout(callback, 1000 / 60);
};
})();
//Start the game and resets all variables and entities, spawn ground and water.
function startGame()
{
document.getElementById('game-over').style.display = 'none';
ground = [];
water = [];
environment = [];
enemies = [];
player.reset();
ticker = 0;
stop = false;
score = 0;
platformHeight = 2;
platformLength = 15;
gapLength = 0;
ctx.font = '16px arial, sans-serif';
for (var i = 0; i < 30; i++)
{
ground.push(new Sprite(i * (platformWidth-3), platformBase - platformHeight * platformSpacer, 'grass'));
}
for (i = 0; i < canvas.width / 32 + 2; i++)
{
water.push(new Sprite(i * platformWidth, platformBase, 'water'));
}
background.reset();
animate();
}
//End the game and restart
function gameOver()
{
stop = true;
document.getElementById('game-over').style.display = 'block';
}
document.getElementById('restart').addEventListener('click', startGame);
assetLoader.downloadAll();
})();
The Problem
I am creating a game where you have to move away from or dodge projectiles coming towards you, I have enabled the user to move the image they are controlling but at the moment the user can place the image anywhere on the canvas.
The Question
How can I only allow the user to move along designated part of the canvas and only along the X axis? for example:
Here is my game, "working progress":
The user is in control of the ship, they should only be able to move left or right like this for example:
The Code
<script>
var game = create_game();
game.init();
//music
var snd = new Audio("menu.mp3");
snd.play();
document.getElementById('mute').addEventListener('click', function (evt) {
if ( snd.muted ) {
snd.muted = false
evt.target.innerHTML = 'mute'
}
else {
snd.muted = true
evt.target.innerHTML = 'unmute'
}
})
function create_game() {
debugger;
var level = 1;
var projectiles_per_level = 1;
var min_speed_per_level = 1;
var max_speed_per_level = 2;
var last_projectile_time = 0;
var next_projectile_time = 0;
var width = 600;
var height = 500;
var delay = 1000;
var item_width = 30;
var item_height = 30;
var total_projectiles = 0;
var projectile_img = new Image();
var projectile_w = 30;
var projectile_h = 30;
var player_img = new Image();
var c, ctx;
var projectiles = [];
var player = {
x: 200,
y: 400,
score: 0
};
function init() {
projectile_img.src = "apple.png";
player_img.src = "basket.png";
level = 1;
total_projectiles = 0;
projectiles = [];
c = document.getElementById("c");
ctx = c.getContext("2d");
ctx.fillStyle = "#ff6600";
ctx.fillRect(0, 0, 500, 600);
c.addEventListener("mousemove", function (e) {
//moving over the canvas.
var bounding_box = c.getBoundingClientRect();
player.x = (e.clientX - bounding_box.left) * (c.width / bounding_box.width) - player_img.width / 2;
player.y = (e.clientY - bounding_box.top) * (c.height / bounding_box.height) - player_img.height / 2;
}, false);
setupProjectiles();
requestAnimationFrame(tick);
}
function setupProjectiles() {
var max_projectiles = level * projectiles_per_level;
while (projectiles.length < max_projectiles) {
initProjectile(projectiles.length);
}
}
function initProjectile(index) {
var max_speed = max_speed_per_level * level;
var min_speed = min_speed_per_level * level;
projectiles[index] = {
x: Math.round(Math.random() * (width - 2 * projectile_w)) + projectile_w,
y: -projectile_h,
v: Math.round(Math.random() * (max_speed - min_speed)) + min_speed,
delay: Date.now() + Math.random() * delay
}
total_projectiles++;
}
function collision(projectile) {
if (projectile.y + projectile_img.height < player.y + 74) {
return false;
}
if (projectile.y > player.y + 74) {
return false;
}
if (projectile.x + projectile_img.width < player.x + 177) {
return false;
}
if (projectile.x > player.x + 177) {
return false;
}
return true;
}
function maybeIncreaseDifficulty() {
level = Math.max(1, Math.ceil(player.score / 10));
setupProjectiles();
}
function tick() {
var i;
var projectile;
var dateNow = Date.now();
c.width = c.width;
for (i = 0; i < projectiles.length; i++) {
projectile = projectiles[i];
if (dateNow > projectile.delay) {
projectile.y += projectile.v;
if (collision(projectile)) {
initProjectile(i);
player.score++;
} else if (projectile.y > height) {
initProjectile(i);
} else {
ctx.drawImage(projectile_img, projectile.x, projectile.y);
}
}
}
ctx.font = "bold 24px sans-serif";
ctx.fillStyle = "#ff6600";
ctx.fillText(player.score, c.width - 50, 50);
ctx.fillText("Level: " + level, 20, 50);
ctx.drawImage(player_img, player.x, player.y);
maybeIncreaseDifficulty();
requestAnimationFrame(tick);
}
return {
init: init
};
}
</script>
JSFiddle (Broken)
https://jsfiddle.net/3oc4jsf6/10/
If your ship is tied to mouse movement, and you want to only allow movement across the X-axis you can simply avoid changing its .y property in your mousemove listener.
Remove this line:
player.y = (e.clientY - bounding_box.top) * (c.height / bounding_box.height) - player_img.height / 2;