我是使用畫布和 javascript 的初學者,我正在嘗試使用滑鼠懸停。我必須讓它作業一點,但只有當滑鼠在畫布上時,我想讓我的方形顏色在我的滑鼠放在畫布上時改變。
我怎樣才能讓它作業?
這是我的代碼:
window.onload = function()
{
canvasEvent();
}
function canvasEvent()
{
var c=document.getElementById("canvas");
var ctx=c.getContext("2d");
ctx.rect(150, 150, 100, 100);
ctx.fillStyle = "blue";
ctx.fill();
ctx.stroke();
c.addEventListener("mouseover", hover, false);
c.addEventListener("mouseout", hoverOut, false);
}
function hover(e)
{
var c=document.getElementById("canvas");
var ctx=c.getContext("2d");
ctx.fillStyle = 'green';
ctx.fill();
ctx.stroke();
}
function hoverOut(e)
{
var c=document.getElementById("canvas");
var ctx=c.getContext("2d");
ctx.fillStyle = 'blue';
ctx.fill();
}
canvas#canvas{
background-color:#DDDDDD;
display: block;
margin: 0 auto;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>TEST</title>
<script type="text/javascript" src="script.js"></script>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<center>
<canvas id="canvas" width="550" height="400"></canvas>
</center>
</body>
</html>
uj5u.com熱心網友回復:
只需檢查滑鼠是否在矩形上
window.onload = function()
{
canvasEvent();
}
function canvasEvent()
{
var c=document.getElementById("canvas");
var ctx=c.getContext("2d");
ctx.rect(150, 150, 100, 100);
ctx.fillStyle = "blue";
ctx.fill();
ctx.stroke();
c.addEventListener("mousemove", e => {
if (
e.offsetX >=150 &&
e.offsetX <= 250 &&
e.offsetY >= 150 &&
e.offsetY<=250){
hover();
}
else{
hoverOut();
}
});
}
function hover(e)
{
var c=document.getElementById("canvas");
var ctx=c.getContext("2d");
ctx.fillStyle = 'green';
ctx.fill();
ctx.stroke();
}
function hoverOut(e)
{
var c=document.getElementById("canvas");
var ctx=c.getContext("2d");
ctx.fillStyle = 'blue';
ctx.fill();
}
canvas#canvas{
background-color:#DDDDDD;
display: block;
margin: 0 auto;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>TEST</title>
<script type="text/javascript" src="script.js"></script>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<center>
<canvas id="canvas" width="550" height="400"></canvas>
</center>
</body>
</html>
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/464798.html
標籤:javascript html css html5-画布
下一篇:如何使滑塊在BS折疊元素中作業?
