
contr.gif
一、拖動
所要的鼠標(biāo)事件mousedown(鼠標(biāo)按下)、mousemove(鼠標(biāo)移動)及mouseup(鼠標(biāo)抬起)
1、設(shè)置全局變量
var x = 50 //初始x位置
var y = 50 //初始y位置
var r = 20 //半徑
var area = Math.PI*r*r //面積
var step = 5 //速度
2、獲取canvas對象
var canvas = document.getElementById("canvas"); //獲取canvas對象
var ctx = canvas.getContext("2d"); //創(chuàng)建二維對象
3、方法封裝:創(chuàng)建對象實例,每次執(zhí)行清除一下畫布
// 創(chuàng)建實例
function createBlock(x, y){
ctx.clearRect(0, 0, canvas.width, canvas.height); // 清除畫布
ctx.restore();
ctx.beginPath();
// arc參數(shù)分別是(橫坐標(biāo)、縱坐標(biāo)、半徑、起始角(弧度計0.5PI/1PI/1.5PI/2PI)、結(jié)束角 、可選(False順時針,true逆時針))
ctx.arc(x, y, r, 0, 2 * Math.PI);
ctx.save();
ctx.fillStyle = "skyblue";
ctx.fill()
ctx.stroke(); // 重繪
}
4、鼠標(biāo)事件,及執(zhí)行方法,用isPointInPath(x, y)判斷鼠標(biāo)位置是否在圓上(小知識:isPointInPath只能判斷最后一個繪制的路徑),利用拖動實時計算圓的位置
document.onmousedown = function(evt){ // 鼠標(biāo)左鍵按下
evt = evt || event;
var eX = evt.clientX - canvas.offsetLeft;
var eY = evt.clientY - canvas.offsetTop;
// 按下鼠標(biāo)判斷鼠標(biāo)位置是否在圓上,當(dāng)畫布上有多個路徑時,isPointInPath只能判斷最后那一個繪制的路徑
if (evt.which == 1 && ctx.isPointInPath(eX, eY) && type == 'drag'){
document.onmousemove = function(ev) { // 鼠標(biāo)拖動
var e = ev || event;
var moveX = e.clientX - evt.clientX;
var moveY = e.clientY - evt.clientY;
drag(moveX, moveY)
}
}
}
document.onmouseup = function(evt) { // 鼠標(biāo)抬起
if (evt.which == 1 && type == 'drag'){
// 保存當(dāng)前位置
x = clientX? clientX: x
y = clientY? clientY: y
document.onmousemove = null // 取消拖動
}
}
// 記錄位置
var clientX = 0
var clientY = 0
function drag(moveX, moveY){ // 拖動執(zhí)行
clientX = getLimitX(x + moveX)
clientY = getLimitX(y + moveY)
createBlock(clientX, clientY)
}
5、獲取畫布的邊界,位置改變時不允許超出canvas
// 獲取左右邊界(包括邊框)
function getLimitX(x){
if (x < r + 1) { //左邊界
x = r + 1
} else if (x > canvas.width - r - 1) { //右邊界
x = canvas.width - r - 1
}
return x
}
// 獲取上下邊界(包括邊框)
function getLimitY(x){
if (y < r + 1) { //上邊界
y = r + 1
} else if (y > canvas.height - r - 1) { //下邊界
y = canvas.height - r - 1
}
return y
}
二、方向鍵控制
所要鍵盤事件keydown(鍵盤按下)、keyup(鍵盤抬起)
1、鍵盤事件,及執(zhí)行方法,利用全局變量x,y的自增、自減實時計算圓的位置
var direction = 0
document.addEventListener('keydown', function(evt) { // 鍵盤按下
// console.log(evt)
switch (evt.which) { // 方向鍵判斷
case 37: // ←left
direction = -1;
break;
case 38: // ↑up
direction = 2;
break;
case 39: // →right
direction = 1;
break;
case 40: // ↓down
direction = -2;
break;
}
document.addEventListener('keyup', function(evt) { // 鍵盤抬起
if ((evt.which == 37 || evt.which == 38 && direction || evt.which == 39 || evt.which == 40) && direction) {
direction = 0;
}
});
});
function animation() {
if (direction == -1) {
// console.log('左移')
x -= step
} else if (direction == 1) {
// console.log('右移')
x += step
} else if (direction == 2) {
// console.log('上移')
y -= step
} else if (direction == -2) {
// console.log('下移')
y += step
}
x = getLimitX(x)
y = getLimitX(y)
createBlock(x, y)
if(type == 'control'){
//執(zhí)行的動畫幀
requestAnimationFrame(animation);
}
}
2、兼容性支持,判斷requestAnimationFrame動畫幀數(shù)方法是否存在,requestAnimationFrame函數(shù)執(zhí)行次數(shù)通常是每秒60次
// 兼容性支持,判斷是否存在requestAnimationFrame
function getAnimationFrame() {
var lastTime = 0;
var vendors = ['webkit', 'moz'];
for (var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) {
window.requestAnimationFrame = window[vendors[x] + 'RequestAnimationFrame'];
window.cancelAnimationFrame = window[vendors[x] + 'CancelAnimationFrame'] || window[vendors[x] +
'CancelRequestAnimationFrame'];
}
if (!window.requestAnimationFrame) {
window.requestAnimationFrame = function(callback) {
var currTime = new Date().getTime();
var timeToCall = Math.max(0, 16 - (currTime - lastTime));
var id = window.setTimeout(function() {
callback(currTime + timeToCall);
},
timeToCall);
lastTime = currTime + timeToCall;
return id;
};
}
if (!window.cancelAnimationFrame) {
window.cancelAnimationFrame = function(id) {
clearTimeout(id);
};
}
}
三、放大縮小
所要鼠標(biāo)事件,鼠標(biāo)滾輪滾動事件mousewheel,
1、鼠標(biāo)事件,及執(zhí)行方法,利用改變圓的面積來重新計算半徑r,只在畫布內(nèi)執(zhí)行
// 鼠標(biāo)滾輪放大縮小
var scaleFactor = 1.1;
canvas.onmousewheel = function(evt){
var delta = evt.wheelDelta ? evt.wheelDelta / 40 : evt.detail ? -evt.detail : 0;
if(delta){
var scale = Math.pow(scaleFactor, delta); // 放大倍數(shù)
area = scale*area // 放大的面積
r = Math.sqrt(area/Math.PI) // 重新計算半徑s=πr2
createBlock(x, y); // 重繪
}
}
四、完整代碼
1、css
* {
margin: 0;
padding: 0;
}
#box {
width: fit-content;
margin: 0 auto;
margin-top: 20px;
}
.btn{
margin-bottom: 5px;
display: flex;
justify-content: space-between;
}
#text{
color: blue;
}
2、html
<div id="box">
<div class="btn">
<!-- 控制:使用方向鍵移動 -->
<div>
<button type="button" onclick="changeType('drag')">拖動</button>
<button type="button" onclick="changeType('control')">控制</button>
</div>
<div>
當(dāng)前模式:
<span id="text">drag</span>
</div>
</div>
<canvas id="canvas" width="500" height="500" style="border:1px solid red">
瀏覽器不支持canvas
</canvas>
</div>
3、js
getAnimationFrame()
var type = 'drag'
function changeType(val) {
type = val
var el = document.getElementById('text')
el.innerText = val
if (type == 'control') {
requestAnimationFrame(animation);
}
}
var x = 50 //初始x位置
var y = 50 //初始y位置
var r = 20 //半徑
var area = Math.PI * r * r //面積
var step = 5 //速度
var canvas = document.getElementById("canvas"); //獲取canvas對象
var ctx = canvas.getContext("2d"); //創(chuàng)建二維對象
//動畫
function animation() {
if (direction == -1) {
// console.log('左移')
x -= step
} else if (direction == 1) {
// console.log('右移')
x += step
} else if (direction == 2) {
// console.log('上移')
y -= step
} else if (direction == -2) {
// console.log('下移')
y += step
}
x = getLimitX(x)
y = getLimitX(y)
createBlock(x, y)
if (type == 'control') {
//這里寫要執(zhí)行的動畫
requestAnimationFrame(animation);
}
}
// 獲取左右邊界(包括邊框)
function getLimitX(x) {
if (x < r + 1) { //左邊界
x = r + 1
} else if (x > canvas.width - r - 1) { //右邊界
x = canvas.width - r - 1
}
return x
}
// 獲取上下邊界(包括邊框)
function getLimitY(x) {
if (y < r + 1) { //上邊界
y = r + 1
} else if (y > canvas.height - r - 1) { //下邊界
y = canvas.height - r - 1
}
return y
}
// 創(chuàng)建實例
function createBlock(x, y) {
ctx.clearRect(0, 0, canvas.width, canvas.height); // 清除畫布
ctx.globalCompositeOperation = "saturation";
ctx.restore();
ctx.beginPath();
// arc參數(shù)分別是(橫坐標(biāo)、縱坐標(biāo)、半徑、起始角(弧度計0.5PI/1PI/1.5PI/2PI)、結(jié)束角 、可選(False順時針,true逆時針))
ctx.arc(x, y, r, 0, 2 * Math.PI);
ctx.save();
// 設(shè)置陰影
ctx.fillStyle = "skyblue";
ctx.fill()
ctx.stroke(); // 重繪
}
createBlock(x, y)
var direction = 0
//鍵盤監(jiān)聽事件
document.addEventListener('keydown', function(evt) { // 鍵盤按下
switch (evt.which) { // 方向鍵判斷
case 37: // ←left
direction = -1;
break;
case 38: // ↑up
direction = 2;
break;
case 39: // →right
direction = 1;
break;
case 40: // ↓down
direction = -2;
break;
}
document.addEventListener('keyup', function(evt) { // 鍵盤抬起
if ((evt.which == 37 || evt.which == 38 && direction || evt.which == 39 || evt.which == 40) && direction) {
direction = 0;
}
});
});
document.onmousedown = function(evt) { // 鼠標(biāo)左鍵按下
evt = evt || event;
var eX = evt.clientX - canvas.offsetLeft;
var eY = evt.clientY - canvas.offsetTop;
// 按下鼠標(biāo)判斷鼠標(biāo)位置是否在圓上,當(dāng)畫布上有多個路徑時,isPointInPath只能判斷最后那一個繪制的路徑
// console.log(ctx.isPointInPath(eX, eY))
if (evt.which == 1 && ctx.isPointInPath(eX, eY) && type == 'drag') {
document.onmousemove = function(ev) { // 鼠標(biāo)拖動
var e = ev || event;
var moveX = e.clientX - evt.clientX;
var moveY = e.clientY - evt.clientY;
drag(moveX, moveY)
}
}
}
document.onmouseup = function(evt) { // 鼠標(biāo)抬起
if (evt.which == 1 && type == 'drag') {
// 保存當(dāng)前位置
x = clientX ? clientX : x
y = clientY ? clientY : y
document.onmousemove = null // 取消拖動
}
}
var clientX = 0
var clientY = 0
function drag(moveX, moveY) { // 拖動執(zhí)行
clientX = getLimitX(x + moveX)
clientY = getLimitX(y + moveY)
createBlock(clientX, clientY)
}
// 鼠標(biāo)滾輪放大縮小
var scaleFactor = 1.1;
canvas.onmousewheel = function(evt) {
var delta = evt.wheelDelta ? evt.wheelDelta / 40 : evt.detail ? -evt.detail : 0;
if (delta) {
var scale = Math.pow(scaleFactor, delta); // 放大倍數(shù)
area = scale * area // 放大的面積
r = Math.sqrt(area / Math.PI) // 重新計算半徑s=πr2
createBlock(x, y); // 重繪
}
}
// 兼容性支持,判斷是否存在requestAnimationFrame
function getAnimationFrame() {
var lastTime = 0;
var vendors = ['webkit', 'moz'];
for (var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) {
window.requestAnimationFrame = window[vendors[x] + 'RequestAnimationFrame'];
window.cancelAnimationFrame = window[vendors[x] + 'CancelAnimationFrame'] || window[vendors[x] +
'CancelRequestAnimationFrame'];
}
if (!window.requestAnimationFrame) {
window.requestAnimationFrame = function(callback) {
var currTime = new Date().getTime();
var timeToCall = Math.max(0, 16 - (currTime - lastTime));
var id = window.setTimeout(function() {
callback(currTime + timeToCall);
},
timeToCall);
lastTime = currTime + timeToCall;
return id;
};
}
if (!window.cancelAnimationFrame) {
window.cancelAnimationFrame = function(id) {
clearTimeout(id);
};
}
}