HTML 5 canvas属性单击

时间:2017-11-05 11:44:31

标签: html5 html5-canvas

所以这个问题是在html5画布上,pic有我们在学校做的问题,但仍然不知道答案

so this question is on html5 canvas the pic has the question we did in school but still do not know the answer to

1 个答案:

答案 0 :(得分:0)

有两种方法可以解决这个问题

在JavaScript中使用EventListener编号1:

var canvas, context;

function drawBox() {
  context.fillStyle = "black";
  context.strokeRect(20, 20, canvas.width - 20, canvas.height - 20);
}

function clickReporter(e) {
  console.log("clicked");
}

canvas = document.getElementById("clickCanvas");
context = canvas.getContext("2d");
drawBox();

// Add the eventlistener
canvas.addEventListener("click", clickReporter);
<canvas id="clickCanvas" width="300" height="300">Your browser does not support the HTML5 canvas</canvas>

Numer 2,在HTML标记中添加EventListener

var canvas, context;

function drawBox() {
  context.fillStyle = "black";
  context.strokeRect(20, 20, canvas.width - 20, canvas.height - 20);
}

function clickReporter(e) {
  console.log("clicked");
}

canvas = document.getElementById("clickCanvas");
context = canvas.getContext("2d");
drawBox();
<!--- Add the eventlistener --->
<canvas id="clickCanvas" width="300" height="300" onclick="clickReporter()">Your browser does not support the HTML5 canvas</canvas>