Drawing repeating image behind Divs - javascript

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

Related

What is the right offset for better drag effect?

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>

Trying to remove quadtree from javascript game

I got an agar.io clone from online and I am trying to remove the Quadtree in the corner (acts as a map) completely! I try to delete everything associating with the quadtree but i end up with a gray screen. Could someone please remove the map from the top right corner for me or tell me which lines to remove?
Here is my HTML:
<div id="viewport">
<canvas id="canvas1"></canvas>
<canvas id="canvas2"></canvas>
<canvas id="canvas3" width="250px" height="250px"></canvas>
</div>
Here is my javascript:
var MouseHandler = (function() {
var x = 0;
var y = 0;
var mouseIn = false;
var init = function(eventSrc) {
eventSrc.addEventListener('mousemove', onMouseMove);
eventSrc.addEventListener('mouseout', onMouseOut);
eventSrc.addEventListener('mouseover', onMouseOver);
};
var onMouseOut = function() {
mouseIn = false;
};
var onMouseOver = function() {
mouseIn = true;
};
var onMouseMove = function(e) {
x = e.clientX;
y = e.clientY;
};
var getPos = function() {
return {
x: x,
y: y
};
};
var isMouseIn = function() {
return mouseIn;
};
return {
init: init,
getPos: getPos,
isMouseIn: isMouseIn
};
}());
Quadtree.MAX_OBJECTS = 5;
Quadtree.MAX_LEVEL = 5;
function Quadtree(lvl, bnds) {
var level = lvl;
var bounds = bnds;
var objects = [];
var nodes = [];
var xMiddle = bounds.x + (bounds.width / 2);
var yMiddle = bounds.y + (bounds.height / 2);
var clear = function() {
objects = [];
nodes = [];
};
var split = function() {
nodes[0] = new Quadtree(level+1, {x: xMiddle, y: bounds.y , width: bounds.width/2, height: bounds.height/2});
nodes[1] = new Quadtree(level+1, {x: bounds.x, y: bounds.y, width: bounds.width/2, height: bounds.height/2});
nodes[2] = new Quadtree(level+1, {x: bounds.x, y: yMiddle, width: bounds.width/2, height: bounds.height/2});
nodes[3] = new Quadtree(level+1, {x: xMiddle, y: yMiddle, width: bounds.width/2, height: bounds.height/2});
};
var getIndex = function(rec) {
var top = (rec.y > bounds.y && (rec.y+rec.height) < yMiddle);
var bottom = (rec.y > yMiddle && (rec.y+rec.height) < (bounds.y+bounds.height));
if(rec.x > bounds.x && (rec.x+rec.width) < xMiddle) {
if(top) {
return 1;
} else if(bottom) {//LEFT
return 2;
}
} else if(rec.x > xMiddle && (rec.x+rec.width) < (bounds.x+bounds.width)) {
if(top) {
return 0;
} else if(bottom) {//RIGHT
return 3;
}
}
return -1;
};
var insert = function(ent) {
var rec = ent.getBounds();
var index = getIndex(rec);
var len = 0;
var i = 0;
if(nodes[0] && index !== -1) {
nodes[index].insert(ent);
return;
}
objects.push(ent);
if(objects.length > Quadtree.MAX_OBJECTS && level < Quadtree.MAX_LEVEL) {
if(!nodes[0]) {
split();
}
len = objects.length;
while(i < objects.length) {
index = getIndex(objects[i].getBounds());
if(index !== -1) {
nodes[index].insert(objects[i]);
objects.splice(i, 1);
} else {
i += 1;
}
}
}
};
var retrieve = function (list, ent) {
var rec1 = bounds;
var rec2 = ent.getBounds();
if(rec2.x < (rec1.x+rec1.width) && (rec2.x+rec2.width) > rec1.x &&
rec2.y < (rec1.y+rec1.height) && (rec2.y+rec2.height) > rec1.y) {
for(var o in objects) {
if(objects[o] !== ent) {
list.push(objects[o]);
}
}
if(nodes.length) {
nodes[0].retrieve(list, ent);
nodes[1].retrieve(list, ent);
nodes[2].retrieve(list, ent);
nodes[3].retrieve(list, ent);
}
}
return list;
};
var drawTree = function(ctx) {
draw(ctx);
if(nodes[0]) {
nodes[0].drawTree(ctx);
nodes[1].drawTree(ctx);
nodes[2].drawTree(ctx);
nodes[3].drawTree(ctx);
}
};
var draw = function(ctx) {
var entAttr = null
ctx.strokeStyle = 'black';
ctx.lineWidth = 1;
ctx.strokeRect(bounds.x/20, bounds.y/20, bounds.width/20, bounds.height/20);
ctx.fillStyle = 'gray';
for(o in objects) {
entAttr = objects[o].getAttr();
ctx.fillRect(entAttr.x/20, entAttr.y/20, 3, 3);
}
};
var toString = function() {
return '('+bounds.x+','+bounds.y+')'+'['+bounds.width+','+bounds.height+']';
};
return {
clear: clear,
insert: insert,
retrieve: retrieve,
drawTree: drawTree,
toString: toString,
};
}
function Circle(attr) {
attr = attr || {};
var x = attr.x || 0;
var y = attr.y || 0;
var mass = attr.mass || 500;
var color = attr.color || 'white';
var borderColor = attr.borderColor || 'black';
var velX = attr.velX || 0;
var velY = attr.velY || 0;
var droplet = attr.droplet || false;
var maxVel = 80 * (80 / Math.sqrt(mass));
var radius = Math.sqrt( mass / Math.PI ); //1 unit of area === 1 uni of mass
var getAttr = function() {
return {
x: x,
y: y,
mass: mass,
radius: radius,
color: color,
velX: velX,
velY: velY,
maxVel: maxVel
};
};
var setAttr = function(attr) {
x = (attr.x !== undefined)? attr.x: x;
y = (attr.y !== undefined)? attr.y: y;
mass = (attr.mass !== undefined)? attr.mass: mass;
color = (attr.color !== undefined)? attr.color: color;
velX = (attr.velX !== undefined)? attr.velX: velX;
velY = (attr.velY !== undefined)? attr.velY: velY;
};
var incMass = function(dMass) {
mass += dMass;
maxVel = 100 * (100 / Math.sqrt(mass));
radius = Math.sqrt( mass / Math.PI );
};
var intersects = function(ent2) {
var ent2Attr = ent2.getAttr();
var dX = Math.abs(ent2Attr.x - x);
var dY = Math.abs(ent2Attr.y - y);
var totalRadius = ent2Attr.radius + radius;
return (dX < totalRadius && dY < totalRadius);
};
var draw = function(ctx, cam) {
var camSize = cam.getSize();
var rPos = cam.getRelPos(getAttr());
//if outside Cam view
if((rPos.x + radius) < 0 || (rPos.y + radius) < 0 || (rPos.x - radius) > camSize.width || (rPos.y - radius) > camSize.height) {
return;
}
ctx.fillStyle = color;
ctx.strokeStyle = borderColor;
ctx.lineWidth = 5;
ctx.beginPath();
ctx.arc(rPos.x, rPos.y, radius, 0, 2 * Math.PI, false);
ctx.fill();
ctx.stroke();
};
var update = !droplet && function(dTime) {
x += velX * dTime;
y += velY * dTime;
};
var getBounds = function() {
return {
x: x-radius,
y: y-radius,
width: radius*2,
height: radius*2,
};
};
return {
getBounds: getBounds,
getAttr: getAttr,
setAttr: setAttr,
incMass: incMass,
intersects: intersects,
draw: draw,
update: update
};
}
var gameManager = (function() {
var canvasGrid = null;
var canvasEnt = null;
var canvasQuadtree = null;
var ctxGrid = null;
var ctxEnt = null;
var ctxQuadTree = null;
var dTime = 1 / 60;
var player = null;
var entityBag = [];
var qTree = null;
var drwQuad = 0;
var addEntity = function(ent) {
entityBag.push(ent);
};
var removeEntity = function(ent) {
var len = entityBag.length;
var i = 0;
for(i=0; i<len; i+=1) {
if(ent === entityBag[i]) {
entityBag.splice(i, 1);
return;
}
}
};
var init = function(cvsGridId, cvsEntId, cvsQuadtree) {
canvasGrid = document.getElementById(cvsGridId);
canvasEnt = document.getElementById(cvsEntId);
canvasQuadtree = document.getElementById(cvsQuadtree);
ctxGrid = canvasGrid.getContext('2d');
ctxEnt = canvasEnt.getContext('2d');
ctxQuadtree = canvasQuadtree.getContext('2d');
fitToContainer(canvasGrid);
fitToContainer(canvasEnt);
ctxGrid.fillStyle = '#F0FBFF';
ctxGrid.strokeStyle = '#BFBFBF';
ctxGrid.lineWidth = 1;
MouseHandler.init(document);
qTree = new Quadtree(0, {x:0, y:0, width:5000, height:5000});
player = new Circle({
x: 50,
y: 50,
color: 'red',
mass: 1000,
velX: 500,
velY:500
});
Camera.init(ctxEnt, player);
addEntity(player);
gameloop();
};
var handleInput = function() {
if(MouseHandler.isMouseIn() === false) {
player.setAttr({ velX: 0, velY: 0 });
return;
}
var pAttr = player.getAttr();
var rPlyrPos = Camera.getRelPos(player.getAttr());
var mPos = MouseHandler.getPos();
var dX = mPos.x - rPlyrPos.x;
var dY = mPos.y - rPlyrPos.y;
var vLength = Math.sqrt( (dX*dX) + (dY*dY) );
var normX = dX / vLength;
var normY = dY / vLength;
var newVelX = normX * (pAttr.maxVel * vLength / 50);
var newVelY = normY * (pAttr.maxVel * vLength / 50);
player.setAttr({
velX: newVelX,
velY: newVelY
});
};
var drawGrid = function() {
var camPos = Camera.getPos();
var camSize = Camera.getSize();
var start = Math.floor(camPos.x / 40);
var relX = Camera.getRelPos({x: (start*40), y: 0}).x;
var numLines = camSize.width / 40;
var i = 0;
ctxGrid.fillRect(0, 0, canvasGrid.width, canvasGrid.height);
for(i=0; i<numLines; i+=1) {
ctxGrid.beginPath();
ctxGrid.moveTo(relX + (40 * i), 0);
ctxGrid.lineTo(relX + (40 * i), camSize.height);
ctxGrid.stroke();
}
start = Math.floor(camPos.y / 40);
var relY = Camera.getRelPos({x: 0, y: (start * 40)}).y;
numLines = camSize.height / 40;
for(i=0; i<numLines; i+=1) {
ctxGrid.beginPath();
ctxGrid.moveTo(0, relY + (40 * i));
ctxGrid.lineTo(camSize.width, relY + (40 * i));
ctxGrid.stroke();
}
};
var handleCollisions = function() {
var possibleColl = [];
var collisions = [];
var coll = null;
var ent = null;
var plyMass = player.getAttr().mass
var entMass = 0;
qTree.clear();
for(ent in entityBag) {
qTree.insert(entityBag[ent]);
}
possibleColl = qTree.retrieve([], player);
while(ent = possibleColl.pop()) {
if(player.intersects(ent)) {
entMass = ent.getAttr().mass;
if(plyMass > (1.5 * entMass)) {
removeEntity(ent);
player.incMass(entMass);
}
}
var entAttr = ent.getAttr();
ctxQuadtree.fillStyle = 'red';
ctxQuadtree.fillRect(entAttr.x/20, entAttr.y/20, 3, 3);
}
};
var fitToContainer = function(canvas) {
canvas.style.width='100%';
canvas.style.height='100%';
canvas.width = canvas.offsetWidth;
canvas.height = canvas.offsetHeight;
};
var gameloop = function() {
var len = entityBag.length;
var i = 0;
var ent = null;
handleInput();
Camera.update();
drawGrid();
if(drwQuad === 5) {
ctxQuadtree.fillStyle = 'white';
ctxQuadtree.fillRect(0, 0, 250, 250);
qTree.drawTree(ctxQuadtree);
drwQuad = 0;
}
drwQuad += 1;
ctxEnt.clearRect(0, 0, canvasEnt.width, canvasEnt.height)
for(i=0; i<len; i+=1) {
ent = entityBag[i];
if(ent.update) {
ent.update(dTime);
}
if(ent.draw) {
ent.draw(ctxEnt, Camera);
}
}
handleCollisions();
setTimeout(gameloop, dTime * 1000);
};
return {
init: init,
addEntity: addEntity,
removeEntity: removeEntity
};
}());
var Camera = (function() {
var x = 0;
var y = 0;
var width = 0;
var height = 0;
var ctx = null;
var player = null;
var init = function(_ctx, plyr) {
ctx = _ctx;
player = plyr;
width = ctx.canvas.width;
height = ctx.canvas.height;
};
var update = function() {
width = ctx.canvas.width;
height = ctx.canvas.height;
var plyrAttr = player.getAttr();
x = (plyrAttr.x - width / 2);
y = (plyrAttr.y - height / 2);
};
var getRelPos = function(entAttr) {
var relX = entAttr.x - x;
var relY = entAttr.y - y;
return {
x: relX,
y: relY
};
};
var getPos = function() {
return {
x: x,
y: y
};
};
var getSize = function() {
return {
width: width,
height: height
};
};
return {
init: init,
update: update,
getRelPos: getRelPos,
getPos: getPos,
getSize: getSize
};
}());
var i = 0;
var space = 70;
for(i=0; i<400; i+=1) {
gameManager.addEntity(new Circle({
x: 100 + Math.random() * 4850,//(i%20) * space,
y: 100 + Math.random() * 4850,//Math.floor(i/20)*space,
color: ['red', 'blue', 'green', 'yellow', 'purple', 'brown', 'violet'][Math.floor(Math.random()*7)],
droplet: true
}));
}
gameManager.init('canvas1', 'canvas2', 'canvas3');
And last but not least, my css:
html, body {
background: gray;
width: 100%;
height: 100%;
margin: 0px;
}
#viewport {
position: relative;
width: 100%;
height: 100%;
}
#viewport canvas {
position: absolute;
}
canvas {
background-color: transparent;
}

add rectangle dynamically on button click inside canvas

function Shape(x, y, w, h, fill) {
this.x = x || 0;
this.y = y || 0;
this.w = w || 1;
this.h = h || 1;
this.fill = fill || '#AAAAAA';
}
Shape.prototype.draw = function(ctx) {
ctx.fillStyle = this.fill;
ctx.fillRect(this.x, this.y, this.w, this.h);
}
Shape.prototype.contains = function(mx, my) {
return (this.x <= mx) && (this.x + this.w >= mx) &&
(this.y <= my) && (this.y + this.h >= my);
}
function CanvasState(canvas) {
this.canvas = canvas;
this.width = canvas.width;
this.height = canvas.height;
this.ctx = canvas.getContext('2d');
var stylePaddingLeft, stylePaddingTop, styleBorderLeft, styleBorderTop;
if (document.defaultView && document.defaultView.getComputedStyle) {
this.stylePaddingLeft = parseInt(document.defaultView.getComputedStyle(canvas, null)['paddingLeft'], 10) || 0;
this.stylePaddingTop = parseInt(document.defaultView.getComputedStyle(canvas, null)['paddingTop'], 10) || 0;
this.styleBorderLeft = parseInt(document.defaultView.getComputedStyle(canvas, null)['borderLeftWidth'], 10) || 0;
this.styleBorderTop = parseInt(document.defaultView.getComputedStyle(canvas, null)['borderTopWidth'], 10) || 0;
}
var html = document.body.parentNode;
this.htmlTop = html.offsetTop;
this.htmlLeft = html.offsetLeft;
this.valid = false;
this.shapes = [];
this.dragging = false;
this.selection = null;
this.dragoffx = 0;
this.dragoffy = 0;
var myState = this;
canvas.addEventListener('selectstart', function(e) { e.preventDefault(); return false; }, false);
canvas.addEventListener('mousedown', function(e) {
var mouse = myState.getMouse(e);
var mx = mouse.x;
var my = mouse.y;
var shapes = myState.shapes;
var l = shapes.length;
for (var i = l-1; i >= 0; i--) {
if (shapes[i].contains(mx, my)) {
var mySel = shapes[i];
myState.dragoffx = mx - mySel.x;
myState.dragoffy = my - mySel.y;
myState.dragging = true;
myState.selection = mySel;
myState.valid = false;
return;
}
}
if (myState.selection) {
myState.selection = null;
myState.valid = false;
}
}, true);
canvas.addEventListener('mousemove', function(e) {
if (myState.dragging){
var mouse = myState.getMouse(e);
myState.selection.x = mouse.x - myState.dragoffx;
myState.selection.y = mouse.y - myState.dragoffy;
myState.valid = false;
}
}, true);
canvas.addEventListener('mouseup', function(e) {
myState.dragging = false;
}, true);
canvas.addEventListener('dblclick', function(e) {
var mouse = myState.getMouse(e);
myState.addShape(new Shape(mouse.x - 10, mouse.y - 10, 20, 20, 'rgba(0,255,0,.6)'));
}, true);
this.selectionColor = '#CC0000';
this.selectionWidth = 2;
this.interval = 30;
setInterval(function() { myState.draw(); }, myState.interval);
}
CanvasState.prototype.addShape = function(shape) {
this.shapes.push(shape);
this.valid = false;
}
CanvasState.prototype.clear = function() {
this.ctx.clearRect(0, 0, this.width, this.height);
}
CanvasState.prototype.draw = function() {
if (!this.valid) {
var ctx = this.ctx;
var shapes = this.shapes;
this.clear();
var l = shapes.length;
for (var i = 0; i < l; i++) {
var shape = shapes[i];
if (shape.x > this.width || shape.y > this.height ||
shape.x + shape.w < 0 || shape.y + shape.h < 0) continue;
shapes[i].draw(ctx);
}
if (this.selection != null) {
ctx.strokeStyle = this.selectionColor;
ctx.lineWidth = this.selectionWidth;
var mySel = this.selection;
ctx.strokeRect(mySel.x,mySel.y,mySel.w,mySel.h);
}
this.valid = true;
}
}
CanvasState.prototype.getMouse = function(e) {
var element = this.canvas, offsetX = 0, offsetY = 0, mx, my;
if (element.offsetParent !== undefined) {
do {
offsetX += element.offsetLeft;
offsetY += element.offsetTop;
} while ((element = element.offsetParent));
}
offsetX += this.stylePaddingLeft + this.styleBorderLeft + this.htmlLeft;
offsetY += this.stylePaddingTop + this.styleBorderTop + this.htmlTop;
mx = e.pageX - offsetX;
my = e.pageY - offsetY;
return {x: mx, y: my};
}
function init() {
var s = new CanvasState(document.getElementById('canvas1'));
s.addShape(new Shape(40,40,50,50)); // The default is gray
}
<canvas id="canvas1" width="200" height="200" style="border:1px solid #000000;">
This text is displayed if your browser does not support HTML5 Canvas.
</canvas>
<button onclick= "init()">click </button>
On click of a button, I am creating a rectangular element which can be drag and drop inside the canvas element restricted area.
however, Is it possible to create a new rectangular element dynamically on every click of a button which can further be drag and drop inside the canvas boundary.
And the previous rectangular element won't lost.
Doing this from scratch will be a lot of work. I suggest you use a library like fabric.js which has everything you asked plus a lot more to offer. Here is a demo page.
On every button click you was calling init(),.. Causing you CanvasState to reset.
I've just made another function called addShape, and just called init once.
I've also kept a reference to the CanvasState, called s.. So I could do s.addShape.. So changes were very minimal.
Hope this helps..
function Shape(x, y, w, h, fill) {
this.x = x || 0;
this.y = y || 0;
this.w = w || 1;
this.h = h || 1;
this.fill = fill || '#AAAAAA';
}
Shape.prototype.draw = function(ctx) {
ctx.fillStyle = this.fill;
ctx.fillRect(this.x, this.y, this.w, this.h);
}
Shape.prototype.contains = function(mx, my) {
return (this.x <= mx) && (this.x + this.w >= mx) &&
(this.y <= my) && (this.y + this.h >= my);
}
function CanvasState(canvas) {
this.canvas = canvas;
this.width = canvas.width;
this.height = canvas.height;
this.ctx = canvas.getContext('2d');
var stylePaddingLeft, stylePaddingTop, styleBorderLeft, styleBorderTop;
if (document.defaultView && document.defaultView.getComputedStyle) {
this.stylePaddingLeft = parseInt(document.defaultView.getComputedStyle(canvas, null)['paddingLeft'], 10) || 0;
this.stylePaddingTop = parseInt(document.defaultView.getComputedStyle(canvas, null)['paddingTop'], 10) || 0;
this.styleBorderLeft = parseInt(document.defaultView.getComputedStyle(canvas, null)['borderLeftWidth'], 10) || 0;
this.styleBorderTop = parseInt(document.defaultView.getComputedStyle(canvas, null)['borderTopWidth'], 10) || 0;
}
var html = document.body.parentNode;
this.htmlTop = html.offsetTop;
this.htmlLeft = html.offsetLeft;
this.valid = false;
this.shapes = [];
this.dragging = false;
this.selection = null;
this.dragoffx = 0;
this.dragoffy = 0;
var myState = this;
canvas.addEventListener('selectstart', function(e) { e.preventDefault(); return false; }, false);
canvas.addEventListener('mousedown', function(e) {
var mouse = myState.getMouse(e);
var mx = mouse.x;
var my = mouse.y;
var shapes = myState.shapes;
var l = shapes.length;
for (var i = l-1; i >= 0; i--) {
if (shapes[i].contains(mx, my)) {
var mySel = shapes[i];
myState.dragoffx = mx - mySel.x;
myState.dragoffy = my - mySel.y;
myState.dragging = true;
myState.selection = mySel;
myState.valid = false;
return;
}
}
if (myState.selection) {
myState.selection = null;
myState.valid = false;
}
}, true);
canvas.addEventListener('mousemove', function(e) {
if (myState.dragging){
var mouse = myState.getMouse(e);
myState.selection.x = mouse.x - myState.dragoffx;
myState.selection.y = mouse.y - myState.dragoffy;
myState.valid = false;
}
}, true);
canvas.addEventListener('mouseup', function(e) {
myState.dragging = false;
}, true);
canvas.addEventListener('dblclick', function(e) {
var mouse = myState.getMouse(e);
myState.addShape(new Shape(mouse.x - 10, mouse.y - 10, 20, 20, 'rgba(0,255,0,.6)'));
}, true);
this.selectionColor = '#CC0000';
this.selectionWidth = 2;
this.interval = 30;
setInterval(function() { myState.draw(); }, myState.interval);
}
CanvasState.prototype.addShape = function(shape) {
this.shapes.push(shape);
this.valid = false;
}
CanvasState.prototype.clear = function() {
this.ctx.clearRect(0, 0, this.width, this.height);
}
CanvasState.prototype.draw = function() {
if (!this.valid) {
var ctx = this.ctx;
var shapes = this.shapes;
this.clear();
var l = shapes.length;
for (var i = 0; i < l; i++) {
var shape = shapes[i];
if (shape.x > this.width || shape.y > this.height ||
shape.x + shape.w < 0 || shape.y + shape.h < 0) continue;
shapes[i].draw(ctx);
}
if (this.selection != null) {
ctx.strokeStyle = this.selectionColor;
ctx.lineWidth = this.selectionWidth;
var mySel = this.selection;
ctx.strokeRect(mySel.x,mySel.y,mySel.w,mySel.h);
}
this.valid = true;
}
}
CanvasState.prototype.getMouse = function(e) {
var element = this.canvas, offsetX = 0, offsetY = 0, mx, my;
if (element.offsetParent !== undefined) {
do {
offsetX += element.offsetLeft;
offsetY += element.offsetTop;
} while ((element = element.offsetParent));
}
offsetX += this.stylePaddingLeft + this.styleBorderLeft + this.htmlLeft;
offsetY += this.stylePaddingTop + this.styleBorderTop + this.htmlTop;
mx = e.pageX - offsetX;
my = e.pageY - offsetY;
return {x: mx, y: my};
}
var s;
function init() {
s = new CanvasState(document.getElementById('canvas1'));
}
function addShape() {
s.addShape(new Shape(40,40,50,50)); // The default is gray
}
init();
<canvas id="canvas1" width="400" height="300" style="border:1px solid #000000;">
This text is displayed if your browser does not support HTML5 Canvas.
</canvas>
<button onclick= "addShape()">click </button>

How to store scaled image in HTML5 canvas

I'm creating one drawing app, there I have option to zoom in/out of the canvas image which I have drawn using drawImage() method, after zoom the image I am trying to save the image using toDataUrl() method but its showing blank page after assigning width and height of zoomed image to canvas.
Below code is to save the image after zoomed
destinationCanvas.width = 500; // actual size given with integer values
destinationCanvas.height = 500;
destinationCanvas.style.width = '500px'; // show at 50% on screen
destinationCanvas.style.height = '500px';
var destinationCanvasURL = destinationCanvas.toDataURL();
console.log("markerNormalStyleChange() destinationCanvasURL - "+destinationCanvasURL);
function drawImage(_onScreenMarkingImagePath) {
var canvas = document.getElementById('drawOnScreen');
var ctx = canvas.getContext("2d");
var imageObject = new Image();
var div = $('#drawOnScreenContext'),
w = $(window).width() - 1,
h = $(window).height() - 150;
canvas.width = w;
canvas.height = h ;
$(imageObject).load(function () {
ctx.drawImage(imageObject, 0, 0, w,h);
});
}
Below code is for rawing and zooming the image, here after draw on canvas if I try to zoom then drawn contents will removed because its drawing image only, so for zooming I want to zoom drawn contents also
var requestID;
(function() {
var root = this; //global object
var ImgTouchCanvas = function(options) {
if( !options || !options.canvas || !options.path) {
throw 'ImgZoom constructor: missing arguments canvas or path';
}
this.canvas = options.canvas;
this.canvas.width = this.canvas.clientWidth;
this.canvas.height = this.canvas.clientHeight;
this.context = this.canvas.getContext('2d');
console.log("ImgTouchCanvas() initiated this.canvas.width - "+this.canvas.width);
console.log("ImgTouchCanvas() initiated this.canvas.height - "+this.canvas.height);
this.desktop = options.desktop || false; //non touch events
this.position = {
x: 0,
y: 0
};
this.scale = {
x: 0.5,
y: 0.5
};
this.imgTexture = new Image();
this.imgTexture.src = options.path;
this.lastZoomScale = null;
this.lastX = null;
this.lastY = null;
this.init = false;
this.checkRequestAnimationFrame();
requestID = requestAnimationFrame(this.animate.bind(this));
this.setEventListeners();
};
ImgTouchCanvas.prototype = {
animate: function() {
console.log("ImgTouchCanvas requestAnimationFrame()");
//set scale such as image cover all the canvas
if(!this.init) {
if(this.imgTexture.width) {
var scaleRatio = null;
if(this.canvas.clientWidth > this.canvas.clientHeight) {
scaleRatio = this.canvas.clientWidth / this.imgTexture.width;
}
else {
scaleRatio = this.canvas.clientHeight / this.imgTexture.height;
}
this.scale.x = scaleRatio;
this.scale.y = scaleRatio;
this.init = true;
}
}
//this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
//canvas.width = w;
//canvas.height = h ;
/*this.canvas.width = zoomWidth;
this.canvas.height = zoomHeight;*/
this.context.drawImage(
this.imgTexture,
this.position.x, this.position.y,
this.scale.x * this.imgTexture.width,
this.scale.y * this.imgTexture.height);
console.log("this.scale.x * this.imgTexture.width -- "+this.scale.x * this.imgTexture.width);
console.log("this.scale.y * this.imgTexture.height -- "+this.scale.y * this.imgTexture.height);
mWidth = this.scale.x * this.imgTexture.width;
mHeight = this.scale.y * this.imgTexture.height;
console.log("mWidth -- "+mWidth);
console.log("mHeight -- "+mHeight);
//if($('#pinchZoomInZoomOut').find('#pinchZoomInZoomOutBg').hasClass('btnIconHighLight')) {
//requestAnimationFrame(this.animate.bind(this));
//}else{
//cancelAnimationFrame(this.animate.bind(this));
//}
},
gesturePinchZoom: function(event) {
var zoom = false;
if( event.targetTouches.length >= 2 ) {
var p1 = event.targetTouches[0];
var p2 = event.targetTouches[1];
var zoomScale = Math.sqrt(Math.pow(p2.pageX - p1.pageX, 2) + Math.pow(p2.pageY - p1.pageY, 2)); //euclidian distance
if( this.lastZoomScale ) {
zoom = zoomScale - this.lastZoomScale;
}
this.lastZoomScale = zoomScale;
}
return zoom;
},
doZoom: function(zoom) {
if(!zoom) return;
//new scale
var currentScale = this.scale.x;
var newScale = this.scale.x + zoom/100;
//some helpers
var deltaScale = newScale - currentScale;
var currentWidth = (this.imgTexture.width * this.scale.x);
var currentHeight = (this.imgTexture.height * this.scale.y);
var deltaWidth = this.imgTexture.width*deltaScale;
var deltaHeight = this.imgTexture.height*deltaScale;
//by default scale doesnt change position and only add/remove pixel to right and bottom
//so we must move the image to the left to keep the image centered
//ex: coefX and coefY = 0.5 when image is centered <=> move image to the left 0.5x pixels added to the right
var canvasmiddleX = this.canvas.clientWidth / 2;
var canvasmiddleY = this.canvas.clientHeight / 2;
var xonmap = (-this.position.x) + canvasmiddleX;
var yonmap = (-this.position.y) + canvasmiddleY;
var coefX = -xonmap / (currentWidth);
var coefY = -yonmap / (currentHeight);
var newPosX = this.position.x + deltaWidth*coefX;
var newPosY = this.position.y + deltaHeight*coefY;
//edges cases
var newWidth = currentWidth + deltaWidth;
var newHeight = currentHeight + deltaHeight;
zoomWidth = newWidth;
zoomHeight = newHeight;
//console.log("doZoom() newWidth -- "+newWidth);
//console.log("doZoom() newHeight -- "+newHeight);
if( newWidth < this.canvas.clientWidth ) return;
if( newPosX > 0 ) { newPosX = 0; }
if( newPosX + newWidth < this.canvas.clientWidth ) { newPosX = this.canvas.clientWidth - newWidth;}
if( newHeight < this.canvas.clientHeight ) return;
if( newPosY > 0 ) { newPosY = 0; }
if( newPosY + newHeight < this.canvas.clientHeight ) { newPosY = this.canvas.clientHeight - newHeight; }
//finally affectations
this.scale.x = newScale;
this.scale.y = newScale;
this.position.x = newPosX;
this.position.y = newPosY;
},
doMove: function(relativeX, relativeY) {
if(this.lastX && this.lastY) {
var deltaX = relativeX - this.lastX;
var deltaY = relativeY - this.lastY;
var currentWidth = (this.imgTexture.width * this.scale.x);
var currentHeight = (this.imgTexture.height * this.scale.y);
//console.log("doZoom() currentWidth -- "+currentWidth);
//console.log("doZoom() currentHeight -- "+currentHeight);
this.position.x += deltaX;
this.position.y += deltaY;
//edge cases
if( this.position.x > 0 ) {
this.position.x = 0;
}
else if( this.position.x + currentWidth < this.canvas.clientWidth ) {
this.position.x = this.canvas.clientWidth - currentWidth;
}
if( this.position.y > 0 ) {
this.position.y = 0;
}
else if( this.position.y + currentHeight < this.canvas.clientHeight ) {
this.position.y = this.canvas.clientHeight - currentHeight;
}
}
this.lastX = relativeX;
this.lastY = relativeY;
},
Draw222: function(x, y, isDown) {
//console.log("Draw222() -- "+isDown);
if (isDown) {
this.context.beginPath();
this.context.strokeStyle="#FF0000";
this.context.lineWidth = 5;
this.context.lineJoin = "round";
this.context.moveTo(lx, ly);
this.context.lineTo(x, y);
this.context.closePath();
this.context.stroke();
}
lx = x; ly = y;
},
setEventListeners: function() {
// touch
this.canvas.addEventListener('touchstart', function(e) {
this.lastX = null;
this.lastY = null;
this.lastZoomScale = null;
//newCtx = this.canvas.getContext("2d");
var relativeX = e.targetTouches[0].pageX - this.canvas.getBoundingClientRect().left;
var relativeY = e.targetTouches[0].pageY - this.canvas.getBoundingClientRect().top;
if($('#pinchZoomInZoomOut').find('#pinchZoomInZoomOutBg').hasClass('btnIconHighLight')) {
//requestAnimationFrame(this.animate.bind(this));
}else{
$( '#undoIcon' ).css({
opacity: 1,
pointerEvents: 'auto'
});
cancelAnimationFrame(this.animate.bind(this));
canvasPressed = true;
this.Draw222(parseInt(relativeX), parseInt(relativeY), false);
}
}.bind(this));
this.canvas.addEventListener('touchmove', function(e) {
e.preventDefault();
if(e.targetTouches.length == 2 && $('#pinchZoomInZoomOut').find('#pinchZoomInZoomOutBg').hasClass('btnIconHighLight')) { //pinch
console.log("pinch zoom")
requestID = requestAnimationFrame(this.animate.bind(this));
this.doZoom(this.gesturePinchZoom(e));
}
else {
//console.log("touchmove --- 1")
var relativeX = e.targetTouches[0].pageX - this.canvas.getBoundingClientRect().left;
var relativeY = e.targetTouches[0].pageY - this.canvas.getBoundingClientRect().top;
if($('#pinchZoomInZoomOut').find('#pinchZoomInZoomOutBg').hasClass('btnIconHighLight')) {
//console.log("hasClass btnIconHighLight --- ");
requestID = requestAnimationFrame(this.animate.bind(this));
this.doMove(relativeX, relativeY);
}else{
//console.log("touchmove --- canvasPressed -- "+canvasPressed)
if (canvasPressed) {
cancelAnimationFrame(this.animate.bind(this));
this.Draw222(parseInt(relativeX), parseInt(relativeY), true);
}
}
}
}.bind(this));
this.canvas.addEventListener('touchend', function(e) {
e.preventDefault();
//cPush();
canvasPressed = false;
/*var base64String = null;
var canvas = document.getElementById('drawOnScreen');
var context = canvas.getContext('2d');
// save canvas image as data url (png format by default)
var dataURL = canvas.toDataURL();
console.log("dataURL - "+dataURL);*/
//base64ByteString = dataURL;
//dataURL = dataURL.substr(dataURL.lastIndexOf(',') + 1);
}.bind(this));
},
checkRequestAnimationFrame: function() {
var lastTime = 0;
var vendors = ['ms', 'moz', 'webkit', 'o'];
for(var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) {
window.requestAnimationFrame = window[vendors[x]+'RequestAnimationFrame'];
window.cancelAnimationFrame =
window[vendors[x]+'CancelAnimationFrame'] || window[vendors[x]+'CancelRequestAnimationFrame'];
}
if (!window.requestAnimationFrame) {
window.requestAnimationFrame = function(callback, element) {
var currTime = new Date().getTime();
var timeToCall = Math.max(0, 16 - (currTime - lastTime));
var id = window.setTimeout(function() { callback(currTime + timeToCall); },
timeToCall);
lastTime = currTime + timeToCall;
return id;
};
}
if (!window.cancelAnimationFrame) {
window.cancelAnimationFrame = function(id) {
clearTimeout(id);
};
}
}
};
root.ImgTouchCanvas = ImgTouchCanvas;
}).call(this);
And for pinch zoom in/out the image, I am using this https://github.com/rombdn/img-touch-canvas

Canvas: Movement only allowed on X axis?

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;

Categories