html5 - 拖动画布

Ami*_*mit 6 html5 drag-and-drop canvas

我有一个巨大的HTML5画布,我希望它像谷歌地图一样工作:用户可以拖动它,并始终只看到它的一小部分(屏幕的大小).它只呈现您可以在屏幕上看到的部分.我该怎么做?你有好主意吗?

小智 5

2个简单步骤:

  • 将画布放在div容器中overflow:hidden
  • 使用任何方法使您的画布可拖动(我将使用jQuery UI)

要遵循我的方法,您需要访问jQuery UI网站并下载任何版本的jQuery UI(您可以创建一个仅包含UI Core和Draggable Interaction的自定义版本.)

解压缩.zip文件并将'js'文件夹移动到您的页面目录.

将文件夹中包含的.js文件包含到您的页面中.

<head></head>-tags 之间放置以下代码以使您的画布可拖动:

<script type="text/javacript">
$(function() {
    $("#CanvasID").draggable();
});
</script>
Run Code Online (Sandbox Code Playgroud)

这是一个例子:

<!DOCTYPE>
<html>
<head>
<title>canvas test</title>

<script type="text/javascript" src="js/jquery-1.5.1.min.js"></script> <!-- include the jQuery framework -->
<script type="text/javascript" src="js/jquery-ui-1.8.11.custom.min.js"></script> <!-- include JQuery UI -->

<style type="text/css">
#box{
width: 400px;
height: 400px;
border:5px solid black;
overflow:hidden;
position:relative;
} /* Just some basic styling for demonstration purpose */
</style>

<script type="text/javascript">
window.onload = function() {
    var drawingCanvas = document.getElementById('myDrawing');
    // Check the element is in the DOM and the browser supports canvas
    if(drawingCanvas.getContext) {
        // Initaliase a 2-dimensional drawing context
        var context = drawingCanvas.getContext('2d');
        context.strokeStyle = "#000000";
        context.fillStyle = "#FFFF00";
        context.beginPath();
        context.arc(200,200,200,0,Math.PI*2,true);
        context.closePath();
        context.stroke();
        context.fill();
    } 
        // just a simple canvas
    $(function() {
        $( "#myDrawing" ).draggable();
    });
        // make the canvas draggable
}
</script> 

</head>
<body>

<div id="box">
<canvas id="myDrawing" width="800" height="800">
<p>Your browser doesn't support canvas.</p>
</canvas>
</div>

</body>
</html>
Run Code Online (Sandbox Code Playgroud)

希望这能让你顺利.

注意:这只是一个基本的例子.这仍然需要一些编辑.例如,用户可以将画布完全拖出视口(可能将画布约束到div可能会起作用?).但这应该是一个很好的起点.