DEV Community

Cover image for Canvas and DOM in perfect Harmony

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);  
          var canvas = canvas2D({width:"100px",height:"100px"}); 
        cell.onclick =  () =>   {this.moveCell(cell)};
        return cell;

      // empty cell customisation 
      this.emptyCell = this.cells[15]; = '0.25' = 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

Discussion (2)

efpage profile image

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

artydev profile image
artydev Author

Thank you Eckehard :-)