HTML 5 Canvas: how to check all coordinates of line points?
I would like to create a simple game with canavas: there is a form and the user has to draw on its border without leaving it. I have a form, the user can draw, but now I can't find a way to check when the custom drawing is out of the border of the form. I have to check the coordinates of each point of the lines it draws. Is it possible and how or are there other ways? Thank!
function findxy(res, e) {
if (res == 'down') {
if(status == 'wait'){
status = 'run';
startX = e.clientX -canvas2.offsetLeft;
startY = e.clientY -canvas2.offsetLeft;
}
if (status == 'run'){
write = true;
currX = e.clientX -canvas2.offsetLeft;
currY = e.clientY -canvas2.offsetTop;
context2.fillStyle = 'red';
context2.fillRect(currX, currY, lineWidth, lineWidth);
}
}
if (res == 'up' || res == "out") {
if(status=='run'){
status = 'stop';
write = false;
if(won)
alert('You won!');
else
alert('You lose!');
}
}
if (res == 'move') {
if (write) {
currX = e.clientX - canvas2.offsetLeft;
currY = e.clientY - canvas2.offsetTop;
var baseData = context1.getImageData(currX, currY, 1, 1).data;
context2.fillStyle = 'red';
context2.fillRect(currX, currY, lineWidth, lineWidth);
if(baseData[3]!=255){
alert('You lose!');
status='lose';
write=false;
}
if(currX==startX && currY==startY){
won=true;
}
}
}
}
+3
source to share
1 answer
Note that I have two canvases, one for the user, and one for the black box (which will be your shape). When the user moves the mouse, I draw a point on the user's canvas, and I check the other canvas if the mouse is in the black box.
Code:
var CheckCanvases = function() {
var canvas1 = document.getElementById("canvas1");
var canvas2 = document.getElementById("canvas2");
var ctx1 = canvas1.getContext("2d");
var ctx2 = canvas2.getContext("2d");
var output = document.getElementById("output");
this.init = function() {
var self = this;
ctx1.fillRect(0, 0, 80, 80);
canvas2.addEventListener("mousemove", function(e) {
var mousePosX = e.clientX;
var mousePosY = e.clientY;
self.checkIfMouseIsInBox(mousePosX, mousePosY);
})
}
this.checkIfMouseIsInBox = function(x, y) {
var imageData = ctx1.getImageData(x, y, 1, 1).data;
ctx2.fillRect(x, y, 1, 1);
//image data is an Red, Green, Blue, Alpha array -> [0, 0, 0, 0]
//if it is [0, 0, 0, 255] it means it is not transparent, thus the mouse is in the black box
if (imageData[3] == 255) {
output.innerHTML = "In Box";
} else {
output.innerHTML = "Not in Box"
}
}
this.init();
}
var checkCanvases = new CheckCanvases();
canvas {
position: absolute;
top: 0;
left: 0;
}
h3 {
margin-top: 120px;
}
<canvas id="canvas1" width="200" height="100"></canvas>
<canvas id="canvas2" width="200" height="100"></canvas>
<h3 id="output">Not in Box</h3>
+3
source to share