我想使用百分比大小制作一个响应式画布,一旦用户调整窗口大小,画布就会相对调整。我可以使用下面的代码来缩放画布,但唯一的问题是当我缩放窗口大小时,鼠标绘图会消失。
<style>
body{margin:0px;padding:0px;background:#a9a9a9;}
#main{
display:block;
width:80%;
padding:50px 10%;
height:300px;
}
canvas{display:block;background:#fff;}
</style>
</head>
<body>
<div id="main" role="main">
<canvas id="paint" width="100" height="100">
< !-- Provide fallback -->
</canvas>
</div>
<script>
var c = document.getElementById('paint');
var ctx = c.getContext('2d');
var x = null;
var y;
c.onmousedown = function(e){
x = e.pageX - c.offsetLeft;
y = e.pageY - c.offsetTop;
ctx.beginPath();
ctx.moveTo(x,y);
}
c.onmouseup = function(e){
x=null;
}
c.onmousemove = function(e){
if(x==null) return;
x = e.pageX - c.offsetLeft;
y = e.pageY - c.offsetTop;
ctx.lineTo(x,y);
ctx.stroke();
}
$(document).ready( function(){
//Get the canvas &
var c = $('#paint');
var container = $(c).parent();
//Run function when browser resizes
$(window).resize( respondCanvas );
function respondCanvas(){
c.attr('width', $(container).width() ); //max width
c.attr('height', $(container).height() ); //max height
//Call a function to redraw other content (texts, images etc)
}
//Initial call
respondCanvas();
});
</script>
谢谢。