DEV Community

Cover image for Canvas and DOM in perfect Harmony
artydev
artydev

Posted on

Canvas and DOM in perfect Harmony

DML is a library which provides nice wrappers around DOM API.
One of this wrapper is canvas2D.

In my sliding game, here is how I fill each cell with fractions of the image.

    createCells () {
      // fills cells array with cell element
      this.cells = [...Array(16)].map((_, i) => { 
        let y = Math.trunc(i/4);
        let x = i % 4;
        let options = {
          style : this.cssCell,
          ["data-pos"] : i, ["data-curpos"] : i,
          ["data-dx"] : 0, ["data-dy"] : 0
        }
        let cell = create("div", options);  
        selectBase(cell)
          var canvas = canvas2D({width:"100px",height:"100px"}); 
          canvas.ctx.drawImage(dove,100*x,100*y,100,100,0,0,100,100);  
        unselectBase() 
        cell.onclick =  () =>   {this.moveCell(cell)};
        return cell;
      });

      // empty cell customisation 
      this.emptyCell = this.cells[15];
      this.emptyCell.style.opacity = '0.25'
      this.emptyCell.style.zIndex = 0;
    }
Enter fullscreen mode Exit fullscreen mode

Note how easy it is to insert a canvas element in each cell, thanks to DML

You can play with it here : Sliding Puzzle

Top comments (2)

Collapse
 
efpage profile image
Eckehard

Great! Working on the DOM with objects is real fun. The DOM is stateful and so are objects. Connecting both makes life easy!

Collapse
 
artydev profile image
artydev

Thank you Eckehard :-)