canvas製作滑鼠繪圖和方塊移動小案例
阿新 • • 發佈:2018-11-10
在這裡插入圖片描述
canvas製作滑鼠繪圖: 原理:獲取開始點選的點 和滑鼠移動後的點
所用知識:event物件 canvas繪圖
window.onload=function (){ var myCanvas=document.querySelector('#myCanvas'); var cxt=myCanvas.getContext('2d'); myCanvas.onmousedown=function (event) { var e=event || window.event; //獲取滑鼠開始點選位置 cxt.moveTo(e.clientX-myCanvas.offsetLeft,e.clientY-myCanvas.offsetTop); document.onmousemove=function (event) { var e=event || window.event; //滑鼠移動位置 cxt.lineTo(e.clientX-myCanvas.offsetLeft,e.clientY-myCanvas.offsetTop); cxt.stroke(); } document.onmouseup=function () { document.onmouseup=null; document.onmousemove=null; } } }
方塊移動小案例: 座標的改變
window.onload=function (){ var myCanvas=document.querySelector('#myCanvas'); var cxt=myCanvas.getContext('2d'); var num=0; cxt.fillRect(0,0,100,100); setInterval(function () { num++; cxt.clearRect(0,0,myCanvas.width,myCanvas.height); cxt.fillRect(num,num,100,100); },30) }