动态添加工具提示以在HTML画布上移动形状

时间:2017-02-08 12:18:49

标签: javascript html canvas tooltip

在这里,我正在研究在HTML画布中绘制形状并通过设置setInterval函数来移动它们。但我需要动态地为每个形状添加工具提示。无法找到确切的解决方案。请帮忙。请查看我的https://www.betternet.co/

function Shapes(x, y, w, color, shape) 
{
    this.x = x;
    this.y = y;
    this.w = w;
    this.color = color;

    this.anim = function() 
    {
        if (this.x < context.canvas.width) {
            if(shape=="square"){
            this.x += 5;
            context.fillStyle = this.color;
            context.strokeStyle = "red";
            context.lineWidth = 3;
            context.fillRect(this.x,this.y,this.w,this.w);
            context.strokeRect(this.x,this.y,this.w,this.w);
            }else if(shape=="triangle"){

                        this.x += 1;
                        context.beginPath();
                        context.moveTo(this.x, this.x-20);
                    context.lineTo(this.x+60, this.x);
                    context.lineTo(this.x+25, this.x+50);
                        context.closePath();
                        context.fillStyle = "blue";
                        context.fill();
                    }else if(shape=="circle"){
                            this.x += 1;
                            context.beginPath();
                            context.arc(this.x, this.y, 25, 0, 2 * Math.PI, false);
                            context.fillStyle = "green";
                            context.fill();
                            context.strokeStyle = '#003300';
                            context.stroke();
                    }
            if(shape=="rectangle"){
                            this.x += 1;
                    context.fillStyle = "#ff6600";
                    context.strokeStyle = "blue";
                    context.lineWidth = 3;
                    context.fillRect(this.x,this.y,this.w+30,this.w);
                    context.strokeRect(this.x,this.y,this.w+30,this.w);
            }
        }
        else this.x=-this.w;
    }
}

function init() {
    canvas = document.getElementById('testCanvas');
    context = canvas.getContext("2d");
    var max=200, min=0;

    var shapes =["square", "circle", "triangle", "rectangle"]

    var objects =[];

    for(var i=0;i<shapes.length;i++){
            var rectY = Math.floor(Math.random()*(max-min+1)+min);
            var rect1 = new Shapes(0, rectY, 40, "blue", shapes[i]);
            //var rect2 = new Shapes(0, 100, 40, "blue");
            objects.push(rect1);
        }

    setInterval(function(){
        blank();
        for(rect in objects){
            objects[rect].anim();
        }
    }, 30);
}

function blank() {
    context.fillStyle = "#ebebe0";
    context.fillRect(0,0,context.canvas.width, context.canvas.height);
}


init()

0 个答案:

没有答案