html5 - 拖动画布 [英] html5 - drag a canvas

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

问题描述

我有一个巨大的HTML5画布,我想它的工作像谷歌地图:用户可以拖动它,只看到它的一小部分(屏幕的大小)所有的时间。它只渲染您可以在屏幕上看到的部分。
我该怎么办呢?你有想法吗?

I have a huge HTML5 Canvas, and I want it to work like google maps: the user can drag it and see only a small part of it (the screen's size) all the time. it renders only the part you can see on the screen. how can I do it? do you have an idea?

推荐答案

2个简单步骤:


  • 将画布放置在 div 容器中,并且 overflow:hidden

  • 使用任何方法使您的画布可拖动(我将使用jQuery UI)

  • place the canvas inside a div container with overflow:hidden
  • use any method to make your canvas draggable (I will use jQuery UI)

要转到 jQuery UI 网站并下载任何版本的jQuery UI(您可以创建仅由UI组成的自定义版本

To follow my method you need to go to the jQuery UI website and download any version of the jQuery UI (you can create a custom version only consisting of the UI Core and Draggable Interaction for this example.)

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

Unpack the .zip file and move the 'js' folder to your page directory.

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

Inlcude the .js files contained in the folder into your page.

< head& < / head> -tags以使您的画布可拖动:

Place the following code between your <head></head>-tags to get your canvas draggable:

<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到div可以做的窍门?)。但这应该是一个好的起点。

这篇关于html5 - 拖动画布的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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