Reputation: 431
In W3schools it written that there is "No support for event handlers".But when i append onclick to canvas its working .Why ?
<html>
<body>
<canvas id="myCanvas" width="100" height="100" style="border:1px solid #c3c3c3;" onclick="alert(1)">
</canvas>
<script>
Upvotes: 1
Views: 833
Reputation:
Because w3school content should be taken with a grain of salt. They are correct and provides nice examples for some things, but are directly wrong on other things - and does not have a proper mechanism to tell/correct them.
Canvas do support events both as subscriptions (using addEventListener()
) as well as as direct callbacks (such as canvas.onclick = ...
).
For keys you need to use tabIndex
to "activate" the ability to catch focus. While it has focus it can also receive key events (you can in any case receive those from the window
object).
var canvas = document.getElementById("canvas");
var out = document.getElementById("out");
canvas.addEventListener("keydown", output);
canvas.addEventListener("keyup", output);
canvas.addEventListener("mousedown", mouse);
canvas.addEventListener("mouseup", mouse);
canvas.addEventListener("mousemove", mouse);
// ... etc
function output(e) {out.innerHTML = e.type + ": " + e.keyCode}
function mouse(e) {out.innerHTML = e.type + ": x=" + e.clientX + " y=" + e.clientY}
canvas {background:#ddd}
<canvas id="canvas" tabIndex="0" width=400 height=150></canvas><br>
<output id="out"></output>
Upvotes: 3