html5 - 拖动 Canvas

标签 html canvas drag-and-drop

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

最佳答案

2 个简单的步骤:

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

要遵循我的方法,您需要转到 jQuery UI网站并下载任何版本的 jQuery UI(对于此示例,您可以创建仅包含 UI Core 和 Draggable Interaction 的自定义版本。)

解压 .zip 文件并将“js”文件夹移动到您的页面目录。

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

将以下代码放在您的 <head></head> 之间- 使 Canvas 可拖动的标签:

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

这是一个例子:

<!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>

希望这能让你前进。

注意:这只是一个基本示例。这仍然需要一些编辑。例如,用户可以将 Canvas 完全拖出视口(viewport)(也许将 Canvas 限制在 div 上可以解决问题?)。但这应该是一个很好的起点。

关于html5 - 拖动 Canvas ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5685713/

相关文章:

javascript - 我如何在循环的 HTML5 视频上复制 'ended' 事件

jQuery 拖放可回流内容

c# - 在 MVVM 中适当处理 WPF Canvas (缩放)

objective-c - 在 UIView 之间拖动 UIView

javascript - 如何设置拖动元素的样式

javascript - 我面临一个问题,要确定此 textarea 值是 iframe 还是简单文本。有人能帮我吗?

javascript - 阻止了源为 "http://localhost:8084"的框架访问跨域框架

javascript - 检测点击任何子节点并在 JavaScript 中获取其 ID 属性

android - Canvas 剪裁矩形 - 包括右/底边?

javascript - 如何在canvas html5中渲染Socket数据?