canvas事件模拟

2021-03-09  本文已影响0人  aichisuan

一. demo预览

image

二.前置知识

关于canvas事件模拟方式罗列

1. isPointInPath + Path2D API (存在极大的兼容性)

2. 角度法

image

3. 射线法

image

4.像素法

5. 其他...

三. 一些特别注明

1. OffscreenCanvas
2. getImageData

3.正多边形绘制方式

4.五角星绘制方式

5.心绘制方式

6. 关于demo中取名

四.设计思路以及具体代码

import { Widget, Mural } from './canvasEvent'

const Mural = new Mural(canvas对象)

const widget1 = new Widget(options)
const widget2 = new Widget(options)
const widget3 = new Widget(options)

widget1.on('事件名1', callback1)
widget2.on('事件名2', callback2)
widget3.on('事件名3', callback3)
    
Mural.add(widget1) // 如果在widget1上促发事件1 调用callback1
Mural.add(widget2) // 如果在widget2上促发事件2 调用callback2
Mural.add(widget3) // 如果在widget3上促发事件3 调用callback3

这里的widget是很多各种类型所要监听图案实例的总称,所以这里可以设计一个base类,抽离公共方法, 子类继承父类的方法,并且自定义方法形成多种形态. 贴出wiget Base类的代码.

export class Base {

  constructor(props){
    this.id = createId()
    this.listeners = {}
    this.isAnimation = props.isAnimation || false // 这个元素是否需要移动位置,以及是否需要重叠
  }

  draw (){
    throw new Error('this widget not have draw methods')
  }

  on(eventName, listenerFn) {
    if(this.listeners[eventName]){
      this.listeners[eventName].push(listenerFn)
    }else{
      this.listeners[eventName] = [listenerFn]
    }
  }

  getListeners() {
    return this.listeners
  }

  getId(){
    return this.id
  }

  getIsAnimation(){
    return this.isAnimation
  }
}
import { Base } from './Base';
export class Rect extends Base {
  constructor(props) {
    super(props);
    this.options = {
      x: props.x,
      y: props.y,
      width: props.width,
      height: props.height,
      fillColor: props.fillColor || '#fff',
      strokeColor: props.strokeColr || '#000',
      strokeWidth: props.strokeWidth || 1
    };
  }

  draw(ctx, hideCtx) {
    const { x, y, width, height, fillColor, strokeColor, strokeWidth } = this.options;
    ctx.save();
    ctx.beginPath();
    ctx.strokeStyle = strokeColor;
    ctx.lineWidth = strokeWidth;
    ctx.fillStyle = fillColor;
    ctx.rect(x, y, width, height);
    ctx.fill();
    ctx.stroke();
    ctx.restore();
    ....
  }
}

写出Mural代码的架构.
export class Mural {
  constructor(canvas) {
    // canvas 在不同dpr屏幕上的模糊问题
    const dpr = window.devicePixelRatio;
    canvas.width = parseInt(canvas.style.width) * dpr;
    canvas.height = parseInt(canvas.style.height) * dpr;

    this.canvas = canvas;
    this.ctx = this.canvas.getContext('2d');
    this.ctx.scale(dpr, dpr); // 根据dpr 缩放画布

    this.canvas.addEventListener('mousedown', callback);
    this.canvas.addEventListener('mouseup', callback);
    this.canvas.addEventListener('mousemove', callback);
  }

  add(widget) {
    widget.draw(this.ctx);
  }
}

那么怎么通过 this.canvas.addEventListener('事件名', callback); 促发widget.on中的回调函数呢? 于是有下一步代码.

Mural


export class Mural {
  constructor(canvas) {
    // canvas 在不同dpr屏幕上的模糊问题
    const dpr = window.devicePixelRatio;
    canvas.width = parseInt(canvas.style.width) * dpr;
    canvas.height = parseInt(canvas.style.height) * dpr;

    // 如果无法使用这个API可以画在一个隐藏的canvas上
    this.hidecanvas = new OffscreenCanvas(canvas.width, canvas.height);

    this.canvas = canvas;
    this.ctx = this.canvas.getContext('2d');
    this.hideCtx = this.hidecanvas.getContext('2d');
    this.ctx.scale(dpr, dpr); // 根据dpr 缩放画布
    this.hideCtx.scale(dpr, dpr); // 根据dpr 缩放画布
    this.dpr = dpr;

    this.canvas.addEventListener('mousedown', this.handleCreator(ActionTypes.down));
    this.canvas.addEventListener('mouseup', this.handleCreator(ActionTypes.up));
    this.canvas.addEventListener('mousemove', this.handleCreator(ActionTypes.move));

    this.widgets = new Set(); // 将所有的部件放入Set容器中

    this.eventAnglogies = new EventAnglogies();
  }

  add(widget) {
    const id = widget.getId();
    this.eventAnglogies.addListeners(id, widget.getListeners());
    this.widgets.add(id);
    widget.draw(this.ctx, this.hideCtx);
  }

  handleCreator = (type) => (ev) => {
    const x = ev.offsetX;
    const y = ev.offsetY;
    const id = this.getHideId(x, y);
    this.eventAnglogies.addAction({ type, id }, ev);
  };

  getHideId(x, y) {
    const rgba = [ ...this.hideCtx.getImageData(x * this.dpr, y * this.dpr, 1, 1).data ];

    const id = rgbaToId(rgba);

    return this.widgets.has(id) ? id : undefined;
  }
}

Rect

import { idToRgba } from '../lib/helper';
import { Base } from './Base';

export class Rect extends Base {
  constructor(props) {
    super(props);
    this.options = {
      x: props.x,
      y: props.y,
      width: props.width,
      height: props.height,
      fillColor: props.fillColor || '#fff',
      strokeColor: props.strokeColr || '#000',
      strokeWidth: props.strokeWidth || 1
    };
  }

  draw(ctx, hideCtx) {
    const { x, y, width, height, fillColor, strokeColor, strokeWidth } = this.options;
    ctx.save();
    ctx.beginPath();
    ctx.strokeStyle = strokeColor;
    ctx.lineWidth = strokeWidth;
    ctx.fillStyle = fillColor;
    ctx.rect(x, y, width, height);
    ctx.fill();
    ctx.stroke();
    ctx.restore();

    const [ r, g, b, a ] = idToRgba(this.getId());

    hideCtx.save();
    hideCtx.beginPath();
    hideCtx.strokeStyle = `rgba(${r}, ${g}, ${b}, ${a})`;
    hideCtx.fillStyle = `rgba(${r}, ${g}, ${b}, ${a})`;
    hideCtx.rect(x, y, width, height);
    hideCtx.fill();
    hideCtx.stroke();
    hideCtx.restore();
  }
}

helper.js

export const rgbaToId = (rgba) => rgba.join('-');

// 这里最多可以绘制图形 256*256*256个  16,777,216 约1600万个
const idPool = {};

export const createId = () => {
  let id = createOnceId();

  while (idPool[id]) {
    id = createOnceId();
  }
  // console.log(id)
  return id;
};

export const createOnceId = () => Array(3).fill(0).map(() => Math.ceil(Math.random() * 255)).concat(255).join('-');

// 判断两个set容器相等,注意这里只判断字符串类型的set容器
export const equalSet = (a, b)=> [...a].join('') === [...b].join('')

// set容器的差值
export const diffSet = (a, b) => new Set([...a].filter(x => !b.has(x)));

进一步Mural代码

import { EventAnglogies, ActionTypes } from './EventAnglogies';
import { rgbaToId } from './lib/helper';

export class Mural {
  constructor(canvas) {
    // canvas 在不同dpr屏幕上的模糊问题
    const dpr = window.devicePixelRatio;
    canvas.width = parseInt(canvas.style.width) * dpr;
    canvas.height = parseInt(canvas.style.height) * dpr;



    this.canvas = canvas;
    this.ctx = this.canvas.getContext('2d');
    this.ctx.scale(dpr, dpr); // 根据dpr 缩放画布

    // 创建一个隐藏的ctx 如果无法使用这个API可以画在一个隐藏的canvas上
    this.hideCtx = this.createHideCtx(canvas.width, canvas.height, dpr)


    this.dpr = dpr;
    // 需要即时移动的canvas隐藏画布
    this.moveHideCtxMap = new Map()

    this.canvas.addEventListener('mousedown', this.handleCreator(ActionTypes.down));
    this.canvas.addEventListener('mouseup', this.handleCreator(ActionTypes.up));
    this.canvas.addEventListener('mousemove', this.handleCreator(ActionTypes.move));

    this.widgets = new Set(); // 将所有静态部件放入Set容器中
    this.widgetsMap = new Map()

    this.eventAnglogies = new EventAnglogies();
  }

  createHideCtx(width, height, dpr) {
    const hidecanvas = new OffscreenCanvas(width, height);
    const hideCtx = hidecanvas.getContext('2d');
    hideCtx.scale(dpr, dpr);
    return hideCtx
  }


  add(widget, isOld = false) {
    // 这里代表了动画,或者其他,就是事件已经绑定好了,只是一些位置发生改变
    if(isOld){
      this.drawAll(widget)
      return
    }
    const id = widget.getId();
    const isAnimation = widget.getIsAnimation()
    this.eventAnglogies.addListeners(id, widget.getListeners());
    this.widgets.add(id);
    this.widgetsMap.set(id, widget)
    let hideCtx = this.hideCtx

    // 如果该widget需要移动的话或者覆盖, 存在的话加上,不存在的话new, 防止用户多次add
    if (isAnimation) {
      if (this.moveHideCtxMap.get(id)) hideCtx = this.moveHideCtxMap.get(id)
      else {
        hideCtx = this.createHideCtx(this.canvas.width, this.canvas.height, this.dpr)
        this.moveHideCtxMap.set(id, hideCtx)
      }
    }

    widget.draw(this.ctx, hideCtx);
  }

  handleCreator = (type) => (ev) => {
    const x = ev.offsetX;
    const y = ev.offsetY;
    const idSet = this.getHideIdSet(x, y);
    // 不能在这里遍历idSet
    this.eventAnglogies.dispatchAction({ type, idSet }, ev)
  };

  getHideIdSet(x, y) {
    const rgba = [...this.hideCtx.getImageData(x * this.dpr, y * this.dpr, 1, 1).data];
    const staticRgbaToId = rgbaToId(rgba);

    const staticId = this.widgets.has(staticRgbaToId) ? staticRgbaToId :[]

    let animationId = []
    
    this.moveHideCtxMap.forEach((hCtx, id)=>{
      if(rgbaToId([...hCtx.getImageData(x * this.dpr, y * this.dpr, 1, 1).data]) === id){
        animationId.push(id)
      }
    })
    // 获取到所有当前位置的关于动静态id的组合
    return new Set(animationId.concat(staticId))
  }

  // 产生动画重绘所有的图案
  drawAll(moveWidget){
    // 清空视口画布
    this.ctx.clearRect(0, 0 , this.canvas.height, this.canvas.width)
    this.widgetsMap.forEach((widget, id)=>{
      const hideCtx = this.moveHideCtxMap.get(id) || this.hideCtx
      // 如果不是当前widget 直接画,如果是当前widget 清空隐藏的Rect
      // 因为重新draw之后又会有一次hideCtx记录
      if(moveWidget !== widget) widget.draw(this.ctx, hideCtx);
      else hideCtx.clearRect(0, 0 , this.canvas.height, this.canvas.width)
    })
    const moveId = moveWidget.getId();
    const moveCtx = this.moveHideCtxMap.get(moveId)
    moveWidget.draw(this.ctx, moveCtx)
  }
}

EventAnglogies.js

import { equalSet, diffSet } from './lib/helper'

export const ActionTypes = {
  down: 'down',
  up: 'up',
  move: 'move'
};

export const EventNames = {
  click: 'click',
  mousedown: 'mousedown',
  mousemove: 'mousemove',
  mouseup: 'mouseup',
  mouseenter: 'mouseenter',
  mouseleave: 'mouseleave'
};

export class EventAnglogies {
  listenersMap = {};
  lastDownIdSet = new Set(); // 最后一个按下的一堆idSet
  lastMoveIdSet = new Set(); // move的idSet

  dispatchAction(action, ev) {

    const { type, idSet } = action;
    
    if (type === ActionTypes.move) {
      // mousemove
      this.fire(idSet, EventNames.mousemove, ev);

      // mouseenter
      const enterSet = diffSet(idSet, this.lastMoveIdSet)
      enterSet.size && this.fire(enterSet, EventNames.mouseenter, ev)

      // mouseleave
      const leaveSet = diffSet(this.lastMoveIdSet, idSet)
      leaveSet && this.fire(leaveSet, EventNames.mouseleave, ev)
    }

    // mousedown
    if (type === ActionTypes.down) {
      this.fire(idSet, EventNames.mousedown, ev);
    }

    // mouseup
    if (type === ActionTypes.up) {
      this.fire(idSet, EventNames.mouseup, ev);
    }

    // click
    if (type === ActionTypes.up && equalSet(this.lastDownIdSet, idSet)) {
      this.fire(idSet, EventNames.click, ev);
    }

    if (type === ActionTypes.move) this.lastMoveIdSet = action.idSet;
    else if (type === ActionTypes.down) this.lastDownIdSet = action.idSet;
  }

  addListeners(id, listeners) {
    this.listenersMap[id] = listeners;
  }

  fire(idSet, eventName, ev) {
    idSet.forEach(id => {
      if (this.listenersMap[id] && this.listenersMap[id][eventName]) {
        this.listenersMap[id][eventName].forEach((listener) => listener(ev));
      }
    })
  }
}

到此为止步,再回头看看预览的demo 图示

image

这里再贴出入口文件的代码,就一目了然了。

import { Circle, Mural, Rect, Heart, FivePointedStar, Polygon } from './canvasEvent';
import { EventNames } from './canvasEvent/EventAnglogies';

const canvas = document.querySelector('#canvas');

const mural = new Mural(canvas);

const circle = new Circle({
  x: 350,
  y: 50,
  radius: 50,
  fillColor: 'pink'
});

const rect = new Rect({
  x: 10,
  y: 10,
  width: 120,
  height: 60,
  fillColor: 'yellow'
});

const heart = new Heart({
  x: 200,
  y: 50,
  heartA: 3,
  fillColor: 'red'
});

const polygon = new Polygon({
  x:500,
  y: 50,
  n: 8,
  size: 50,
  fillColor: 'blue',
  isAnimation: true
})

const fivePoint = new FivePointedStar({
  x: 50,
  y: 200,
  minSize: 25,
  maxSize: 50,
  fillColor: 'red',
  isAnimation: true
});

rect.on(EventNames.click, () => {
  alert('点击了矩形');
});

heart.on(EventNames.mouseenter, () => {
  console.log('进入心');
});
heart.on(EventNames.mouseleave, () => {
  console.log('离开心');
});

circle.on(EventNames.click, () => {
  alert('点击了圆');
});

circle.on(EventNames.mouseleave, () => {
  console.log('离开了圆形');
});


polygon.on(EventNames.mousedown, (e) => {
  console.log(polygon)
  let baseX = e.pageX
  let baseY = e.pageY
  document.onmousemove = (event) =>{
    const moveX = event.pageX - baseX
    const moveY = event.pageY - baseY
    baseX = event.pageX
    baseY = event.pageY
    polygon.options.x = polygon.options.x + moveX
    polygon.options.y = polygon.options.y + moveY
    mural.add(polygon);
  }
})

fivePoint.on(EventNames.mouseenter, () => {
  console.log('进入了五角星');
});

fivePoint.on(EventNames.mouseleave, () => {
  console.log('离开了五角星');
});

fivePoint.on(EventNames.mousedown, (e) => {
  let baseX = e.pageX
  let baseY = e.pageY
  document.onmousemove = (event) =>{
    const moveX = event.pageX - baseX
    const moveY = event.pageY - baseY
    baseX = event.pageX
    baseY = event.pageY
    fivePoint.options.x = fivePoint.options.x + moveX
    fivePoint.options.y = fivePoint.options.y + moveY
    mural.add(fivePoint, true);
  }
})


document.addEventListener('mouseup', function() {
  document.onmousemove = null
}, false)

mural.add(circle);
mural.add(rect);
mural.add(heart);
mural.add(polygon);
mural.add(fivePoint);

以上总共解决了canvas事件模拟:

  1. mousedown事件
  2. mouseup事件
  3. mouseenter事件
  4. mousemove事件
  5. click事件
  6. 多个图案重叠事件监听
  7. 图片变动后的事件监听
到这里,canvas事件模拟像素点法就介绍到这,具体业务,要根据实际业务中方案选择。

五.未做的一些兼容性处理

若有不明之处, github地址, 可运行demo调试。

参考文档

上一篇 下一篇

猜你喜欢

热点阅读