02Canvas 画板

2018-08-25  本文已影响0人  雄霸是也

1.功能描述

实现画画功能,并可切换画笔颜色、细条粗细。可保存、清空画板。

2.思路

创建画板——》监听鼠标(触屏)事件——》绘制路线

3.具体操作

3.1 创建画板

通过canvas创建画板

<canvas id="xxx" width=300 height=300></canvas>

3.2 监听鼠标(触屏)事件

监听鼠标(触屏)事件,当鼠标按下(触屏)时进行绘画,根据鼠标(手指)移动路线绘制,松开鼠标(手指离屏)时停止绘画。

canvas.ontouchstart = function(aaa){
    var x = aaa.touches[0].clientX;
    var y = aaa.touches[0].clientY;

    using = true;

    if(isEraser){
        context.clearRect(x-5,y-5,10,10);
    } else{
        lastpoint = {"x":x,"y":y};
    }
}

canvas.ontouchmove = function(aaa){
    var x = aaa.touches[0].clientX;
    var y = aaa.touches[0].clientY;

    if(using == false){return;}

    if(isEraser){
        context.clearRect(x-5,y-5,10,10);
    } else{
        var newPoint = {"x":x,"y":y}

        //drawCircle(x,y);
         drawLine(lastPoint.x,lastPoint.y,newPoint.x,newPoint.y);
         lastPoint = newPoint;
    }
}

canvas.ontouchend = function(){
    using = false;
    lastPoint =  {"x":undefined,"y":undefined};
}

3.3 绘制路线

通过点与线的连接,实现绘画功能。

function drawLine(x1,y1,x2,y2){
    context.beginPath();
    context.moveTo(x1,y1);
    context.lineWidth = lineWidth;
    context.lineTo(x2,y2);
    context.stroke();
    context.closePath();
}

4.相关知识点

4.1 js

监听鼠标点击事件

按下去鼠标 document.onmousedown =function(x){console.log(x)}

移动鼠标 document.onmousemove = function(y){console.log(y)}

松开鼠标 document.onmouseup = function(z){console.log(1)}


监听触摸事件(因为手机上没有mouse所以用touch)

开始触摸 canvas.ontouchstart = function(aaa){}

结束触摸 canvas.ontouchend = function(aaa){}

边摸边动 canvas.ontouchmove = function(aaa){}


通过特性检测得知是用mouse还是touch


touch时把当前所有touch事件都存到了touches中,所以从touches[0]中获取坐标


用div画画

首先获取鼠标在视图上的x、y,然后生成1个div,并设置div的样式,最后将div放到画板(div)中。即可打点。

缺点:元素画画只能画点,没办法连线。


用canvas画画

出现第1个点第2个点的时候之间连个线,即mouseDown的时候为第1个点,mouseMove的时候为第2个点。并每次记录上1个点。


获取页面宽高

document.documentElement.clientWidth

document.documentElement.clientHeight


一个按钮只做一件事


让页面缩放

content="width=device-width,minimum-scale=1.0,maximum-scale=1.0"/>


in操作符

varhash = {a:1,b:2,c:3}

‘a’in hash——》true

‘d’in hash——》false

禁止滚动条 overflow:hidden

在移动端让canvas不移动 绝对定位 position:fixed; top:0; left:0;

5.实际成果

上一篇 下一篇

猜你喜欢

热点阅读