简体   繁体   English

悬停时更改strokeRect颜色

[英]changing strokeRect colour on hover

so i'm playing around with HTML and JavaScript and i'm trying out the Canvas element. 所以我在玩HTML和JavaScript,并尝试使用Canvas元素。
so I made a simple strokeRect that acts as a button. 所以我做了一个简单的strokeRect作为按钮。
I want to make it so it changes the strokeRect colour when i hover over it 我要制作它,以便将鼠标悬停在它上面时会更改strokeRect颜色
how would i do this? 我该怎么办? Here is my HTML code 这是我的HTML代码

<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
<title>UNNAMED</title>
</head>
<body>
<canvas id="secret" width="360px" height="30px"></canvas>
<canvas id="drawing" onClick="secret()" width="102px" height="42px">Your browser doesn't support the canvas element</canvas>
<script src="jsfil.js" type="text/javascript"></script>
</body>
</html> 

and here is my JavaScript code 这是我的JavaScript代码

var cSecret = document.getElementById("secret").getContext("2d");
var cRect = document.getElementById("drawing").getContext("2d");
var cText = document.getElementById("drawing").getContext("2d");
cText.font="18px Times New Roman";
cText.fillText("Click me",18,26);
cRect.strokeStyle = "#FF0000";
cRect.strokeRect(1, 1 , 100, 40);
var secretFound = false;
function secret() {
if(secretFound == false)
{
    secretFound = true;
    cSecret.font="24px Times New Roman";
    cSecret.fillText("Congratulations, you found a secret",1,20);
   }    
}

And here is my css code 这是我的CSS代码

#copyright{
position: absolute;
top: 92%;   
}
#drawing{
position: absolute;
top: 50px;
left: 50px;
border: 1px;
border-style: solid;
border-color: blue; 
}
#drawing:hover{
position: absolute;
top: 50px;
left:   50px;
border: 1px;
border-style: solid;
border-color: red;
}
#secret{
    position: absolute;
}

I want to change the strokeStyle when I hover over the rectangle. 当我将鼠标悬停在矩形上时,我想更改strokeStyle。
i've tried using CSS but that only creates a new border. 我试过使用CSS,但这只会创建一个新的边框。
One way I thought of doing it is checking the cursor position 我想到的一种方法是检查光标位置
if the cursor is in this area it would change colour but it feels like there should be an easier way. 如果光标位于该区域,它将改变颜色,但感觉应该有一种更简单的方法。

Canvas does not work like that. 画布不能那样工作。 If you want to change something, you have to redraw. 如果要更改某些内容,则必须重新绘制。 You can take a look at SVG, that allows to modify things with Css. 您可以看一下SVG,它允许使用CSS修改内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM