Canvas and DOM in perfect Harmony
Tags: javascript, gamedev, showdev, webdev
Published: 2021-09-12 16:35:31

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.

```js
    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;
    }
```
Note how easy it is to insert a canvas element in each cell, thanks to DML

You can play with it here : [Sliding Puzzle](https://flems.io/#0=N4IgtglgJlA2CmIBcAGAdAZgwGhAZ3gQGMAXeKZENACxLFhFyIHsA7PZhSl2WAQwAOBCrjxEATpwZIA2imwYATADZMATg1qMADjXKALNv36AurgBmEBHmQzQrPmERIqteoxAtWZb5QA8brAABPysAOYAvAA6IFDwMQB8UaxBQQHwfFBJKWlOJHxBRNR84gQk0SAAriTmALTaicmpqX4kECQICW0d8H4A9N2dTc1+eQUOThUAbhDwAO4CzOIkMYVsPuUxc9Ak1BFxM0TwtdtQu9hBEKztEHywtWJ38BEAjGgojTktYuIQAiRBPDiIgVWgkIRIPp9eDmAR8MLwNBxPoAEQAsgAZVGYgD61GYTjhCL6sAgACNsRjapBWGgAFZ4RL9H5-EjZFp9agZLLDPxk5hQACeCSCyV5LP+IuGUxKQSgzCm8CCESCrHmQQAkmB4fAABQASgA3MMofLFWggURlaKQGCIVC5o76XNmALFSQ0Cw0JUANZ9Ba1LwbPqVASwZiZPB9RQoF7aPooePysKBqSCAj0gR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