刚开始学Js写的
把canvas Api 看完就会了,链接: canvas api,也通过CRM 学习法
初始化项目
- 新建一个
index.html - 初始化下
git然后git init - 预览: 先安装下工具
yarn global add http-serve装完之后hs . -c-1就可以预览了
heght:100vh 跟屏幕一样高
先随便搞一个,出错了再改
技巧:
怎么确定是我想要的x,y呢! 可以找一个特殊位置,最左上角x,y
code:
canvas.onclick = (e)=>{
console.log(e)
// console.log调式大法
}
canvas.onclick = (e)=>{
console.log(e.clientX)
console.log(e.clientY)
}
document.createElement让文档创建一个标签div.style.left = e.clientX + 'px'注意加上单位canvas.appendChild(div)添加一个孩子 divonmousemove鼠标移动事件fillStyle填充样式fillRect填充矩形painting正在画strokeStyle描边
通过 log得到鼠标的位置,然后创建一个div + css 的样式,然后把样式添加到canvas 样式里面
用div 标签会很卡,要选择 canvas
至于怎么用 canvas 画线呢!
canvas 默认是 inline元素,设置宽高都是没有用的,所以要把
#canvas{
display:block;
}
图片上的宽高是会被css样式覆盖的,同样的在canvas 可以写宽高
<canvas id ="canvas width='100' height='100'></canvas>
ctx.fillStyle = 'blue' // 控制它的颜色
ctx.fillRect(`起始的横坐标`,`纵坐标`,`宽度`,`高度`);
canvas 的宽高是一开始就确定了的,就必须一开始写好它的宽度是屏幕的宽度,高度是屏幕的高度
用什么拿呢!
用log拿
console.log(document.body.clienWidth)
canvas.width = documentElement.clientWidth
canvas.height = documentElement.clientHeight
获取canvas ,宽度变成文档的宽度,高度变成文档的高度
ctx.beginPath(); // 先开始
ctx.arc(`圆心`,`半径`,`角度`,2*Math.PI); //然后画
ctx.stroke(); //结束
关于文档链接
移动端
canvas.onmusemove
因为是监听鼠标事件,手机哪有鼠标
根据现在的情况,很难有比较靠谱的方法去检测是否真的是支持 是鼠标或者不支持鼠标
- 还有两种方法:
- 根据屏幕宽度来做
- js检测是否支持触屏 用第二种方法
var isTocuhDevice = 'ontouchstart` in document.documentElement;
console.log('isTouchDevice')
说明它支持触屏,再换成pc 端,也是支持的
if(isTouchDevice){
//如果是触屏设备就做什么
}else{
//如果不是触屏设备就做什么
canvas.onmusedown =()=>{
painting = true
}
canvas.onmusemove = (x) =>{
if(painting === true){
ctx.beginPath(); // 先开始
ctx.arc(`圆心`,`半径`,`角度`,2*Math.PI); //然后画
ctx.stroke(); //结束
}
}
canvas.onmuseup = () => {
painting = false
}
}
if(isTouchDevice){
canvas.ontouchmove = (e)=>{ // 拿到一个事件
console.log(e.tochs[0])
}
}
非常遗憾没有x,y
说明如果有多个事件这里就会有两个touch,每个 tocuh 都会告诉你,这就是不同事件有不同结构
if(isTouchDevice){
canvas.ontouchmove = (e)=>{ // 拿到一个事件
let x = e.tochs[0].clientX
let y = e.tochs[0].clientY
// 这些知识在文档是没有的,必须要用 log 方法来获取
console.log(x.y)
ctx.beginPath(); // 先开始
ctx.arc(`圆心`,`半径`,`角度`,2*Math.PI); //然后画
ctx.stroke(); //结束
}
}
要告诉你手机上比想象复杂的多
在微信上访问微信浏览器是有 bug 的,在正常浏览器是没有问题,再有特殊操作浏览器在往下滑东西的时候这个屏幕会跟你动
touch触摸ontouchstart就是开始被摸touch多个手指事件
补充常识: 跟JS 没有关系
在手机上滑的时候一定是一个手指,会不会两个手指滑,所以 e 包括多个手指事件