删除新标记上的上一个标记

时间:2016-04-18 20:14:38

标签: javascript html5 canvas

我目前正在为我的大学图书馆制作地图/位置共享网站。我使用HTML5 canvas元素来显示地图,并允许在您单击的位置放置标记。

目前,如果您错过了点击,则必须单击清除按钮以清除本地存储并重新加载页面以删除标记以便能够放置新标记。当你点击其他地方时,我宁愿有办法清除之前的标记,但我似乎无法想到如何去做。此外,如果有一种方法可以清除标记而无需重新加载会很棒的页面。

感谢您提出的任何建议。

您可以看到网站 here

以下是相关的HTML

<div id="wrapper">

<!-- Main -->
<section id="main">
    <h1>Level 5</h1>
    <p>Simply tap your location and then hit share</p>
    <div class="mobileShow">
        On mobile: just drag with one finger around the box below and then tap your location.
    </div>
    <div class="container" id="container">
        <canvas id="mapCan" width="868px" height="828px"></canvas>
    </div>
    <div id="mapButtons" style="padding-top: 1%; padding-bottom: 1%;">

        <input id="Clr1" type="button" onclick="clearMark()" value="Clear">
        <input id="Shr1" type="button" onclick="saveImg() " value="Share">
        <form method="post" accept-charset="utf-8" name="form1">
            <input name="hidden_data" id='hidden_data' type="hidden"/>
        </form>
    </div>
    <h1><a href="index.html">Back To Main Page</a></h1>

这是相关的JS

window.onload = function () {
    window.localStorage.clear();
    var mapCan = document.getElementById('mapCan');
    var share = document.getElementById('Shr1');
    var clear = document.getElementById('Clr1');

    var img = new Image(),
            count = 0;
    img.src = '../images/Maps/L5.png';


    img.onload = function draw() {
        renderMarks();

        mapCan.onclick = function (e) {

            var rect = mapCan.getBoundingClientRect(),
                    x = e.clientX - rect.left,
                    y = e.clientY - rect.top;
            if (count == 0) {
                addMark(x, y);
                renderMarks();
            } else {
                renderMarks();
            }
        }
    }
    function renderMarks() {
        var ctx = mapCan.getContext('2d'),
                w = mapCan.width,
                h = mapCan.height;
        ctx.drawImage(img, 0, 0, w, h);
        var marks = localStorage.getItem('marks'),
                i = 0;
        console.log(marks);
        if (marks !== null) {

            marks = JSON.parse(marks);

            ctx.strokeStyle = '#f00';
            ctx.lineWidth = 3;

            for (; i < marks.length; i++) {
                ctx.beginPath();
                ctx.arc(marks[i][0], marks[i][1], 10, 0, 2 * Math.PI);
                ctx.stroke();
            }
        }
    }

    function addMark(x, y) {

        var marks = JSON.parse(localStorage.getItem('marks') || '[]');
        marks.push([x, y]);
        localStorage.setItem('marks', JSON.stringify(marks));
        count++;
    }

    clear.onclick = function clearMark() {
        window.localStorage.clear();
        location.reload(true);
    }

0 个答案:

没有答案