Html5画布垂直和水平滚动 [英] Html5 canvas scrolling vertically and horizontally

查看:100
本文介绍了Html5画布垂直和水平滚动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 <!DOCTYPE html> 
< html>
< head>
< style type =text / css>
#canvasOne
{
border:1px纯黑色;
}
< / style>
< script src =http://code.jquery.com/jquery-1.10.2.jstype =text / javascript>< / script>
< / head>
< body>
< div align =center>
< canvas id =canvasOne>
< / canvas>
< / div>

< script type =text / javascript>

var myCanvas = document.getElementById(canvasOne);
var myContext = myCanvas.getContext(2d);

var requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame || window.msRequestAnimationFrame;

init();

var numShapes;
var shapes;
var dragIndex;
var拖动;
var mouseX;
var mouseY;
var dragHoldX;
var dragHoldY;
var timer;
var targetX;
var targetY;
var easeAmount;
var bgColor;
var nodes;
var colorArr;

函数init()
{
myCanvas.width = $(window).width() - 200;
myCanvas.height = $(window).height() - 200;

shapes = [];
nodes = [0; Person; 24828760; Alok Kumar; Gorakhpur;#F44336; 28,
0; Suspect; 04 / Dec / 2016; 4; Suman_Biswas;#3F51B5; 20, 1; Rule; 4; Apparent Means; 3 Parameter;#EEFF41; 20,
0; Policy; 36QA649749; Effectively; Quarterly;#FF9800; 20,3; Product; Pension; Saral Pension; SRPEN;#795548; 20,3; Payment; Check; Realized; Lucknow;#0091EA; 20,
0; Policy; 162348873; Lapsed; Quarterly;#FF9800; 20,6 ;产品;养老金;终身养老金; LLPP;#795548; 20,6;支付;支票;实现; Gorakhpur;#0091EA; 20,
0;政策; 1EQF178639; Lapsed;每月; #FF9800; 20,9; Product; Life; Shield; SHIELDA;#795548; 20,9; Payment; Demand Draft; Realized; Lucknow;#0091EA; 20];

numShapes = nodes.length;

makeShapes();

drawScreen();

myCanvas.addEventListener(mousedown,mouseDownListener,false);


绘图
函数makeShapes()
{
var tempX;
var tempY; (var i = 0; i< numShapes; i ++)


{
var centerX = myCanvas.width / 2;
var centerY = myCanvas.height / 2;

var nodeColor = nodes [i] .split(;)[5];

var nodeRadius =节点[i] .split(;)[6];

var nodeConnect =节点[i] .split(;)[0];

if(i == 0)//圆的中心
{
tempX = centerX
tempY = centerY;
}
else
{
// tempX = Math.random()*(myCanvas.width - tempRadius);
// tempY = Math.random()*(myCanvas.height - tempRadius);

// var x = x0 + r * Math.cos(2 * Math.PI * i / items);
// var y = y0 + r * Math.sin(2 * Math.PI * i / items);


// 250是从中心节点到外部节点的距离,它可以是以度为单位的实际半径
tempX = shapes [nodeConnect] .x + 300 * Math.cos 2 * Math.PI * i / numShapes);
tempY = shapes [nodeConnect] .y + 300 * Math.sin(2 * Math.PI * i / numShapes);
}

tempShape = {x:tempX,y:tempY,rad:nodeRadius,color:nodeColor,text:nodes [i]};

shapes.push(tempShape);
}
}

//绘制形状(直线和圆形)和屏幕

函数drawScreen()
{
myContext.fillStyle =#ffffff;
myContext.fillRect(0,0,myCanvas.width,myCanvas.height);
drawShapes();

$ b $函数drawShapes()
{
// line
for(var i = 1; i< numShapes; i ++)
{
myContext.beginPath();
myContext.strokeStyle =#B2B19D;

var nodeConnect =节点[i] .split(;)[0];

myContext.moveTo(shapes [nodeConnect] .x,shapes [nodeConnect] .y);
myContext.lineTo(shapes [i] .x,shapes [i] .y);
myContext.stroke();


// circle
for(var i = 0; i< numShapes; i ++)
{
myContext.fillStyle = shapes [i ]。颜色;
myContext.beginPath();
myContext.arc(shapes [i] .x,shapes [i] .y,shapes [i] .rad,0,2 * Math.PI,false);
myContext.closePath();
myContext.fill();


$ text
for(var i = 0; i< numShapes; i ++)
{
myContext.beginPath();
myContext.font ='10pt Arial';
myContext.fillStyle ='black';
var textarr = shapes [i] .text.split(;);

myContext.fillText(textarr [1],shapes [i] .x + 30,shapes [i] .y - 24);
/*myContext.fillText(textarr [2],shapes [i] .x + 30,shapes [i] .y + 1);
myContext.fillText(textarr [3],shapes [i] .x + 30,shapes [i] .y + 22);
myContext.fillText(textarr [4],shapes [i] .x + 30,shapes [i] .y + 44); * /
myContext.closePath();
myContext.fill();




$ b //动画

函数mouseDownListener(evt)
{
var highestIndex = -1;

var bRect = myCanvas.getBoundingClientRect();
mouseX =(evt.clientX - bRect.left)*(myCanvas.width / bRect.width);
mouseY =(evt.clientY - bRect.top)*(myCanvas.height / bRect.height);
$ b $ for(var i = 0; i< numShapes; i ++)
{
if(hitTest(shapes [i],mouseX,mouseY))
{
dragging = true;
if(i> highestIndex)
{
dragHoldX = mouseX - shapes [i] .x;
dragHoldY = mouseY - shapes [i] .y;
highestIndex = i;
dragIndex = i;



$ b如果(拖动)
{
window.addEventListener(mousemove,mouseMoveListener,false);
}

myCanvas.removeEventListener(mousedown,mouseDownListener,false);
window.addEventListener(mouseup,mouseUpListener,false);

if(evt.preventDefault)
{
evt.preventDefault;
}

return false;
}

函数mouseMoveListener(evt)
{
var shapeRad = shapes [dragIndex] .rad;

var minX = shapeRad;
var maxX = myCanvas.width - shapeRad;

var minY = shapeRad;
var maxY = myCanvas.height - shapeRad;

//正确获取鼠标位置
var bRect = myCanvas.getBoundingClientRect();
mouseX =(evt.clientX - bRect.left)*(myCanvas.width / bRect.width);
mouseY =(evt.clientY - bRect.top)*(myCanvas.height / bRect.height);

//钳住x和y的位置以防止对象拖出画布
posX = mouseX - dragHoldX;
posX =(posX< minX)? minX:((posX> maxX)?maxX:posX);
posY = mouseY - dragHoldY;
posY =(posY maxY)≠maxY:posY);

形状[dragIndex] .x = posX;
形状[dragIndex] .y = posY;

drawScreen();
}

函数mouseUpListener(evt)
{
myCanvas.addEventListener(mousedown,mouseDownListener,false);
window.removeEventListener(mouseup,mouseUpListener,false);

if(dragging)
{
dragging = false;
window.removeEventListener(mousemove,mouseMoveListener,false);
}
}

函数hitTest(shape,mx,my)
{
var dx = mx - shape.x;
var dy = my - shape.y;

return(dx * dx + dy * dy }

< / script>
< / body>
< / html>




  1. 以下画布动画创建节点和边线。然而,由于
    到空间约束,由于画布
    的高度和宽度,某些节点不可见。即使在画布上添加溢出CSS也无济于事,因为
    i无法滚动。


解决方案

那么你的节点图不适合画布大小?



只需1个命令即可轻松缩小内容以适合可见画布!



context.scale(horizo​​ntalRescale,verticalRescale)命令将缩小您指定的horizo​​ntalRescale& verticalRescale百分比。



重要提示:必须使horizo​​ntalRescale,verticalRescale具有相同的值,否则您的内容将会失真。

使用 context.scale 的好处是,您不必更改任何绘制节点的代码... canvas自动为您缩放所有节点。



例如,此代码会将节点缩小到原始大小的80%:

  var downscaleFactor = 0.80; 

context.scale(downscaleFactor,downscaleFactor);

我不会通过您的200多行代码,而是留给您计算 downscaleFactor


<!DOCTYPE html>
<html>
<head>
    <style type="text/css">
        #canvasOne
        {
            border: 1px solid black;            
        }
    </style>
    <script src="http://code.jquery.com/jquery-1.10.2.js" type="text/javascript"></script>
</head>
<body>
    <div align="center">
        <canvas id="canvasOne">
        </canvas>
    </div>

    <script type="text/javascript">

        var myCanvas = document.getElementById("canvasOne");
        var myContext = myCanvas.getContext("2d");

        var requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame || window.msRequestAnimationFrame;

        init();

        var numShapes;
        var shapes;
        var dragIndex;
        var dragging;
        var mouseX;
        var mouseY;
        var dragHoldX;
        var dragHoldY;
        var timer;
        var targetX;
        var targetY;
        var easeAmount;
        var bgColor;
        var nodes;
        var colorArr;

        function init()
        {
            myCanvas.width = $(window).width() - 200;
            myCanvas.height = $(window).height() - 200;

            shapes = [];
            nodes = ["0;Person;24828760;Alok Kumar;Gorakhpur;#F44336;28",
                     "0;Suspect;04/Dec/2016;4;Suman_Biswas;#3F51B5;20","1;Rule;4;Apparent Means;3 Parameter;#EEFF41;20",
                     "0;Policy;36QA649749;In-Force;Quarterly;#FF9800;20","3;Product;Pension;Saral Pension;SRPEN;#795548;20","3;Payment;Cheque;Realized;Lucknow;#0091EA;20",
                     "0;Policy;162348873;Lapsed;Quarterly;#FF9800;20","6;Product;Pension;Life-Long Pension;LLPP;#795548;20","6;Payment;Cheque;Realized;Gorakhpur;#0091EA;20",
                     "0;Policy;1EQF178639;Lapsed;Monthly;#FF9800;20","9;Product;Life;Shield;SHIELDA;#795548;20","9;Payment;Demand Draft;Realized;Lucknow;#0091EA;20"];                                          

            numShapes = nodes.length;

            makeShapes();

            drawScreen();       

            myCanvas.addEventListener("mousedown", mouseDownListener, false);
        }

        //drawing
        function makeShapes()
        {
            var tempX;
            var tempY;

            for(var i = 0; i < numShapes; i++)
            {                                   
                var centerX = myCanvas.width/2;
                var centerY = myCanvas.height/2;

                var nodeColor = nodes[i].split(";")[5];

                var nodeRadius = nodes[i].split(";")[6];

                var nodeConnect = nodes[i].split(";")[0];

                if(i == 0)//center of circle
                {                   
                    tempX = centerX
                    tempY = centerY;                    
                }
                else
                {
                    //tempX = Math.random() * (myCanvas.width - tempRadius);
                    //tempY = Math.random() * (myCanvas.height - tempRadius);

                    //var x = x0 + r * Math.cos(2 * Math.PI * i / items);
                    //var y = y0 + r * Math.sin(2 * Math.PI * i / items); 


                    //250 is the distance from center node to outside nodes it can be actual radius in degrees
                    tempX = shapes[nodeConnect].x + 300 * Math.cos(2 * Math.PI * i / numShapes);
                    tempY = shapes[nodeConnect].y + 300 * Math.sin(2 * Math.PI * i / numShapes);                                    
                }

                tempShape = {x: tempX, y: tempY, rad: nodeRadius, color: nodeColor, text: nodes[i]};

                shapes.push(tempShape);
            }       
        }

        //drawing both shape (line and circle) and screen

        function drawScreen()
        {
            myContext.fillStyle = "#ffffff";
            myContext.fillRect(0, 0, myCanvas.width, myCanvas.height);
            drawShapes();
        }

        function drawShapes()
        {       
            //line
            for(var i = 1; i < numShapes; i++)
            {
                myContext.beginPath();
                myContext.strokeStyle = "#B2B19D";

                var nodeConnect = nodes[i].split(";")[0];

                myContext.moveTo(shapes[nodeConnect].x, shapes[nodeConnect].y);
                myContext.lineTo(shapes[i].x, shapes[i].y);
                myContext.stroke();
            }

            //circle        
            for(var i = 0; i < numShapes; i++)
            {                           
                myContext.fillStyle = shapes[i].color;
                myContext.beginPath();
                myContext.arc(shapes[i].x, shapes[i].y, shapes[i].rad, 0, 2*Math.PI, false);                
                myContext.closePath();
                myContext.fill();
            }

            //text
            for(var i = 0; i < numShapes; i++)
            {
                myContext.beginPath();          
                myContext.font = '10pt Arial';
                myContext.fillStyle = 'black';
                var textarr = shapes[i].text.split(";");

                myContext.fillText(textarr[1], shapes[i].x + 30, shapes[i].y - 24);
                /*myContext.fillText(textarr[2], shapes[i].x + 30, shapes[i].y + 1);
                myContext.fillText(textarr[3], shapes[i].x + 30, shapes[i].y + 22);
                myContext.fillText(textarr[4], shapes[i].x + 30, shapes[i].y + 44);*/           
                myContext.closePath();
                myContext.fill();
            }


        }

        //animation

        function mouseDownListener(evt)
        {
            var highestIndex = -1;

            var bRect = myCanvas.getBoundingClientRect();
            mouseX = (evt.clientX - bRect.left) * (myCanvas.width/bRect.width);
            mouseY = (evt.clientY - bRect.top) * (myCanvas.height/bRect.height);

            for(var i = 0; i < numShapes; i++)
            {
                if(hitTest(shapes[i], mouseX, mouseY))
                {
                    dragging = true;
                    if(i > highestIndex)
                    {
                        dragHoldX = mouseX - shapes[i].x;
                        dragHoldY = mouseY - shapes[i].y;
                        highestIndex = i;
                        dragIndex = i;
                    }               
                }
            }

            if(dragging)
            {
                window.addEventListener("mousemove", mouseMoveListener, false);
            }

            myCanvas.removeEventListener("mousedown", mouseDownListener, false);
            window.addEventListener("mouseup", mouseUpListener, false);

            if(evt.preventDefault)
            {
                evt.preventDefault;
            }

            return false;
        }

        function mouseMoveListener(evt)
        {
            var shapeRad = shapes[dragIndex].rad;

            var minX = shapeRad;
            var maxX = myCanvas.width - shapeRad;

            var minY = shapeRad;
            var maxY = myCanvas.height - shapeRad;

            //get mouse position correctly
            var bRect = myCanvas.getBoundingClientRect();
            mouseX = (evt.clientX - bRect.left)*(myCanvas.width / bRect.width);
            mouseY = (evt.clientY - bRect.top)*(myCanvas.height / bRect.height);

            //clamp x and y position to prevent object from dragging outside canvas
            posX = mouseX - dragHoldX;
            posX = (posX < minX) ? minX : ((posX > maxX) ? maxX : posX);
            posY = mouseY - dragHoldY;      
            posY = (posY < minY) ? minY : ((posY > maxY) ? maxY : posY);

            shapes[dragIndex].x = posX;
            shapes[dragIndex].y = posY;

            drawScreen();       
        }

        function mouseUpListener(evt)
        {
            myCanvas.addEventListener("mousedown", mouseDownListener, false);
            window.removeEventListener("mouseup", mouseUpListener, false);

            if(dragging)
            {
                dragging = false;                                   
                window.removeEventListener("mousemove", mouseMoveListener, false);          
            }
        }

        function hitTest(shape, mx, my)
        {
            var dx = mx - shape.x;
            var dy = my - shape.y;

            return(dx * dx + dy * dy < shape.rad * shape.rad);
        }   

    </script>
</body>
</html>

  1. The following canvas animation creates nodes and edges. However due to space constraint, some of the nodes are not visible due to canvas height and width. Even adding overflow css to canvas dosen't help as i am not able to scroll.

解决方案

So your node drawings don't fit on the canvas size?

You can easily "shrink" your content to fit the visible canvas with just 1 command!

The context.scale(horizontalRescale,verticalRescale) command will shrink every following drawing by your specified horizontalRescale & verticalRescale percentages.

An Important note: You must make horizontalRescale,verticalRescale the same value or your content will be distorted.

The nice thing about using context.scale is that you don't have to change any of the code that draws your nodes ... canvas automatically scales all those nodes for you.

For example, this code will shrink your nodes to 80% of their original size:

var downscaleFactor= 0.80;

context.scale( downscaleFactor, downscaleFactor );

Rather than go through your 200+ lines of code, I leave it to you to calculate downscaleFactor.

这篇关于Html5画布垂直和水平滚动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆