【发布时间】:2019-12-12 19:33:26
【问题描述】:
我的画布有 4 个矩形,我想用图像填充每个矩形,例如 i1.png 画布已旋转并具有比例,当我旋转图像时,它们不在其位置上。我该如何解决?
代码:
<html>
<head>
<script src="jquery-3.4.1.js"></script>
</head>
<body bgcolor="black">
<canvas id="tutorial" width="500" height="500"></canvas>
<script type="text/javascript">
var canvas = document.getElementById("tutorial"),
ctx = canvas.getContext("2d"),
rects = [
{x: 0, y: 0, w: 100, h: 100},
{x: 0, y: 100, w: 100, h: 100},
{x: 100, y: 100, w: 100, h: 100},
{x: 100, y: 0, w: 100, h: 100}
],
i = 0,
r;
ctx.translate(500, 500);
ctx.scale(0.71, 0.3834);
ctx.rotate(-0.25 * Math.PI);
canvas.onmousemove = function(e) {
var rect = this.getBoundingClientRect(),
x = e.clientX - rect.left,
y = e.clientY - rect.top,
i = 0,
r;
ctx.clearRect(0, 0, canvas.width, canvas.height);
while (r = rects[i++]) {
ctx.beginPath();
ctx.rect(r.x, r.y, r.w, r.h);
ctx.fillStyle = "#c5de89";
ctx.fill();
if(ctx.isPointInPath(x, y)) {
ctx.strokeStyle = "white";
ctx.lineWidth = 5;
ctx.strokeRect(r.x + 5, r.y + 5, r.w - 10, r.h - 10);
ctx.save();
base_image = new Image();
base_image.src = 'https://i.stack.imgur.com/D3HBL.png';
ctx.rotate(0.25 * Math.PI);
//console.log(base_image.width);
ctx.drawImage(base_image, 0, 0, base_image.width, base_image.height , r.x , r.y , r.w , r.h);
ctx.restore()
} else {
ctx.fillStyle = "#c5de89";
}
ctx.save();
ctx.restore()
}
};
</script>
</body>
</html>
我的代码结果:
我想像这样填充我的矩形:
这是我们用于此示例的 i1.png:
更多细节(编辑):
我正在尝试创建游戏地图,实际上他们创建了一个画布并 旋转那个。我想在没有任何旋转的情况下附加我的图像 矩形。我认为形状并不重要,我只想设置一个图像 到每个没有旋转的矩形,当我这样做时,它们不再是 在他们的位置!看第二张照片,我想创造类似的东西 这。我希望这张图片能说明目的,我们拆分了每张地图 阻止 i.stack.imgur.com/kFN6G.jpg ,不要考虑我的代码,认为我们 想在我们的形状上添加一个图像层!
【问题讨论】:
-
在某一时刻,您在 save()、rotate() 和 restore() 之间没有实际进行任何绘图操作。那段代码的预期目的是什么?
-
@scg 该部分是额外的,在测试期间编写,您可以跳过它。
-
好的。这绝不是关键,但如果您可以从示例中删除任何此类多余的代码,对读者来说可能会更容易。这样我们就不必试图弄清楚什么是相关的,什么不是相关的。
-
@Rishab 你能帮我解决这个问题吗
-
@Rmanx77,请创建正确的minimal-reproducible-example 并删除其他不必要的东西。您的问题、代码和预期输出似乎彼此不一致。
i created 4 rects and i want to fill them with an image for background of rectangles but i don't know how to set them.感觉您想在旋转的平行四边形内插入一个矩形图像。您发布的代码的输出是 4 个旋转的平行四边形,但my code的图像已经包含该图像。What I want图片与您的要求不同。
标签: javascript jquery html canvas