gpt4 book ai didi

javascript - HTML 5 Canvas : how to check all line points coordinates?

转载 作者:行者123 更新时间:2023-11-29 10:41:44 25 4
gpt4 key购买 nike

我想用 canavas 构建一个简单的游戏:有一个形状,用户必须沿着它的边界绘制,而不能超出它。我有形状,用户可以绘制,但现在我找不到检查用户绘制何时超出形状边界的方法。我应该检查他画的线的每个点的坐标。有可能吗?还有其他方法吗?谢谢!

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;
}

}
}
}

最佳答案

请注意,我有两张 Canvas ,一张供用户绘制,一张用于黑框(即您的形状)。当用户移动鼠标时,我会在用户 Canvas 上画一个点,然后在另一个 Canvas 上检查鼠标是否在黑框上。

代码:

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>

关于javascript - HTML 5 Canvas : how to check all line points coordinates?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27801205/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com