学习canvas鼠标控制事件的demo,鼠标移入移出切换圆形的颜色。
思路:
1.主函数中绑定鼠标移动事件监听器,编写鼠标移动函数判断鼠标位置
2.通过setInterval(gameLoop,200);函数进行画面刷新。
3.通过属性ctx.globalAlpha = alive;来控制图像的透明度,指定出现或者消失。
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>engineer</title>
<style type = "text/css">
div{
margin-top: 50px;
text-align: center;
}
#cv{
margin: auto;
border: 1px solid #0cc;
}
</style>
</head>
<body>
<div>
<canvas id = "cv" height = "600px" width = "600px">
</canvas>
</div>
<script src = "my.js"></script>
</body>
</html>
js
var canvas = document.getElementById("cv");
var ctx = canvas.getContext('2d');
var switchy = false;
var width = ctx.canvas.width;
var height = ctx.canvas.height;
window.onload = function (){
document.addEventListener('mousemove', mousemove, false);
gameLoop();
setInterval(gameLoop,200);
}
function mousemove(e){
if (e.offsetX || e.layerX) {
var px = e.offsetX == undefined ? e.layerX : e.offsetX;
var py = e.offsetY == undefined ? e.layerY : e.offsetY;
if (px > 0 && px < 600 && py > 0 && py < 600) {
switchy = true;
} else {
switchy = false;
}
console.log(switchy);
}
}
function gameLoop(){
var alive = 0;
alive = isalive();
draw(alive);
}
function draw(alive){
ctx.save();
ctx.beginPath();
ctx.fillStyle = "#ff0000";
ctx.arc(width/2,height/2,100,0,2*Math.PI,true);
ctx.fill();
ctx.stroke();
ctx.restore();
ctx.save();
ctx.globalAlpha = alive;
ctx.fillStyle = "#0000ff";
ctx.arc(width/2,height/2,100,0,2*Math.PI,true);
ctx.fill();
ctx.stroke();
ctx.restore();
}
function isalive(){
if (switchy) {
alive = 1;
}else{
alive = 0;
}
return alive;
}
canvas基础知识小结:
1.canvas学习小结
(1)获取标签
canvas = document.getElementById("canvas");
ctx = canvas.getContext("2d")
var width = ctx.canvas.width;
var height = ctx.canvas.height;
(2)绘图
ctx.beginPath();
ctx.linewidth = 1;
ctx.globalAlpha = 1;
ctx.fillStyle = "#cccccc"
ctx.fill()
ctx.save();
ctx.restore();
ctx.moveTo(100,100);
ctx.lineTo(200,200);
ctx.arc(100,100,10,0,Math.PI * 2,false);
ctx.moveTo(150, 350);
ctx.quadraticCurveTo(300, 500, 450, 400);
ctx.stroke();
(3)事件
document.addEventListener('mousemove',mousemove, false);
function mousemove(e){
if (e.offsetX || e.layerX) {
var px = e.offsetX == undefined ? e.layerX : e.offsetX;
var py = e.offsetY == undefined ? e.layerY : e.offsetY;
if (px > 0 && px < 600 && py > 0 && py < 600) {
switchy = true;
} else {
switchy = false;
}
console.log(switchy);
}
}
(3)画面刷新
写法一:
window.requestAnimFrame(gameLoop);
window.requestAnimFrame = (function() {
return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame ||
function( /* function FrameRequestCallback */ callback, /* DOMElement Element */ element) {
return window.setTimeout(callback, 1000 / 60);
};
})();
写法二:
setInterval(draw,1000);