开发Canvas 绘画应用(一):搭好框架

毕业汪今年要毕业啦,毕设做的是三维模型草图检索,年前将算法移植到移动端做了一个小应用(利用nodejs搭的服务),正好也趁此机会可以将前端的 Canvas 好好学一下~~毕设差不多做完了,现将思路和代码进行回顾整理,希望以最简单的方式将核心前端部分总结并呈现。

Canvas 绘画应用

采用 webpackES6HTML5jQuery 构建,利用了移动端的触摸和手势事件,结合 Canvas,实现在移动端的绘画功能。

先从简单的小绘图功能开始实现,后面有新的功能进行迭代实现。

采取的CSS规范

  • 规范参考
  • OOCSS:结构(structure)与表现(skin)分离,容器(container)与内容(content)分离
  • BEM:类似于组件化的概念,独立的元素搭积木拼接

基础目录结构

  • paintApp/
    • asset/
      • css/
      • img/
    • src/
      • common/
      • component/
      • app.js
    • index.html
    • package.json
    • webpack.config.js

基础功能实现

☞ index.html

<canvas class="painter" id="js-cva">A drawing of something</canvas>

☞ painter.js

① 获取canvas及上下文

// 初始化选择器
initSelectors() {
    this.cva = document.getElementById('js-cva');
    this.ctx = this.cva.getContext('2d');

    return this;
}

② 设置绘图板

// 属性设置
setConfig() {
    this.config = {
        cvaW: 800,
        cvaH: 600,
        cvaBg: '#fff',
        lineWidth: 2,
        lineJoin: 'round',
        strokeStyle: 'red'
    };

    return this;
}

// 画板宽高设置
// 注意此处不能在 css 中设置,像素会失真,会导致不能获取正确的坐标
setCvaWH() {
    this.cva.setAttribute('width', this.config.cvaW);
    this.cva.setAttribute('height', this.config.cvaH);

    return this;
}

// 画板背景设置
setCvaBg() {
    this.ctx.fillStyle = this.config.cvaBg;
    this.ctx.fillRect(0, 0, this.config.cvaW, this.config.cvaH);

    return this;
}

// 画笔设置
setPen() {
    this.ctx.lineWidth = this.config.lineWidth;
    this.ctx.lineJoin = this.config.lineJoin;
    this.ctx.strokeStyle = this.config.strokeStyle;

    return this;
}

设置样式均在 this.ctx 上下文中设置,如 fillStylefillRectlineWidthlineJoinstrokeStyle 等。

③ 监听触摸事件

initEvents() {
    this._touchListen('touchstart');
    this._touchListen('touchmove');
    this._touchListen('touchend');
}

_touchListen(event) {
    this.cva.addEventListener(event, $.proxy(this.touchF, this), false);
}

移动端的触摸事件如下(摘自《JavaScript 高级程序设计》):

  • touchstart:当手指触摸屏幕时触发;即使有一个手指放在了屏幕上也触发。
  • touchmove:当手指在屏幕上滑动时连续地触发。在这个事件发生期间,调用 preventDefault() 可以阻止滚动
  • touchend:当手指东屏幕上移开时触发。
  • toucncancle:当系统停止跟踪触摸时触发。关于此事件的确切触发时间,文档中没有明确说明。

④ 事件处理函数(★重点)

touchF(e) {
    e.preventDefault();	// 阻止浏览器默认行为

    switch (e.type) {
        case 'touchstart':

            break;
        case 'touchmove':

            break;
        case 'touchend':

            break;
    }
}

基础框架有了,事件监听也实现了,接下来就是获取触摸点的坐标,实现绘画功能了,请继续阅读 开发Canvas绘画应用(二):实现绘画

✈ Github:paintApp

✎ 参考:

HTML5实例教程——创意画板

使用html5 canvas制作涂鸦画板

JS | 移动端“刮刮卡式”蒙层画板 Canvas


posted on 2017-03-27 22:12  Ruth92  阅读(2404)  评论(0编辑  收藏  举报

导航