Jer*_*Jer 116 javascript html5 canvas onclick event-handling
我是一名经验丰富的Java程序员,但我在大约十年来第一次看到一些JavaScript/HTML5的东西.我完全不知道应该是最简单的事情.
作为一个例子,我只想绘制一些东西并为其添加一个事件处理程序.我确定我做了一些愚蠢的事情,但我已经搜索了所有内容并且没有任何建议(例如,这个问题的答案: 添加onclick属性以使用JavaScript输入).我正在使用Firefox 10.0.1.我的代码如下.您将看到几条注释行,并在每一行的末尾是对(或什么不)发生的描述.
这里的语法是什么?我要疯了!
<html>
<body>
<canvas id="myCanvas" width="300" height="150"/>
<script language="JavaScript">
var elem = document.getElementById('myCanvas');
// elem.onClick = alert("hello world"); - displays alert without clicking
// elem.onClick = alert('hello world'); - displays alert without clicking
// elem.onClick = "alert('hello world!')"; - does nothing, even with clicking
// elem.onClick = function() { alert('hello world!'); }; - does nothing
// elem.onClick = function() { alert("hello world!"); }; - does nothing
var context = elem.getContext('2d');
context.fillStyle = '#05EFFF';
context.fillRect(0, 0, 150, 100);
</script>
</body>
Run Code Online (Sandbox Code Playgroud)
ale*_*lex 200
绘制canvas元素时,只需在立即模式下绘制位图.
绘制的元素(形状,线条,图像)除了使用的像素和颜色外没有任何表示.
因此,为了获得一个点击一个事件canvas 元素(形状),您需要捕获点击的事件canvasHTML元素,并使用一些数学确定单击哪个元素,只要你是存储元素的宽度/高度和X/Y偏移.
要向元素添加click事件,请canvas使用...
canvas.addEventListener('click', function() { }, false);
Run Code Online (Sandbox Code Playgroud)
确定点击的元素 ...
var elem = document.getElementById('myCanvas'),
elemLeft = elem.offsetLeft,
elemTop = elem.offsetTop,
context = elem.getContext('2d'),
elements = [];
// Add event listener for `click` events.
elem.addEventListener('click', function(event) {
var x = event.pageX - elemLeft,
y = event.pageY - elemTop;
// Collision detection between clicked offset and element.
elements.forEach(function(element) {
if (y > element.top && y < element.top + element.height
&& x > element.left && x < element.left + element.width) {
alert('clicked an element');
}
});
}, false);
// Add element.
elements.push({
colour: '#05EFFF',
width: 150,
height: 100,
top: 20,
left: 15
});
// Render elements.
elements.forEach(function(element) {
context.fillStyle = element.colour;
context.fillRect(element.left, element.top, element.width, element.height);
});?
Run Code Online (Sandbox Code Playgroud)
此代码将一个click事件附加到canvas元素,然后将一个形状(element在我的代码中称为一个)推送到一个elements数组.您可以在此处添加任意数量的内容.
创建对象数组的目的是为了以后我们可以查询它们的属性.在将所有元素推送到数组之后,我们遍历并根据它们的属性渲染每个元素.
当click事件被触发时,代码循环遍历元素并确定点击是否在elements数组中的任何元素上.如果是这样,它会触发一个alert(),可以很容易地修改它来做一些事情,比如删除数组项,在这种情况下你需要一个单独的渲染函数来更新canvas.
为了完整,为什么你的尝试不起作用......
elem.onClick = alert("hello world"); // displays alert without clicking
Run Code Online (Sandbox Code Playgroud)
这是指定的返回值alert()的onClick财产elem.它立刻调用了alert().
elem.onClick = alert('hello world'); // displays alert without clicking
Run Code Online (Sandbox Code Playgroud)
在JavaScript中,'和"语义相同,词法分析器可能['"]用于引号.
elem.onClick = "alert('hello world!')"; // does nothing, even with clicking
Run Code Online (Sandbox Code Playgroud)
您正在为该onClick属性指定一个字符串elem.
elem.onClick = function() { alert('hello world!'); }; // does nothing
Run Code Online (Sandbox Code Playgroud)
JavaScript区分大小写.该onclick属性是附加事件处理程序的古老方法.它只允许一个事件与属性相关联,并且在序列化HTML时可能会丢失事件.
elem.onClick = function() { alert("hello world!"); }; // does nothing
Run Code Online (Sandbox Code Playgroud)
再次,' === ".
Le_*_*___ 48
2021 年:
要在 HTML5 画布中创建可跟踪元素,您应该使用新的 Path2D()方法。
创建形状并new Path2D()为每个形状指定名称后,侦听画布上的触摸或鼠标事件(例如onclick、ondblclick、oncontextmenu或等)以获取点坐标,然后使用或来精确检查鼠标是否是将您的元素悬停在该事件中。onmousemoveevent.offsetXevent.offsetYCanvasRenderingContext2D.isPointInPath()CanvasRenderingContext2D.isPointInStroke()
路径中的点:
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
// Create circle
const circle = new Path2D();
circle.arc(150, 75, 50, 0, 2 * Math.PI);
ctx.fillStyle = 'red';
ctx.fill(circle);
// Listen for mouse moves
canvas.addEventListener('mousemove', function(event) {
// Check whether point is inside circle
if (ctx.isPointInPath(circle, event.offsetX, event.offsetY)) {
ctx.fillStyle = 'green';
}
else {
ctx.fillStyle = 'red';
}
// Draw circle
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.fill(circle);
});Run Code Online (Sandbox Code Playgroud)
<canvas id="canvas"></canvas>Run Code Online (Sandbox Code Playgroud)
笔画中的点:
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
// Create ellipse
const ellipse = new Path2D();
ellipse.ellipse(150, 75, 40, 60, Math.PI * .25, 0, 2 * Math.PI);
ctx.lineWidth = 25;
ctx.strokeStyle = 'red';
ctx.fill(ellipse);
ctx.stroke(ellipse);
// Listen for mouse moves
canvas.addEventListener('mousemove', function(event) {
// Check whether point is inside ellipse's stroke
if (ctx.isPointInStroke(ellipse, event.offsetX, event.offsetY)) {
ctx.strokeStyle = 'green';
}
else {
ctx.strokeStyle = 'red';
}
// Draw ellipse
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.fill(ellipse);
ctx.stroke(ellipse);
});Run Code Online (Sandbox Code Playgroud)
<canvas id="canvas"></canvas>Run Code Online (Sandbox Code Playgroud)
具有多个元素的示例:
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
const circle = new Path2D();
circle.arc(50, 75, 50, 0, 2 * Math.PI);
ctx.fillStyle = 'red';
ctx.fill(circle);
const circletwo = new Path2D();
circletwo.arc(200, 75, 50, 0, 2 * Math.PI);
ctx.fillStyle = 'red';
ctx.fill(circletwo);
// Listen for mouse moves
canvas.addEventListener('mousemove', function(event) {
// Check whether point is inside circle
if (ctx.isPointInPath(circle, event.offsetX, event.offsetY)) {
ctx.fillStyle = 'green';
ctx.fill(circle);
}
else {
ctx.fillStyle = 'red';
ctx.fill(circle);
}
if (ctx.isPointInPath(circletwo, event.offsetX, event.offsetY)) {
ctx.fillStyle = 'blue';
ctx.fill(circletwo);
}
else {
ctx.fillStyle = 'red';
ctx.fill(circletwo);
}
});Run Code Online (Sandbox Code Playgroud)
html {cursor: crosshair;}Run Code Online (Sandbox Code Playgroud)
<canvas id="canvas"></canvas>Run Code Online (Sandbox Code Playgroud)
如果您有要检查的动态元素列表,则可以循环检查它们,如下所示:
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
var elementslist = []
const circle = new Path2D();
circle.arc(50, 75, 30, 0, 2 * Math.PI);
ctx.fillStyle = 'red';
ctx.fill(circle);
const circletwo = new Path2D();
circletwo.arc(150, 75, 30, 0, 2 * Math.PI);
ctx.fillStyle = 'red';
ctx.fill(circletwo);
const circlethree = new Path2D();
circlethree.arc(250, 75, 30, 0, 2 * Math.PI);
ctx.fillStyle = 'red';
ctx.fill(circlethree);
elementslist.push(circle,circletwo,circlethree)
document.getElementById("canvas").addEventListener('mousemove', function(event) {
event = event || window.event;
var ctx = document.getElementById("canvas").getContext("2d")
for (var i = elementslist.length - 1; i >= 0; i--){
if (elementslist[i] && ctx.isPointInPath(elementslist[i], event.offsetX, event.offsetY)) {
document.getElementById("canvas").style.cursor = 'pointer';
ctx.fillStyle = 'orange';
ctx.fill(elementslist[i]);
return
} else {
document.getElementById("canvas").style.cursor = 'default';
ctx.fillStyle = 'red';
for (var d = elementslist.length - 1; d >= 0; d--){
ctx.fill(elementslist[d]);
}
}
}
});Run Code Online (Sandbox Code Playgroud)
<canvas id="canvas"></canvas>Run Code Online (Sandbox Code Playgroud)
资料来源:
| 归档时间: |
|
| 查看次数: |
203716 次 |
| 最近记录: |