0

I have a canvas script, with a dynamic of data. I want to add a link to share the website to facebook:

https://gyazo.com/c1fd1fe956fddba27b48907dc0e9de0a

The icons are part of the image I have not generated them via canvas, now if I listen for a click for co-ords it won't work because it'll look for clicks on the first canvas part aswell.... How can I go about making those icons part of the image clickable....

Part that makes the menu:

ig.module("game.entities.gameover").requires("impact.entity", "game.entities.button-gameover").defines(function() {
var b = new ig.Timer;
EntityGameover = ig.Entity.extend({
    size: {
        x: 302,
        y: 355
    },
    type: ig.Entity.TYPE.B,
    animSheet: new ig.AnimationSheet("media/graphics/game/gameover.png", 301, 352),
    zIndex: 900,
    globalAlpha: 0.1,
    closeDialogue: !0,

    init: function(c, d, g) {
        this.parent(c, d, g);
        this.addAnim("idle", 1, [0]);
        this.currentAnim = this.anims.idle;
        this.tween({
            pos: {
                x: 89,
                y: 120
            }
        }, 0.5, {
            easing: ig.Tween.Easing.Back.EaseInOut
        }).start();
        this.storage = new ig.Storage;
        this.storage.initUnset("highscore-CTF", 0);
        this.storage.initUnset("highscore-CTF2", 0);
        this.storage.initUnset("highscore-CTF3", 0);
        ig.global.score > this.storage.get("highscore-CTF") ? (this.storage.set("highscore-CTF3", this.storage.get("highscore-CTF2")), this.storage.set("highscore-CTF2", this.storage.get("highscore-CTF")), this.storage.set("highscore-CTF", ig.global.score), this.storage.initUnset("highscore-CTF2", 0), this.storage.initUnset("highscore-CTF3", 0)) : ig.global.score > this.storage.get("highscore-CTF2") ?
            (this.storage.set("highscore-CTF3", this.storage.get("highscore-CTF2")), this.storage.set("highscore-CTF2", ig.global.score), this.storage.initUnset("highscore-CTF2", 0), this.storage.initUnset("highscore-CTF3", 0)) : ig.global.score > this.storage.get("highscore-CTF3") && this.storage.set("highscore-CTF3", ig.global.score);
        this.storage.initUnset("total-CTF", 0);
        this.storage.set("total-CTF", this.storage.get("total-CTF") + ig.global.score);
        ig.game.spawnEntity(EntityButtonGameover, 23, 700, {
            buttonID: 1
        });
        ig.game.spawnEntity(EntityButtonGameover,
            220, 700, {
                buttonID: 2
            });
        ig.game.spawnEntity(EntityButtonGameover, 390, 700, {
            buttonID: 3
        });
        b.set(0.3)
    },
    update: function() {
        this.parent()
    },
    draw: function() {
        this.ctx = ig.system.context;
        this.closeDialogue ? (this.ctx.save(), this.ctx.fillStyle = "#000000", this.ctx.globalAlpha = this.globalAlpha, this.ctx.fillRect(0, 0, 480, 640), this.ctx.restore(), this.globalAlpha = 0.7 <= this.globalAlpha ? 0.7 : this.globalAlpha + 0.01) : this.closeDialogue || (this.ctx.save(), this.ctx.fillStyle = "#000000", this.ctx.globalAlpha = this.globalAlpha, this.ctx.fillRect(0,
            0, 480, 640), this.ctx.restore(), this.globalAlpha = 0.1 >= this.globalAlpha ? 0 : this.globalAlpha - 0.05);
        this.parent();
        this.ctx.font = "30px happy-hell";
        this.ctx.fillStyle = "#5b2a0b";
        this.ctx.textAlign = "center";
        this.ctx.fillText(_STRINGS.UI.Best, this.pos.x + 70, this.pos.y + 180);
        this.ctx.fillText(_STRINGS.UI.Score, this.pos.x + 70, this.pos.y + 260);




        //share
        this.ctx.font = "30px happy-hell";
        this.ctx.fillStyle = "#ffffff";
        this.ctx.textAlign = "left";
        this.ctx.fillText(this.storage.getInt("highscore-CTF"), this.pos.x + 140, this.pos.y + 180);
        this.ctx.fillText(ig.global.score, this.pos.x + 140, this.pos.y + 260)
    },
    closeDialogueFunc: function() {
        this.closeDialogue && (this.tween({
            pos: {
                x: 89,
                y: -600
            }
        }, 0.5, {
            easing: ig.Tween.Easing.Back.EaseInOut
        }).start(), this.closeDialogue = !1)
    }
})

});

markE
  • 102,905
  • 11
  • 164
  • 176
  • 2
    Listen for click events on the canvas. If the mouse is over the image-icon then `window.open` to your desired url. – markE May 20 '16 at 04:24
  • What do you mean by "now if I listen for a click for coords it won't work because it'll look for clicks on the first canvas part aswell"? – ShuberFu May 23 '16 at 19:00
  • @randommman Could you post all the scripts that are required to run this code (including the HTML)? – jehna1 May 24 '16 at 21:11
  • 1
    I would prefer using the DOM for a menu overlay, e.g. a transparent
    containing your
    – le_m May 26 '16 at 00:51

3 Answers3

1

A simple, versatile way to add menus to canvas graphics is to simply overlay an absolutely positioned DOM structure. Your browser has already all event handling build-in, there is no need to reinvent the wheel.

var canvas = document.getElementById('canvas'),
  ctx = canvas.getContext('2d');

ctx.fillStyle = 'rgb(0, 155, 255)';
ctx.fillRect(0, 0, canvas.width, canvas.height)
#container {
  position: relative;
  display: inline-block;
}
#menu {
  position: absolute;
  text-align: center;
  width: 100%;
  height: 100%;
  top: 0;
  left: 0;
}
#menu a {
  padding: 15px;
  font-size: 50px;
  line-height: 100px;
  color: black;
  text-shadow: 2px 2px 5px white;
}
#menu a:hover {
  color: white;
}
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.6.3/css/font-awesome.min.css" rel="stylesheet" />

<div id='container'>
  <canvas id='canvas' width='400' height='100'></canvas>
  <div id='menu'>
    <a href='http://facebook.com'><i class='fa fa-facebook-official'></i></a>
    <a href='http://twitter.com'><i class='fa fa-twitter'></i></a>
    <a href='http://whatsapp.com'><i class='fa fa-whatsapp'></i></a>
  </div>
</div>

Your browser is capable of rendering such overlay menus very quickly. You should use CSS to style your overlay menu links or buttons.

le_m
  • 19,302
  • 9
  • 64
  • 74
  • This is not the answer he was asking for, but It is a nice solution too, at least, the easiest one to deal with this problem. – Jose Serodio May 30 '16 at 19:24
0

You have several operations in this case.

Option 1: You'll need to remember the "bounding area" of the three buttons. Anytime the canvas receives a "click", get the click position (How do I get the coordinates of a mouse click on a canvas element?). Once you get the click position. Detect if said click occurs within the bounding area of the button. If it does, use window.open to go there.

Option 2: Similar to Option 1, but instead of remembering a "bounding area", create a separate hidden canvas of the same size as your image with the backgrounds black ('#000000') and the button given distinctive colors (for example, red for Facebook, green for Twitter, and blue for Hangout?). Then, similar to Option 1, get the click position relative to the canvas. Then use ctx.getImageData(sx, sy, sw, sh) on the context of the hidden canvas layer. If the value you get back is red, then user clicked on Facebook, if green, Twitter, and if blue, Hangout.

Community
  • 1
  • 1
ShuberFu
  • 689
  • 3
  • 15
0

I have managed to click on a certain element in a canvas.

I have tried to explain with comments what it does. I have made 3 limits as shown in the image below. image with limits

And I'm comparing only with x value, if it's in between these limits. It can be more complex so getCursorPosition() method returns an object with x and y components, just in case if you need to make more comparisons.

https://jsfiddle.net/_jserodio/asa10pye/

    var canvas;
    var ctx;

    // first get your canvas
    canvas = document.getElementById('canvas');
    canvas.width = 253;
    canvas.heigth = 68;

    // assign the context
    ctx = canvas.getContext("2d");

    // asign click event to the canvas
    addEventListener("click", listener, false);

    function listener(e) {
      // if you have 3 buttons
      var position = getCursorPosition(e);

      var limit1 = canvas.width / 3;
      //console.log("limit1: " + limit1);
      var limit2 = canvas.width * 2 / 3;
      //console.log("limit2: " + limit2);
      var limit3 = canvas.width;
      //console.log("limit3: " + limit3);

      if (position.x < limit1) {
        console.log("go to facebook");
        //window.open("http://www.facebook.com");
      } else if (position.x < limit2) {
        console.log("go to twitter");
        //window.open("http://www.twitter.com");
      } else if (position.x < limit3) {
        console.log("go to whatsapp");
        //window.open("http://www.whatsapp.com");
      }

      //console.log("\nx" + position.x);
      //console.log("y" + position.y);
    }

    function getCursorPosition(event) {
      var rect = canvas.getBoundingClientRect();
      var x = event.clientX - rect.left;
      var y = event.clientY - rect.top;
      var data = {
        x: x,
        y: y
      };
      return data;
    }

    // load image from data url
    var imageObj = new Image();
    imageObj.onload = function() {
      ctx.drawImage(this, 0, 0);
    };

    imageObj.src = 'https://justpaste.it/files/justpaste/d307/a11791570/file1.png';
<canvas id='canvas' width="253" height="68">

</canvas>

Bonus!
Here you have a demo I made using this. demo (Draughts/checkers).
You can check the entire code here if you want.

Jose Serodio
  • 1,390
  • 3
  • 17
  • 31
  • Bounty is ending in _23 minutes_, I spent like _2 hours_ to make this example work as easy as possible, but It was fun anyway. I enjoyed this. – Jose Serodio May 30 '16 at 18:28