您的当前位置:首页正文

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

来源:华佗小知识

demo 实现一共分为四个部分:

以下是第一部分:


Canvas 绘画应用

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

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

采取的CSS规范

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

基础目录结构

目录结构

基础功能实现

☞ 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;
}

② 设置绘图板(cvaConfig.js)

 // 属性设置
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;
    }
}

✈ Github:

使用方式:

npm install
npm start
image.png

✎ 参考: