Canvas 矩形背景图片
Canvas rectangle background image
我想在 canvas 中将背景图像设置为我的矩形。
到目前为止我已经做到了。
var img = new Image()
img.src = //Source of an image.
var newPattern = ctx.createPattern(img, "no-repeat");
ctx.fillStyle = newPattern;
它有效,但问题是,它将图像应用到 canvas,而不是矩形。
每当我改变矩形的位置时,图像都保持在相同的位置。
任何人都可以建议如何解决这个问题,以便将图像附加到矩形上。
如果你只想在指定的矩形内绘制图像,你可以这样做。
context.rect(x, y, width, height);
context.clip();
context.drawImage(img, 0, 0);
这会在 (x, y) 处创建一个大小为 (width, height) 的矩形,用于以后对上下文的所有调用。如果你想停止剪辑,你需要添加一个
context.save();
在上面的代码之前然后是
context.restore();
画完图像后。
编辑:更新为 rect
我想在 canvas 中将背景图像设置为我的矩形。 到目前为止我已经做到了。
var img = new Image()
img.src = //Source of an image.
var newPattern = ctx.createPattern(img, "no-repeat");
ctx.fillStyle = newPattern;
它有效,但问题是,它将图像应用到 canvas,而不是矩形。
每当我改变矩形的位置时,图像都保持在相同的位置。
任何人都可以建议如何解决这个问题,以便将图像附加到矩形上。
如果你只想在指定的矩形内绘制图像,你可以这样做。
context.rect(x, y, width, height);
context.clip();
context.drawImage(img, 0, 0);
这会在 (x, y) 处创建一个大小为 (width, height) 的矩形,用于以后对上下文的所有调用。如果你想停止剪辑,你需要添加一个
context.save();
在上面的代码之前然后是
context.restore();
画完图像后。
编辑:更新为 rect