简体   繁体   中英

Incremental Integer in JCanvas text

I'm trying to increment text value everytime I click on the rectangle. What am I doing wrong ? I don't understand because the call to my var works in drawText but doesn't in setLayer. I looked at "setLayer" source code, who's working with '+=' syntax, but text is a String var and I don't want to make String concatenation.

value=1
$('canvas').drawText({
  name: 'count',
  fillStyle: '#0f0',
  x: 20, y: 20,
  fontSize: 22,
  fontFamily: 'Verdana, sans-serif',
  text: value
})
.drawRect({
  strokeStyle: '#000',
  fillStyle: '#ccc',
  x: 20, y: 50,
  width: 20,
  height: 20,
  layer: true,
  click: function(layer) {
    // Spin
    $(this).animateLayer(layer, {
      rotate: '+=180'
    });
    v=parseInt(value);
    $(this).setLayer('count',{
        text: value+1 // TRYING to increment over here
    });
  }})

Removing and recreating layers will make jCanvas unhappy. A much better solution would be to use setLayer() by parsing the current value to a number, incrementing that value, and passing it to the method:

$('canvas').drawText({
    layer: true,
    name: 'count',
    fillStyle: '#0f0',
    x: 20, y: 20,
    fontSize: 22,
    fontFamily: 'Verdana, sans-serif',
    text: '1'
})
.drawRect({
    strokeStyle: '#000',
    fillStyle: '#ccc',
    x: 20, y: 50,
    width: 20,
    height: 20,
    layer: true,
    click: function(layer) {
        var $canvas = $(this),
            countLayer = $canvas.getLayer('count');
        // Spin
        $canvas.animateLayer(layer, {
          rotate: '+=180'
        });
        $canvas.setLayer(countLayer,{
            text: parseFloat(countLayer.text) + 1
        });
    }
});

I found a workaround removing the layer and creating a new one at the same place.

 function updateCount(param) {
  $('canvas').removeLayer("count")
  .drawText({
  name: 'count',
  fillStyle: '#0f0',
  x: 250, y: 180,
  fontSize: 22,
  fontFamily: 'Verdana, sans-serif',
  text: value,
  layer: true,
  maxWidth: 200
})
  .drawLayers();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM