我有一个程序,可以通过鼠标拖动在画布上移动对象。然而,我希望画布适应屏幕大小。我不确定如何实现这一点。如果我将画布设置为"width:100%; height:100%;",那么对象就会超出范围。
<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" media="all" href="css/reset.css"/> <!-- reset css -->
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js">
</script>
<style>
body{ background-color: ivory; }
canvas{border:1px solid red;}
</style>
<script>
$(function(){
var img = new Image();
img.onload = function(){
ctx.drawImage(img, 0,0);
};
img.src = "http://images.christmastimeclipart.com/images/2/1271716593176_1788/img_1271716593176_17881.jpg";
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var canvasOffset=$("#canvas").offset();
var offsetX=canvasOffset.left;
var offsetY=canvasOffset.top;
var canvasWidth=canvas.width;
var canvasHeight=canvas.height;
var isDragging=false;
// functions to handle mouseup, mousedown, mousemove, mouseout events
$("#canvas").mousedown(function(e){handleMouseDown(e);});
$("#canvas").mousemove(function(e){handleMouseMove(e);});
$("#canvas").mouseup(function(e){handleMouseUp(e);});
$("#canvas").mouseout(function(e){handleMouseOut(e);});
}); // end $(function(){});
</script>
</head>
<body>
<canvas id="canvas" width=400 height=300></canvas>
</body>
</html>