請幫我理解畫布的事件。畫布和事件
以兩個方塊爲例。每個區域都有自己的區域,您需要處理此類事件:
- 將鼠標懸停在正方形上填充顏色。
- 單擊調用填充正方形的第三種顏色並顯示在單獨的塊中,例如正方形的ID。
- 因此,有可能只使用一個正方形。點擊第二個方塊將重置第一個方塊並從第二個方塊輸出數據。
- 將鼠標移動到鼠標附近的一個正方形區域時,會彈出一個窗口,顯示該正方形的ID。
而我該如何建立一個單獨的廣場鏈接?也就是說,用戶點擊一個調用該事件的鏈接,類似於單獨的方塊上的點擊。
HTML代碼
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<script type="text/javascript" src="scripts/canvas.js"></script>
<script>
window.onload = function()
{
drawCanvas('mainCanvas');
};
</script>
</head>
<body style="margin: 0px;">
<canvas id="mainCanvas" width="300" height="200"></canvas>
<aside>ID of the square</aside>
</body>
</html>
JS代碼
function makeRect(x, y, w, h)
{
return { x: x, y: y, w: w, h: h };
}
function drawCanvas(canvasId)
{
//// General Declarations
var canvas = document.getElementById(canvasId);
var context = canvas.getContext('2d');
//// Color Declarations
var blackColor = 'rgba(0, 0, 0, 1)';
var whiteColor = 'rgba(255, 255, 255, 1)';
//// Frames
var frameOne = makeRect(64, 70, 50, 50);
var frameTwo = makeRect(194, 70, 50, 50);
//// RectangleOne Drawing
context.beginPath();
context.rect(frameOne.x, frameOne.y, 50, 50);
context.fillStyle = whiteColor;
context.fill();
context.strokeStyle = blackColor;
context.lineWidth = 1;
context.stroke();
//// RectangleTwo Drawing
context.beginPath();
context.rect(frameTwo.x, frameTwo.y, 50, 50);
context.fillStyle = whiteColor;
context.fill();
context.strokeStyle = blackColor;
context.lineWidth = 1;
context.stroke();
}
如果我理解正確,那麼您希望在呈現到畫布之後仍然可以選擇正方形,除非您保留一些持久性有關正方形的信息並執行一些相交測試,您不能在畫布上執行此操作,它們會丟失所有正方形的上下文,並且只是畫布上的像素。 – zero298
感謝您的回覆!那麼我應該注意使用SVG來提供交互性? – user3174610