gpt4 book ai didi

html - 使用在 Canvas 上绘制的形状调整 html5 Canvas 的大小

转载 作者:太空宇宙 更新时间:2023-11-04 15:19:33 24 4
gpt4 key购买 nike

我在 html5 Canvas 上用一些硬编码像素绘制了形状。现在我想在调整 Canvas 宽度和高度时调整 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();

调整 Canvas 大小后,形状大小也应该发生变化(这里我想将 Canvas 大小最小化为 500x300)。

最佳答案

你应该使用变换矩阵。这里有教程https://developer.mozilla.org/en/Canvas_tutorial/Transformations

scale(x, y)

这是您需要的功能。这是一个带有您的代码示例的 JSFiddle

http://jsfiddle.net/peRxy/1/

代码:

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();
}​

关于html - 使用在 Canvas 上绘制的形状调整 html5 Canvas 的大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10800729/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com