- <!DOCTYPE html>
- <html xmlns="http://www.w3.org/1999/html">
- <head>
- <meta http-equiv="content-type" content="text/html; charset=utf-8"/>
- <title>demo</title>
- <script type="text/javascript" src="https://cdn.bootCSS.com/jquery/3.3.1/jquery.js"></script>
- <script type="text/javascript">
- function drawBg(context,width,height){
- context.beginPath();
- context.lineWidth="1";
- context.strokeStyle="#ccc";
- context.rect(0,0,width,height);
- context.stroke();
- }
- function draw(context,width,height,x,y){
- context.clearRect(0, 0,width,height);
- drawBg(context,width,height);
- context.beginPath();
- context.fillStyle="#ccc";
- context.rect(x,y,300,100);
- context.fill();
- }
- function init() {
- var $cvs1 = $('#cvs1');
- var x=0;
- var y=0;
- var context = $('#cvs1')[0].getContext('2d');
- draw(context,$('#cvs1').width(),$('#cvs1').height(),x,y);
- var isTouched = false;
- var oldX = -1;
- var oldY = -1;
- $cvs1.bind('mousedown', function(e) {
- isTouched = true;
- oldX = e.clientX;
- oldY = e.clientY;
- });
- $cvs1.bind('mousemove', function(e) {
- if (isTouched) {
- var deltaX = e.clientX - oldX;
- var deltaY = e.clientY - oldY;
- oldX = e.clientX;
- oldY = e.clientY;
- if(y>=0&&y<=500){
- y -= deltaY;
- }
- else if(y>500){
- y = 500;
- }
- else{
- y=0
- }
- draw(context,$('#cvs1').width(),$('#cvs1').height(),x,y);
- }
- });
- $cvs1.bind('mouseup', function(e) {
- isTouched = false;
- oldX = -1;
- oldY = -1;
- });
- };
- $(function() {
- init();
- });
- </script>
- </head>
- <body>
- <!-- <div id="div_cvs" style="position: relative;left:50px;top:50px;width: 400px;height: 300px;overflow: auto"> -->
- <canvas id="cvs1" width='800' height='600'></canvas>
- <!-- </div> -->
- </body>
- </html>
来源: http://www.qdfuns.com/article/18184/1933bed51296b0b675f9a91c4378306d.html