How to Show/ hide part of canvas? - javascript

Here is My JS fiddle
I have a requirement like when user clicks on center circle, that should toggle outer circle and when user clicks on outer small circles that should change center circle value.
Here i am not getting how to Show/ hide part of Canvas when user clicks on center circle?
Any help on how to do this?
GenerateCanvas();
function GenerateCanvas() {
try {
var FlagCircleCenterCoordinates = new Array();
var FlagCircles = [];
var CenterX = document.getElementById('canvasFlag').width / 2;
var CenterY = document.getElementById('canvasFlag').height / 2;
var OuterTrackRadius = 98;
var InnerTrackRadius = 70;
var InnerCircleRadius = 20;
var FlagElement = document.getElementById("canvasFlag");
var ObjContext = FlagElement.getContext("2d");
// Outer track
ObjContext.fillStyle = "#FFF";
ObjContext.beginPath();
ObjContext.arc(CenterX, CenterY, OuterTrackRadius, 0, 2 * Math.PI);
ObjContext.strokeStyle = '#CCC';
ObjContext.stroke();
ObjContext.fill();
// Inner track
ObjContext.beginPath();
ObjContext.arc(CenterX, CenterY, InnerTrackRadius, 0, 2 * Math.PI);
ObjContext.strokeStyle = '#CCC';
ObjContext.stroke();
// Inner small circle
ObjContext.beginPath();
ObjContext.arc(CenterX, CenterY, InnerCircleRadius, 0, 2 * Math.PI);
ObjContext.strokeStyle = '#CCC';
ObjContext.stroke();
//Max 17...other wide need to change the Inner and Outer circle radius
var FlagImagesArray = [1, 2, 3,4,5];
if (FlagImagesArray.length > 0) {
var StepAngle = 2 * Math.PI / FlagImagesArray.length;
var FlagCircleRadius = (OuterTrackRadius - InnerTrackRadius) / 2;
var RadiusOfFlagCircleCenters = OuterTrackRadius - FlagCircleRadius;
for (var LoopCnt in FlagImagesArray) {
var CircleCenterCoordinates = new Object();
CircleCenterCoordinates.PostionX = CenterX + (Math.cos(StepAngle * (parseInt(LoopCnt) + 1)) * RadiusOfFlagCircleCenters);
CircleCenterCoordinates.PostionY = CenterY + (Math.sin(StepAngle * (parseInt(LoopCnt) + 1)) * RadiusOfFlagCircleCenters);
ObjContext.beginPath();
ObjContext.arc(CircleCenterCoordinates.PostionX, CircleCenterCoordinates.PostionY, FlagCircleRadius, 0, 2 * Math.PI);
ObjContext.strokeStyle = '#CCC';
ObjContext.stroke();
ObjContext.fillStyle = 'blue';
ObjContext.fillText(FlagImagesArray[LoopCnt], CircleCenterCoordinates.PostionX, CircleCenterCoordinates.PostionY);
FlagCircleCenterCoordinates[LoopCnt] = CircleCenterCoordinates;
var ObjFlagCircle = {
Left : CircleCenterCoordinates.PostionX - FlagCircleRadius,
Top : CircleCenterCoordinates.PostionY - FlagCircleRadius,
Right : CircleCenterCoordinates.PostionX + FlagCircleRadius,
Bottom : CircleCenterCoordinates.PostionY + FlagCircleRadius,
FlagName : FlagImagesArray[LoopCnt]
}
FlagCircles[LoopCnt] = ObjFlagCircle;
}
$('#canvasFlag').mousemove(function (Event) {
debugger;
$(this).css('cursor', 'auto');
var ClickedX = Event.pageX - $('#canvasFlag').offset().left;
var ClickedY = Event.pageY - $('#canvasFlag').offset().top;
for (var Count = 0; Count < FlagCircles.length; Count++) {
if (ClickedX < FlagCircles[Count].Right &&
ClickedX > FlagCircles[Count].Left &&
ClickedY > FlagCircles[Count].Top &&
ClickedY < FlagCircles[Count].Bottom) {
$(this).css('cursor', 'pointer');
break;
}
}
});
$('#canvasFlag').click(function (Event) {
debugger;
$(this).css('cursor', 'auto');
var ClickedX = Event.pageX - $('#canvasFlag').offset().left;
var ClickedY = Event.pageY - $('#canvasFlag').offset().top;
for (var Count = 0; Count < FlagCircles.length; Count++) {
if (ClickedX < FlagCircles[Count].Right &&
ClickedX > FlagCircles[Count].Left &&
ClickedY > FlagCircles[Count].Top &&
ClickedY < FlagCircles[Count].Bottom) {
ObjContext.fillStyle = "#FFF";
ObjContext.beginPath();
ObjContext.arc(CenterX, CenterY, InnerCircleRadius - 1, 0, Math.PI * 2);
ObjContext.closePath();
ObjContext.fill();
ObjContext.fillStyle = "blue";
ObjContext.fillText(FlagCircles[Count].FlagName, CenterX, CenterY);
break;
}
}
});
}
}
catch (E) {
alert(E);
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<canvas id="canvasFlag" width="200" height="200">
Your browser does not support the canvas
</canvas>

Oh man. Ok so first off, you'll need to get rid of the try/catch statement, it isn't doing anything.
Next you'll need to make all those vars you have outside of the function body, we need to be able to access them from another function
It looks like you have all your click functionality done, and it's working too. That's good, just go ahead and move both of the lines that start with jquery outside of the generateCanvas function. They only need to run once, and we're going to need to call generate canvas again.
Fourth, make a variable to toggle the outer circle off and on somewhere, and only draw the outer ring in generateCanvas() when that variable is true. You should also set another Global variable that gets set to Count, right before you break, so that you can remember it when you regenerate the canvas.
Take all the code you have in your click function to draw the inner circle with the number, and put that inside of generate canvas. Make sure that code only calls if the variable you used to remember Count is set to something (ie you had already clicked an outer number)
Next, add a generateCanvas() call in your click function.Now your click function sets the variable you use to represent the center value, redraws the canvas, and returns. You'll need more logic in your mouse down function in order to figure out when you clicked the center, but based on the code you already have you can figure that out, your main problem is just that this was set up to run once, not multiple times. That makes the canvas a lot more like an image instead of an active drawing element
Don't forget to add FlagElement.width = FlagElement.width to clear the canvas! (or just draw a background over it)

Related

trying to make a drawn line move like a laser in javascript

I made this red line in JavaScript that goes to closest target (balloon 1 to 3) to the player but I need to make it so that it moves like a laser starting from player position into the target position. I thought about multiple ways of implementing this with no luck.
function Tick() {
// Erase the sprite from its current location.
eraseSprite();
for (var i = 0; i < lasers.length; i++) {
lasers[i].x += lasers[i].direction.x * laserSpeed;
lasers[i].y += lasers[i].direction.y * laserSpeed;
//Hit detection here
}
function detectCharClosest() {
var ballon1char = {
x: balloon1X,
y: balloon1Y
};
var ballon2char = {
x: balloon2X,
y: balloon2Y
};
var ballon3char = {
x: balloon3X,
y: balloon3Y,
};
ballon1char.distanceFromPlayer = Math.sqrt((CharX - balloon1X) ** 2 + (CharY - balloon1Y) ** 2);
ballon2char.distanceFromPlayer = Math.sqrt((CharX - balloon2X) ** 2 + (CharY - balloon2Y) ** 2);
ballon3char.distanceFromPlayer = Math.sqrt((CharX - balloon3X) ** 2 + (CharY - balloon3Y) ** 2);
var minDistance = Math.min(
ballon1char.distanceFromPlayer,
ballon2char.distanceFromPlayer,
ballon3char.distanceFromPlayer);
console.log(ballon1char);
console.log(ballon2char);
console.log(ballon3char);
for (let i = 0; i < 3; i++) {
if (minDistance == ballon1char.distanceFromPlayer)
return ballon1char
if (minDistance == ballon2char.distanceFromPlayer)
return ballon2char
if (minDistance == ballon3char.distanceFromPlayer)
return ballon3char
}
}
function loadComplete() {
console.log("Load is complete.");
canvas = document.getElementById("theCanvas");
ctx = canvas.getContext("2d");
myInterval = self.setInterval(function () { Tick() }, INTERVAL);
myInterval = self.setInterval(function () { laserTicker(detectCharClosest()) }, 2000);
function laserTicker(balloon) {
//gets the closest ballon to go to
laserDo(balloon);
}
function laserDo(balloon) {
ctx.beginPath();
ctx.lineWidth = 2;
ctx.strokeStyle = "#F44336"; // "red";
ctx.moveTo(CharX + 16, CharY + 16);
ctx.lineTo(balloon.x, balloon.y);
// lasers.push({x: })
ctx.stroke();
}
I didn't put all of my code here so If something doesn't make sense please tell me. I'm still new to JavaScript and learning it. One way I thought I could make this work was by taking the distance between the player and the target and dividing it by the speed on the x and y axis then changing having it start from the player position and keeps on adding up on both axis until it reaches the target. That didn't work out though. If you have any suggestions then please tell me.
Thanks

Is DOM manipulation code queued or run synchronously? [duplicate]

I don't understand why the infinite loop does not work but uncommenting the function call works.
<body>
<canvas id="myCanvas"style="border:2px solid black;" width="1600" height="900">
Your browser does not support the HTML5 canvas tag.
</canvas>
<script>
var c = document.getElementById ("myCanvas").getContext ("2d");
var boxSize = 25;
var numBoxes = 1;
var x = 1000;
var dx = 1;
var y = 100;
var dy = 1;
var a = 0.01;
var da = 0.1;
var size = 20;
var w = c.canvas.width;
var h = c.canvas.height;
//function testing () {
while (true) {
c.clearRect (0, 0, w, h);
x = x + 1;
y = y + 1;
a = a + 0.1;
x = x + dx;
y = y + dy;
if (x < size / 2 || x + (size / 2) > w) {
dx = -dx;
da = -da;
}
if (y < size / 2 || y + (size / 2) > h) {
dy = -dy;
da = -da;
}
c.save ();
c.translate (x, y);
c.rotate (a);
c.strokeRect (-size / 2, -size / 2, size, size);
c.restore ();
}
// testing ();
// setInterval (testing, 10);
</script>
</body>
When you use setInterval you keep adding the function you are calling to the queue of things for the browser to do. Repaint events are also added to this queue.
When you use an infinite loop, the browser never gets to the end of the function, so it never gets around to running a repaint and the image in the document never updates.
JavaScript-in-a-browser is a part of a larger construction. You need to align to the rules of this construction and don't hurt it. One of the rule is that your JavaScript must run quick and exit then. Exit means that control gets back to the framework, which does all the job, repaint the screen etc.
Try to hide and show something many times:
for (n = 0; n < 200; n++) {
$("#test").hide();
$("#test").show();
}
When this code runs, you won't see any flickering, you will see that the last command will have effect.
Have to say, it's not easy to organize code that way, if you want to make a cycle which paints nice anims on a canvas, you have to do it without while.

d3 js - how to mimic distance/depth of field using randomized opacity on fillStyle() & fillRect() without strobe effect?

I am attempting to use particlesDepthBlur() in place of the opacity for the "snowflakes" - which is located inside the step function, however it produces an undesired strobe effect - why? Consider the following code,
Edited for clarification:
<canvas id="canvas"></canvas>
<script src="http://d3js.org/d3.v3.min.js"></script>
<script>
var num = 2000;
var canvas = document.getElementById("canvas");
var width = canvas.width = 960;
var height = canvas.height = 500;
var ctx = canvas.getContext("2d");
var particles = d3.range(num).map(function(i) {
return [Math.round(width*Math.random()), Math.round(height*Math.random())];
});
function particlesDepthBlur(){
return Math.random();
console.log(Math.random());
}
function particlesDepthSize(){
return Math.floor((Math.random()*4)+1);
}
d3.timer(step);
function step() {
ctx.shadowBlur=0;
ctx.shadowColor="";
ctx.fillStyle = "rgba(0,0,0,"+particlesDepthBlur()+")";
ctx.fillRect(0,0,width,height);
ctx.shadowBlur=particlesDepthSize();
ctx.shadowColor="white";
ctx.fillStyle = "rgba(255,255,255,1)";
particles.forEach(function(p) {
p[0] += Math.round(2*Math.random()-1);
p[1] += Math.round(2*Math.random()-1) + 2;
if (p[0] < 0) p[0] = width;
if (p[0] > width) p[0] = 0;
if (p[1] < 0) p[1] = height;
if (p[1] > height) p[1] = 0;
drawPoint(p);
});
};
function drawPoint(p) {
ctx.fillRect(p[0],p[1],1,1);
};
</script>
<style>
html, body { margin: 0; padding: 0; }
</style>
Couple things:
Firstly you are calling ctx.fillStyle = "rgba(0,0,0,"+particlesDepthBlur()+")"; immediately before filling the background of the canvas.
Second, you are only calculating the blur and opacity once per frame, not per particle.
Thirdly, if you calculate it per particle (and continue to use Math.random()) then it bogs down my machine with several thousand operations per second.
Here is my
fiddle!
~Every frame I calculate 10 opacities and 10 sizes and iterate across the particles setting them per particle.~ << This was an
old version; now the opacities are all set up before step() is called, and the sizes are proportional to opacities.
edit: good job with the random falling-downward motion!
edit2: tweaking to set constant opacity and size per particle. this still runs very slowly for me, probably because you are running Math.random() 4000 times per frame. You might consider calculating a couple dozen positional vectors once per frame, and iterate across all your particles. This way every n snowflakes would be falling in the same pattern, at the benefit of much less computation needed.
Finally, perhaps consider making the 'close' snowflakes (big and bright) fall faster than the 'far' snowflakes.
<snip>
// Set up an opacity value for each particle, this will later be indexed with j
var particleOpacities = [];
particles.forEach(function(p){
particleOpacities.push(particlesDepthBlur());
});
d3.timer(step);
var j = 0;
// since j is used by both step and drawPoint, it has to be outside both functions
function step() {
ctx.shadowBlur=0;
ctx.shadowColor="";
ctx.fillStyle = "rgba(0,0,0,1)";
ctx.fillRect(0,0,width,height);
j = 0;
particles.forEach(function(p) {
p[0] += Math.round(2*Math.random()-1);
p[1] += Math.round(2*Math.random()-1) + 2;
if (p[0] < 0) p[0] = width;
if (p[0] > width) p[0] = 0;
if (p[1] < 0) p[1] = height;
if (p[1] > height) p[1] = 0;
drawPoint(p);
});
};
function drawPoint(p) {
j++; // iterate over points
var particleSize = particleOpacities[j] * 4;
ctx.shadowBlur=particleSize;
ctx.shadowColor="white";
ctx.fillStyle = "rgba(255,255,255," + particleOpacities[j] + ")";
ctx.fillRect(p[0],p[1],particleSize,particleSize);
};
The ctx.fillStyle = "rgba(0,0,0,"+particlesDepthBlur()+")"; randomly changes how much of the previous canvas is visible. It does so uniformly across the entire canvas. Sometimes if fills the screen completely with black wiping out the past views, other times it lets the last screen partially show. When it lets previous views be seen it can as much double the amount of white on the canvas, and when followed by a low opacity suddenly the quantity of white drops.
function particlesDepthBlur(){
return Math.random(0.5)+.5;
}
smooths this out

Raphael transform object diagonally and infinite setIntervals

I'm working on a small animation where the user drags a circle and the circle returns back to the starting point. I figured out a way to have the circle return to the starting point. The only problem is that it will hit one of the sides of the frame before returning. Is it possible for it to go straight back (follow the path of a line drawn between the shape and starting point).
The other problem is that my setInterval doesn't want to stop. If you try pulling it a second time it would pull it back before you release your mouse. It also seems to speed up after every time. I have tried using a while loop with a timer but the results weren't as good. Is this fixable?
var paper = Raphael(0, 0, 320, 200);
//var path = paper.path("M10 10L40 40").attr({stoke:'#000000'});
//var pathArray = path.attr("path");
var circle = paper.circle(50, 50, 20);
var newX;
var newY;
circle.attr("fill", "#f00");
circle.attr("stroke", "#fff");
var start = function () {
this.attr({cx: 50, cy: 50});
this.cx = this.attr("cx"),
this.cy = this.attr("cy");
},
move = function (dx, dy) {
var X = this.cx + dx,
Y = this.cy + dy;
this.attr({cx: X, cy: Y});
},
up = function () {
setInterval(function () {
if(circle.attr('cx') > 50){
circle.attr({cx : (circle.attr('cx') - 1)});
} else if (circle.attr('cx') < 50){
circle.attr({cx : (circle.attr('cx') + 1)});
}
if(circle.attr('cy') > 50){
circle.attr({cy : (circle.attr('cy') - 1)});
} else if (circle.attr('cy') < 50){
circle.attr({cy : (circle.attr('cy') + 1)});
}
path.attr({path: pathArray});
},2);
};
circle.drag(move, start, up);
Here's the Jfiddle: http://jsfiddle.net/Uznp2/
Thanks alot :D
I modified the "up" function to the one below
up = function () {
//starting x, y of circle to go back to
var interval = 1000;
var startingPointX = 50;
var startingPointY = 50;
var centerX = this.getBBox().x + (this.attr("r")/2);
var centerY = this.getBBox().y + (this.attr("r")/2);
var transX = (centerX - startingPointX) * -1;
var transY = (centerY - startingPointY) * -1;
this.animate({transform: "...T"+transX+", "+transY}, interval);
};
and the "start" function as follows:
var start = function () {
this.cx = this.attr("cx"),
this.cy = this.attr("cy");
}
Is this the behavior you are looking for? Sorry if I misunderstood the question.
If the circle need to get back to its initial position post drag, we can achieve that via simple animation using transform attribute.
// Assuming that (50,50) is the location the circle prior to drag-move (as seen in the code provided)
// The animation is set to execute in 1000 milliseconds, using the easing function of 'easeIn'.
up = function () {
circle.animate({transform: 'T50,50'}, 1000, 'easeIn');
};
Hope this helps.

Creating a Clickable Grid in a Web Browser

I want to draw a grid of 10 x 10 squares on a HTML5 canvas with number 1-100 displayed on the squares. Clicking a square should call a JavaScript function with the square's number passed as a variable to the function.
First, I encourage you to read this answer to another question involving the HTML5 Canvas. You need to understand that there are no squares. In order to detect a click on a 'square', you would have to keep track of a mapping from each canvas coordinate to the square(s) that it logically contains, handle a single click event on the entire canvas, work out which square(s) you want to change, and then redraw the canvas with the changes you want.
Then—since you seem to have no objection to using a more appropriate technology—I encourage you to do this in either HTML (where each 'square' is something like a <div> that is absolutely-positioned and sized and colored using CSS), or SVG (using <rect> if you need the squares to be able to be rotated, or want to introduce other shapes).
HTML and SVG are both 'retained-mode' graphics mode systems, where drawing a shape 'retains' the concept of that shape. You can move the shape, change its colors, size, etc. and the computer will automatically redraw it for you. Moreover, and more importantly for your use case, you can (with both HTML and SVG):
function changeColor(evt){
var clickedOn = evt.target;
// for HTML
clickedOn.style.backgroundColor = '#f00';
// for SVG
clickedOn.setAttribute('fill','red');
}
mySquare.addEventListener('click',changeColor,false);
Edit: I've created a simple implementation in JavaScript and HTML: http://jsfiddle.net/6qkdP/2/
Here's the core code, in case JSFiddle is down:
function clickableGrid( rows, cols, callback ){
var i=0;
var grid = document.createElement('table');
grid.className = 'grid';
for (var r=0;r<rows;++r){
var tr = grid.appendChild(document.createElement('tr'));
for (var c=0;c<cols;++c){
var cell = tr.appendChild(document.createElement('td'));
cell.innerHTML = ++i;
cell.addEventListener('click',(function(el,r,c,i){
return function(){ callback(el,r,c,i); }
})(cell,r,c,i),false);
}
}
return grid;
}
EDIT: Using HTML elements rather than drawing these things on a canvas or using SVG is another option and quite possibly preferable.
Following up on Phrogz's suggestions, see here for an SVG implementation:
jsfiddle example
document.createSvg = function(tagName) {
var svgNS = "http://www.w3.org/2000/svg";
return this.createElementNS(svgNS, tagName);
};
var numberPerSide = 20;
var size = 10;
var pixelsPerSide = 400;
var grid = function(numberPerSide, size, pixelsPerSide, colors) {
var svg = document.createSvg("svg");
svg.setAttribute("width", pixelsPerSide);
svg.setAttribute("height", pixelsPerSide);
svg.setAttribute("viewBox", [0, 0, numberPerSide * size, numberPerSide * size].join(" "));
for(var i = 0; i < numberPerSide; i++) {
for(var j = 0; j < numberPerSide; j++) {
var color1 = colors[(i+j) % colors.length];
var color2 = colors[(i+j+1) % colors.length];
var g = document.createSvg("g");
g.setAttribute("transform", ["translate(", i*size, ",", j*size, ")"].join(""));
var number = numberPerSide * i + j;
var box = document.createSvg("rect");
box.setAttribute("width", size);
box.setAttribute("height", size);
box.setAttribute("fill", color1);
box.setAttribute("id", "b" + number);
g.appendChild(box);
var text = document.createSvg("text");
text.appendChild(document.createTextNode(i * numberPerSide + j));
text.setAttribute("fill", color2);
text.setAttribute("font-size", 6);
text.setAttribute("x", 0);
text.setAttribute("y", size/2);
text.setAttribute("id", "t" + number);
g.appendChild(text);
svg.appendChild(g);
}
}
svg.addEventListener(
"click",
function(e){
var id = e.target.id;
if(id)
alert(id.substring(1));
},
false);
return svg;
};
var container = document.getElementById("container");
container.appendChild(grid(5, 10, 200, ["red", "white"]));
container.appendChild(grid(3, 10, 200, ["white", "black", "yellow"]));
container.appendChild(grid(7, 10, 200, ["blue", "magenta", "cyan", "cornflowerblue"]));
container.appendChild(grid(2, 8, 200, ["turquoise", "gold"]));
As the accepted answer shows, doing this in HTML/CSS is easiest if this is all your design amounts to, but here's an example using canvas as an alternative for folks whose use case might make more sense in canvas (and to juxtapose against HTML/CSS).
The first step of the problem boils down to figuring out where in the canvas the user's mouse is, and that requires knowing the offset of the canvas element. This is the same as finding the mouse position in an element, so there's really nothing unique to canvas here in this respect. I'm using event.offsetX/Y to do this.
Drawing a grid on canvas amounts to a nested loop for rows and columns. Use a tileSize variable to control the step amount. Basic math lets you figure out which tile (coordinates and/or cell number) your mouse is in based on the width and height and row and column values. Use context.fill... methods to write text and draw squares. I've kept everything 0-indexed for sanity, but you can normalize this as a final step before display (don't mix 1-indexing in your logic, though).
Finally, add event listeners to the canvas element to detect mouse actions which will trigger re-computations of the mouse position and selected tile and re-renders of the canvas. I attached most of the logic to mousemove because it's easier to visualize, but the same code applies to click events if you choose.
Keep in mind that the below approach is not particularly performance-conscious; I only re-render when the cursor moves between cells, but partial re-drawing or moving an overlay to indicate the highlighted element would be faster (if available). There are a lot of micro-optimizations I've ignored. Consider this a proof-of-concept.
const drawGrid = (canvas, ctx, tileSize, highlightNum) => {
for (let y = 0; y < canvas.width / tileSize; y++) {
for (let x = 0; x < canvas.height / tileSize; x++) {
const parity = (x + y) % 2;
const tileNum = x + canvas.width / tileSize * y;
const xx = x * tileSize;
const yy = y * tileSize;
if (tileNum === highlightNum) {
ctx.fillStyle = "#f0f";
}
else {
ctx.fillStyle = parity ? "#555" : "#ddd";
}
ctx.fillRect(xx, yy, tileSize, tileSize);
ctx.fillStyle = parity ? "#fff" : "#000";
ctx.fillText(tileNum, xx, yy);
}
}
};
const size = 10;
const canvas = document.createElement("canvas");
canvas.width = canvas.height = 200;
const ctx = canvas.getContext("2d");
ctx.font = "11px courier";
ctx.textBaseline = "top";
const tileSize = canvas.width / size;
const status = document.createElement("pre");
let lastTile = -1;
drawGrid(canvas, ctx, tileSize);
document.body.style.display = "flex";
document.body.style.alignItems = "flex-start";
document.body.appendChild(canvas);
document.body.appendChild(status);
canvas.addEventListener("mousemove", evt => {
event.target.style.cursor = "pointer";
const tileX = ~~(evt.offsetX / tileSize);
const tileY = ~~(evt.offsetY / tileSize);
const tileNum = tileX + canvas.width / tileSize * tileY;
if (tileNum !== lastTile) {
lastTile = tileNum;
ctx.clearRect(0, 0, canvas.width, canvas.height);
drawGrid(canvas, ctx, tileSize, tileNum);
}
status.innerText = ` mouse coords: {${evt.offsetX}, ${evt.offsetX}}
tile coords : {${tileX}, ${tileY}}
tile number : ${tileNum}`;
});
canvas.addEventListener("click", event => {
status.innerText += "\n [clicked]";
});
canvas.addEventListener("mouseout", event => {
drawGrid(canvas, ctx, tileSize);
status.innerText = "";
lastTile = -1;
});

Categories

Resources