我在html5画布上绘制了一些带有一些硬编码像素的形状。现在我想在调整画布宽度和高度时调整drwan形状的大小。我的代码是:
var canvas = document.getElementById("myCanvas");
var context = canvas.getContext("2d");
context.moveTo(232, 158);
context.lineTo(314, 145);
context.lineTo(382, 134);
context.lineTo(491, 144);
context.lineTo(576, 154);
context.lineTo(512,170);
context.quadraticCurveTo(404, 152, 352, 160);
context.lineTo(304,168);
//context.stroke();
context.closePath();
context.fillStyle = xx_Lpattern;
context.fill();
context.beginPath();
context.moveTo(576, 154);
context.lineTo(670, 163);
context.lineTo(751, 174);
context.lineTo(748,236);
context.lineTo(606, 216);
context.quadraticCurveTo(705, 188, 576, 179);
context.lineTo(512,170)
//context.stroke();
context.closePath();
context.fillStyle = xx_Lpattern;
context.fill();
调整画布大小后,形状大小也应该更改(这里我想将画布大小最小化为500x300)。
答案 0 :(得分:5)
您应该使用转换矩阵。这是一个教程https://developer.mozilla.org/en/Canvas_tutorial/Transformations
scale(x, y)
这是您需要的功能。这里有一个带有代码示例的JSFiddle
代码:
var canvas = document.getElementById("myCanvas");
var context = canvas.getContext("2d");
var resizeFactor = 2;
drawMyWeirdShape();
canvas.width *= resizeFactor;
canvas.height *= resizeFactor;
context.scale(resizeFactor ,resizeFactor );
drawMyWeirdShape();
function drawMyWeirdShape() {
// this is your code for drawing your weird shape
context.moveTo(232, 158);
context.lineTo(314, 145);
context.lineTo(382, 134);
context.lineTo(491, 144);
context.lineTo(576, 154);
context.lineTo(512, 170);
context.quadraticCurveTo(404, 152, 352, 160);
context.lineTo(304, 168);
context.stroke();
context.closePath();
context.fill();
context.beginPath();
context.moveTo(576, 154);
context.lineTo(670, 163);
context.lineTo(751, 174);
context.lineTo(748, 236);
context.lineTo(606, 216);
context.quadraticCurveTo(705, 188, 576, 179);
context.lineTo(512, 170)
context.stroke();
context.closePath();
context.fill();
}