I want to make a responsive canvas using size in percentage and once user will resize the window the canvas adjust relatively. I am able to scale the canvas by using below c
Thanks. it was really helpful. below is the code what i was trying to do.
#main{
display:block;
width:80%;
height:300px;
background:#e0e0e0;
}
canvas{display:block;background:#fff;border:1px solid red;}
</style>
<script>
$(function(){
var container=document.getElementById("main");
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
// draw some content
//alert(canvas.width);
var w=$(container).width();
var h=$(container).height();
$(window).resize( saveResizeAndRedisplay );
function saveResizeAndRedisplay(){
// save the canvas content as imageURL
var data=canvas.toDataURL();
// resize the canvas
canvas.width = $(container).width();
canvas.height = $(container).height();
//alert($(container).width());
// scale and redraw the canvas content
var img=new Image();
img.onload=function(){
ctx.drawImage(img,0,0,img.width,img.height);
}
img.src=data;
}
saveResizeAndRedisplay();
});
</script>
</head>
<body>
<div id="main" role="main">
<canvas id="canvas" width=200 height=150></canvas>
</div>
<script>
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
var x = null;
var y;
canvas.onmousedown = function(e){
x = e.pageX - canvas.offsetLeft;
y = e.pageY - canvas.offsetTop;
ctx.beginPath();
ctx.moveTo(x,y);
}
canvas.onmouseup = function(e){
x=null;
}
canvas.onmousemove = function(e){
if(x==null) return;
x = e.pageX - canvas.offsetLeft;
y = e.pageY - canvas.offsetTop;
ctx.lineTo(x,y);
ctx.stroke();
}
</script>