简体   繁体   中英

creating multiple links on html5 canvas

I am trying to create a map with several locations using html5 canvas. I want each location to be a link to another web page. Currently I am able to get only one link working. I am trying to loop through the locations, there are ~15 locations with individual links. This is the code that I have been trying to use but it will loop through but only the last in the loop with have a link.

I have only started to use html5 canvas and javascript recently. This code was taken from a solution online and adapted to what I want.

        link = ["websitelink1", "websitelink2", ... etc];
        links = [[x_coord1,y_coord1,width1,height1],[x_coord2,y_coord2,width2,height2], ... etc]
        canvas.addEventListener("mousemove", on_mousemove, false);
        canvas.addEventListener("click", on_click, false);
        inlink = "";

        function on_mousemove (ev) {
            var mouse_x, mouse_y;

            // Get the mouse position relative to the canvas element.
            if (ev.layerX || ev.layerX) { //for firefox
                mouse_x = ev.layerX;
                mouse_y = ev.layerY;
            }
            mouse_x-=canvas.offsetLeft;
            mouse_y-=canvas.offsetTop;

            for(n = links.length - 1; n >= 0; n--) {
                var linkX = parseInt(links[n][0]),
                    linkY = parseInt(links[n][1]),
                    linkwidth = parseInt(links[n][2]),
                    linkheight = parseInt(links[n][3]);
                    linkHref = link[n];

                //is the mouse over the link?
                if(mouse_x >= linkX && mouse_x <= (linkX + linkwidth) && mouse_y >= linkY && mouse_y <= (linkY + linkheight)) {
                    document.body.style.cursor = "pointer";
                    inLink=linkHref;
                }
                else{
                    document.body.style.cursor = "";
                    inLink="";
                }
            }
        }
        function on_click(e) {
            if (inLink != "") {
                window.open(inlink);
            }
        }

I have tried similar code with the similar results.

Thank you for your help.

I can see a couple of problems here.

(1) you reset inLink to "" inside the loop. This means that if you hover over a link, remaining links in the loop will not be hovered over, and will reset inLink to "" - fix = set inLink to "" once , before the loop (you can't hover over more than one link at a time, so it can only be set once inside the loop)

(2) You've inconsistently 'spelt' inLink . - fix = ensure capitalization is the same for all instances of the variable (inLink is different to inlink)

(3) The placement of brackets in the check if you're over a link has the potential to be ambiguous.

(4) By using links.length in the for loop, it needs to be recalculated each time through the loop. A better approach is to read this value once and store it in a temporary variable.

Here's a rough example of the code working just fine, as tested in Chrome (no FF here, unfortunately)

Note: I've also added the break to discontinue the loop if a hovered link is found - there's no need to check the remaining ones in the loop if you find one successfully. (This speeds up execution, while also achieving the same effect as point #1)

Note2: It is faster to iterate through the loop from n-1 to 0, as you had initially done - I just prefer to go forwards.

<!DOCTYPE html>
<html>
<head>
<script>
function byId(e){return document.getElementById(e);}

window.addEventListener('load', onDocLoaded, false);

function onDocLoaded()
{
    outlineLinks();
    byId('can').addEventListener("mousemove", on_mousemove, false);
    // byId('can').addEventListener("click", on_click2, false);
    byId('can').addEventListener("click", on_click, false);
}

// var link = ["websitelink1", "websitelink2"];
var link = ["http://stackoverflow.com/questions/24650947/creating-multiple-links-on-html5-canvas/24652217", "http://stackoverflow.com/"];
var links = [[0,0,100,20],[0,25,100,20]];

var inLink = "";

function outlineLinks()
{
    var canvas = byId('can');
    var ctx = canvas.getContext('2d');

    var i, n = links.length;
    for (i=0; i<n; i++)
        ctx.strokeRect( links[i][0], links[i][1], links[i][2], links[i][3] );
}

function on_mousemove(evt) 
{
    var mouse_x, mouse_y;

    // Get the mouse position relative to the canvas element.
    if (evt.layerX || evt.layerX) 
    { //for firefox
        mouse_x = evt.layerX;
        mouse_y = evt.layerY;
    }
    mouse_x -= this.offsetLeft;
    mouse_y -= this.offsetTop;

    byId('coords').innerHTML = "Mouse Pos: " + mouse_x + "," + mouse_y;

    var n = links.length;
    inLink = "";
    for(i=0; i<n; i++) 
    {
        var linkX = parseInt(links[i][0]),
            linkY = parseInt(links[i][1]),
            linkwidth = parseInt(links[i][2]),
            linkheight = parseInt(links[i][3]);

        //is the mouse over the link?
        if( (mouse_x >= linkX) && (mouse_x <= (linkX + linkwidth)) && (mouse_y >= linkY) && (mouse_y <= (linkY + linkheight)))
        {
            document.body.style.cursor = "pointer";
            inLink = link[i];
            break;
        }
        else{
            document.body.style.cursor = "";
        }
    }
}
function on_click(evt)
{
    if (inLink != "")
        window.open(inLink);
}

function on_click2(evt)
{
    if (inLink != "")
        byId('tgt').innerHTML = "Navigating to: " + inLink;
    else
        byId('tgt').innerHTML = "No link is hovered";
}

</script>
<style>
</style>
</head>
<body>
    <div id='tgt'>&nbsp;</div>
    <div id='coords'>&nbsp;</div>
    <canvas id='can'></canvas>
</body>
</html>

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