我该如何使用javascript/jquery调整画布大小?
使用css函数并将其应用于画布元素来调整大小只会像拉伸图像一样拉伸内容。
如果不想出现拉伸的效果,应该怎么做呢?
我该如何使用javascript/jquery调整画布大小?
使用css函数并将其应用于画布元素来调整大小只会像拉伸图像一样拉伸内容。
如果不想出现拉伸的效果,应该怎么做呢?
创建一个绘图函数,并在需要时(如页面调整大小等)重新绘制。 试一下
确保设置context.canvas.width/height,而不是CSS的width/height。同时注意,设置宽高会清除画布。
我的写法:
(function(){
var c = $("#canvas"),
ctx = c[0].getContext('2d');
var draw = function(){
ctx.fillStyle = "#000";
ctx.fillRect(10,10,50,50);
};
$(function(){
// set width and height
ctx.canvas.height = 600;
ctx.canvas.width = 600;
// draw
draw();
// wait 2 seconds, repeate same process
setTimeout(function(){
ctx.canvas.height = 400;
ctx.canvas.width = 400;
draw();
}, 2000)
});
})();
(function($) {
$.fn.extend({
//Let the user resize the canvas to the size he/she wants
resizeCanvas: function(w, h) {
var c = $(this)[0]
c.width = w;
c.height = h
}
})
})(jQuery)
使用我创建的这个小函数来处理及时调整大小。 使用以下方式--
$("the canvas element id/class").resizeCanvas(desired width, desired height)
<canvas id="myCanvas" width="300" height="300" >
canvas {
border: 1px dotted black;
background: blue;
}
(function() {
// get the precentage of height and width of the cavas based on the height and width of the window
getPercentageOfWindow = function() {
var viewportSize = getViewportSize();
var canvasSize = getCanvastSize();
return {
x: canvasSize.width / (viewportSize.width - 10),
y: canvasSize.height / (viewportSize.height - 10)
};
};
//get the context of the canvas
getCanvasContext = function() {
return $("#myCanvas")[0].getContext('2d');
};
// get viewport size
getViewportSize = function() {
return {
height: window.innerHeight,
width: window.innerWidth
};
};
// get canvas size
getCanvastSize = function() {
var ctx = getCanvasContext();
return {
height: ctx.canvas.height,
width: ctx.canvas.width
};
};
// update canvas size
updateSizes = function() {
var viewportSize = getViewportSize();
var ctx = getCanvasContext();
ctx.canvas.height = viewportSize.height * percentage.y;
ctx.canvas.width = viewportSize.width * percentage.x;
};
var percentage = getPercentageOfWindow();
$(window).on('resize', function() {
updateSizes();
});
}());
$("canvas").width(number).height(number)
。 - ayyp