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

这周开始研究 WebGL,发现它是通过 Canvas 来定义网页上的绘图区域的,嗯,还是得回顾一下 Canvas 基础知识了, 然后就找到了自己研究生时期写的 Canvas 绘图 demo(都快忘了......)。很感谢当时的自己写了详细的实现文档,最早发表在博客园上:开发Canvas 绘画应用,博客园差不多被已经被自己废弃了,还是搬过来吧,顺便再温故一下~٩(๑❛ᴗ❛๑)۶

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

开发Canvas 绘画应用(一):搭好框架
开发Canvas 绘画应用(二):实现绘画
开发Canvas 绘画应用(三):实现对照绘画
开发Canvas 绘画应用(四):实现拖拽绘画

以下是第一部分:


Canvas 绘画应用

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

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

采取的CSS规范

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

基础目录结构

目录结构

基础功能实现

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

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

✈ Github:paintApp

使用方式:

npm install
npm start

然后在浏览器中输入 http://localhost:8080,按F12,采用移动端模式进行访问:

image.png

✎ 参考:

HTML5实例教程——创意画板
使用html5 canvas制作涂鸦画板
JS | 移动端“刮刮卡式”蒙层画板 Canvas

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。